diff --git a/.gitignore b/.gitignore index ef7d038..416367f 100644 --- a/.gitignore +++ b/.gitignore @@ -72,4 +72,5 @@ examples/secrets.py # Environment variables .env -.env.* \ No newline at end of file +.env.* +api_key_config.json \ No newline at end of file diff --git a/.openapi-generator/FILES b/.openapi-generator/FILES index 2f225cd..ce3ea80 100644 --- a/.openapi-generator/FILES +++ b/.openapi-generator/FILES @@ -1,6 +1,7 @@ docs/Account.md docs/AccountApi.md docs/AccountApiKeys.md +docs/AccountAsset.md docs/AccountLimits.md docs/AccountMarginStats.md docs/AccountMarketStats.md @@ -14,16 +15,17 @@ docs/Announcement.md docs/AnnouncementApi.md docs/Announcements.md docs/ApiKey.md -docs/Block.md -docs/BlockApi.md -docs/Blocks.md +docs/ApiToken.md +docs/Asset.md +docs/AssetDetails.md +docs/Auth.md +docs/Bridge.md docs/BridgeApi.md docs/BridgeSupportedNetwork.md -docs/Candlestick.md +docs/Candle.md +docs/Candles.md docs/CandlestickApi.md -docs/Candlesticks.md docs/ContractAddress.md -docs/CurrentHeight.md docs/Cursor.md docs/DailyReturn.md docs/DepositHistory.md @@ -46,31 +48,29 @@ docs/LiqTrade.md docs/Liquidation.md docs/LiquidationInfo.md docs/LiquidationInfos.md -docs/MarketInfo.md +docs/MarketConfig.md docs/NextNonce.md docs/NotificationApi.md docs/Order.md docs/OrderApi.md docs/OrderBook.md docs/OrderBookDepth.md -docs/OrderBookDetail.md +docs/OrderBookDepthWithBeginNonce.md docs/OrderBookDetails.md docs/OrderBookOrders.md docs/OrderBookStats.md docs/OrderBooks.md docs/Orders.md +docs/PerpsMarketStats.md +docs/PerpsOrderBookDetail.md docs/PnLEntry.md docs/PositionFunding.md docs/PositionFundings.md docs/PriceLevel.md -docs/PublicPool.md docs/PublicPoolInfo.md docs/PublicPoolMetadata.md docs/PublicPoolShare.md -docs/PublicPools.md -docs/ReferralApi.md -docs/ReferralPointEntry.md -docs/ReferralPoints.md +docs/ReqDoFaucet.md docs/ReqExportData.md docs/ReqGetAccount.md docs/ReqGetAccountActiveOrders.md @@ -81,10 +81,13 @@ docs/ReqGetAccountLimits.md docs/ReqGetAccountMetadata.md docs/ReqGetAccountPnL.md docs/ReqGetAccountTxs.md +docs/ReqGetApiTokens.md +docs/ReqGetAssetDetails.md docs/ReqGetBlock.md docs/ReqGetBlockTxs.md +docs/ReqGetBridgesByL1Addr.md docs/ReqGetByAccount.md -docs/ReqGetCandlesticks.md +docs/ReqGetCandles.md docs/ReqGetDepositHistory.md docs/ReqGetFastWithdrawInfo.md docs/ReqGetFundings.md @@ -97,21 +100,25 @@ docs/ReqGetOrderBookDetails.md docs/ReqGetOrderBookOrders.md docs/ReqGetOrderBooks.md docs/ReqGetPositionFunding.md -docs/ReqGetPublicPools.md docs/ReqGetPublicPoolsMetadata.md docs/ReqGetRangeWithCursor.md docs/ReqGetRangeWithIndex.md docs/ReqGetRangeWithIndexSortable.md docs/ReqGetRecentTrades.md -docs/ReqGetReferralPoints.md docs/ReqGetTrades.md docs/ReqGetTransferFeeInfo.md docs/ReqGetTransferHistory.md docs/ReqGetTx.md docs/ReqGetWithdrawHistory.md docs/RespChangeAccountTier.md +docs/RespGetApiTokens.md +docs/RespGetBridgesByL1Addr.md docs/RespGetFastBridgeInfo.md +docs/RespGetFastwithdrawalInfo.md +docs/RespGetIsNextBridgeFast.md +docs/RespPostApiToken.md docs/RespPublicPoolsMetadata.md +docs/RespRevokeApiToken.md docs/RespSendTx.md docs/RespSendTxBatch.md docs/RespWithdrawalDelay.md @@ -121,6 +128,8 @@ docs/RiskParameters.md docs/RootApi.md docs/SharePrice.md docs/SimpleOrder.md +docs/SpotMarketStats.md +docs/SpotOrderBookDetail.md docs/Status.md docs/SubAccounts.md docs/Ticker.md @@ -130,10 +139,8 @@ docs/TransactionApi.md docs/TransferFeeInfo.md docs/TransferHistory.md docs/TransferHistoryItem.md -docs/Tx.md docs/TxHash.md docs/TxHashes.md -docs/Txs.md docs/ValidatorInfo.md docs/WithdrawHistory.md docs/WithdrawHistoryItem.md @@ -143,14 +150,12 @@ lighter/__init__.py lighter/api/__init__.py lighter/api/account_api.py lighter/api/announcement_api.py -lighter/api/block_api.py lighter/api/bridge_api.py lighter/api/candlestick_api.py lighter/api/funding_api.py lighter/api/info_api.py lighter/api/notification_api.py lighter/api/order_api.py -lighter/api/referral_api.py lighter/api/root_api.py lighter/api/transaction_api.py lighter/api_client.py @@ -160,6 +165,7 @@ lighter/exceptions.py lighter/models/__init__.py lighter/models/account.py lighter/models/account_api_keys.py +lighter/models/account_asset.py lighter/models/account_limits.py lighter/models/account_margin_stats.py lighter/models/account_market_stats.py @@ -172,13 +178,15 @@ lighter/models/account_trade_stats.py lighter/models/announcement.py lighter/models/announcements.py lighter/models/api_key.py -lighter/models/block.py -lighter/models/blocks.py +lighter/models/api_token.py +lighter/models/asset.py +lighter/models/asset_details.py +lighter/models/auth.py +lighter/models/bridge.py lighter/models/bridge_supported_network.py -lighter/models/candlestick.py -lighter/models/candlesticks.py +lighter/models/candle.py +lighter/models/candles.py lighter/models/contract_address.py -lighter/models/current_height.py lighter/models/cursor.py lighter/models/daily_return.py lighter/models/deposit_history.py @@ -199,28 +207,27 @@ lighter/models/liq_trade.py lighter/models/liquidation.py lighter/models/liquidation_info.py lighter/models/liquidation_infos.py -lighter/models/market_info.py +lighter/models/market_config.py lighter/models/next_nonce.py lighter/models/order.py lighter/models/order_book.py lighter/models/order_book_depth.py -lighter/models/order_book_detail.py +lighter/models/order_book_depth_with_begin_nonce.py lighter/models/order_book_details.py lighter/models/order_book_orders.py lighter/models/order_book_stats.py lighter/models/order_books.py lighter/models/orders.py +lighter/models/perps_market_stats.py +lighter/models/perps_order_book_detail.py lighter/models/pn_l_entry.py lighter/models/position_funding.py lighter/models/position_fundings.py lighter/models/price_level.py -lighter/models/public_pool.py lighter/models/public_pool_info.py lighter/models/public_pool_metadata.py lighter/models/public_pool_share.py -lighter/models/public_pools.py -lighter/models/referral_point_entry.py -lighter/models/referral_points.py +lighter/models/req_do_faucet.py lighter/models/req_export_data.py lighter/models/req_get_account.py lighter/models/req_get_account_active_orders.py @@ -231,10 +238,13 @@ lighter/models/req_get_account_limits.py lighter/models/req_get_account_metadata.py lighter/models/req_get_account_pn_l.py lighter/models/req_get_account_txs.py +lighter/models/req_get_api_tokens.py +lighter/models/req_get_asset_details.py lighter/models/req_get_block.py lighter/models/req_get_block_txs.py +lighter/models/req_get_bridges_by_l1_addr.py lighter/models/req_get_by_account.py -lighter/models/req_get_candlesticks.py +lighter/models/req_get_candles.py lighter/models/req_get_deposit_history.py lighter/models/req_get_fast_withdraw_info.py lighter/models/req_get_fundings.py @@ -247,21 +257,25 @@ lighter/models/req_get_order_book_details.py lighter/models/req_get_order_book_orders.py lighter/models/req_get_order_books.py lighter/models/req_get_position_funding.py -lighter/models/req_get_public_pools.py lighter/models/req_get_public_pools_metadata.py lighter/models/req_get_range_with_cursor.py lighter/models/req_get_range_with_index.py lighter/models/req_get_range_with_index_sortable.py lighter/models/req_get_recent_trades.py -lighter/models/req_get_referral_points.py lighter/models/req_get_trades.py lighter/models/req_get_transfer_fee_info.py lighter/models/req_get_transfer_history.py lighter/models/req_get_tx.py lighter/models/req_get_withdraw_history.py lighter/models/resp_change_account_tier.py +lighter/models/resp_get_api_tokens.py +lighter/models/resp_get_bridges_by_l1_addr.py lighter/models/resp_get_fast_bridge_info.py +lighter/models/resp_get_fastwithdrawal_info.py +lighter/models/resp_get_is_next_bridge_fast.py +lighter/models/resp_post_api_token.py lighter/models/resp_public_pools_metadata.py +lighter/models/resp_revoke_api_token.py lighter/models/resp_send_tx.py lighter/models/resp_send_tx_batch.py lighter/models/resp_withdrawal_delay.py @@ -270,6 +284,8 @@ lighter/models/risk_info.py lighter/models/risk_parameters.py lighter/models/share_price.py lighter/models/simple_order.py +lighter/models/spot_market_stats.py +lighter/models/spot_order_book_detail.py lighter/models/status.py lighter/models/sub_accounts.py lighter/models/ticker.py @@ -278,10 +294,8 @@ lighter/models/trades.py lighter/models/transfer_fee_info.py lighter/models/transfer_history.py lighter/models/transfer_history_item.py -lighter/models/tx.py lighter/models/tx_hash.py lighter/models/tx_hashes.py -lighter/models/txs.py lighter/models/validator_info.py lighter/models/withdraw_history.py lighter/models/withdraw_history_item.py diff --git a/README.md b/README.md index 607ade1..ef57fd3 100644 --- a/README.md +++ b/README.md @@ -36,9 +36,12 @@ import asyncio async def main(): client = lighter.ApiClient() - account_api = lighter.AccountApi(client) - account = await account_api.get_account(by="index", value="1") - print(account) + try: + account_api = lighter.AccountApi(client) + account = await account_api.account(by="index", value="1") + print(account) + finally: + await client.close() # Make sure connection is cleanly closed if __name__ == "__main__": asyncio.run(main()) @@ -71,11 +74,6 @@ Class | Method | HTTP request | Description *AccountApi* | [**accounts_by_l1_address**](docs/AccountApi.md#accounts_by_l1_address) | **GET** /api/v1/accountsByL1Address | accountsByL1Address *AccountApi* | [**apikeys**](docs/AccountApi.md#apikeys) | **GET** /api/v1/apikeys | apikeys *AccountApi* | [**pnl**](docs/AccountApi.md#pnl) | **GET** /api/v1/pnl | pnl -*AccountApi* | [**public_pools**](docs/AccountApi.md#public_pools) | **GET** /api/v1/publicPools | publicPools -*BlockApi* | [**block**](docs/BlockApi.md#block) | **GET** /api/v1/block | block -*BlockApi* | [**blocks**](docs/BlockApi.md#blocks) | **GET** /api/v1/blocks | blocks -*BlockApi* | [**current_height**](docs/BlockApi.md#current_height) | **GET** /api/v1/currentHeight | currentHeight -*CandlestickApi* | [**candlesticks**](docs/CandlestickApi.md#candlesticks) | **GET** /api/v1/candlesticks | candlesticks *CandlestickApi* | [**fundings**](docs/CandlestickApi.md#fundings) | **GET** /api/v1/fundings | fundings *OrderApi* | [**account_inactive_orders**](docs/OrderApi.md#account_inactive_orders) | **GET** /api/v1/accountInactiveOrders | accountInactiveOrders *OrderApi* | [**exchange_stats**](docs/OrderApi.md#exchange_stats) | **GET** /api/v1/exchangeStats | exchangeStats @@ -86,13 +84,10 @@ Class | Method | HTTP request | Description *OrderApi* | [**trades**](docs/OrderApi.md#trades) | **GET** /api/v1/trades | trades *RootApi* | [**info**](docs/RootApi.md#info) | **GET** /info | info *RootApi* | [**status**](docs/RootApi.md#status) | **GET** / | status -*TransactionApi* | [**account_txs**](docs/TransactionApi.md#account_txs) | **GET** /api/v1/accountTxs | accountTxs -*TransactionApi* | [**block_txs**](docs/TransactionApi.md#block_txs) | **GET** /api/v1/blockTxs | blockTxs *TransactionApi* | [**deposit_history**](docs/TransactionApi.md#deposit_history) | **GET** /api/v1/deposit/history | deposit_history *TransactionApi* | [**next_nonce**](docs/TransactionApi.md#next_nonce) | **GET** /api/v1/nextNonce | nextNonce *TransactionApi* | [**send_tx**](docs/TransactionApi.md#send_tx) | **POST** /api/v1/sendTx | sendTx *TransactionApi* | [**send_tx_batch**](docs/TransactionApi.md#send_tx_batch) | **POST** /api/v1/sendTxBatch | sendTxBatch -*TransactionApi* | [**tx**](docs/TransactionApi.md#tx) | **GET** /api/v1/tx | tx *TransactionApi* | [**tx_from_l1_tx_hash**](docs/TransactionApi.md#tx_from_l1_tx_hash) | **GET** /api/v1/txFromL1TxHash | txFromL1TxHash *TransactionApi* | [**txs**](docs/TransactionApi.md#txs) | **GET** /api/v1/txs | txs *TransactionApi* | [**withdraw_history**](docs/TransactionApi.md#withdraw_history) | **GET** /api/v1/withdraw/history | withdraw_history @@ -108,13 +103,8 @@ Class | Method | HTTP request | Description - [AccountPosition](docs/AccountPosition.md) - [AccountStats](docs/AccountStats.md) - [ApiKey](docs/ApiKey.md) - - [Block](docs/Block.md) - - [Blocks](docs/Blocks.md) - [BridgeSupportedNetwork](docs/BridgeSupportedNetwork.md) - - [Candlestick](docs/Candlestick.md) - - [Candlesticks](docs/Candlesticks.md) - [ContractAddress](docs/ContractAddress.md) - - [CurrentHeight](docs/CurrentHeight.md) - [Cursor](docs/Cursor.md) - [DepositHistory](docs/DepositHistory.md) - [DepositHistoryItem](docs/DepositHistoryItem.md) @@ -178,10 +168,8 @@ Class | Method | HTTP request | Description - [Ticker](docs/Ticker.md) - [Trade](docs/Trade.md) - [Trades](docs/Trades.md) - - [Tx](docs/Tx.md) - [TxHash](docs/TxHash.md) - [TxHashes](docs/TxHashes.md) - - [Txs](docs/Txs.md) - [ValidatorInfo](docs/ValidatorInfo.md) - [WithdrawHistory](docs/WithdrawHistory.md) - [WithdrawHistoryItem](docs/WithdrawHistoryItem.md) diff --git a/docs/Account.md b/docs/Account.md index 173acf4..6937475 100644 --- a/docs/Account.md +++ b/docs/Account.md @@ -17,6 +17,7 @@ Name | Type | Description | Notes **available_balance** | **str** | | **status** | **int** | | **collateral** | **str** | | +**transaction_time** | **int** | | ## Example diff --git a/docs/AccountApi.md b/docs/AccountApi.md index 9e90478..50fb542 100644 --- a/docs/AccountApi.md +++ b/docs/AccountApi.md @@ -10,12 +10,15 @@ Method | HTTP request | Description [**accounts_by_l1_address**](AccountApi.md#accounts_by_l1_address) | **GET** /api/v1/accountsByL1Address | accountsByL1Address [**apikeys**](AccountApi.md#apikeys) | **GET** /api/v1/apikeys | apikeys [**change_account_tier**](AccountApi.md#change_account_tier) | **POST** /api/v1/changeAccountTier | changeAccountTier +[**faucet**](AccountApi.md#faucet) | **GET** /api/v1/faucet | faucet [**l1_metadata**](AccountApi.md#l1_metadata) | **GET** /api/v1/l1Metadata | l1Metadata [**liquidations**](AccountApi.md#liquidations) | **GET** /api/v1/liquidations | liquidations [**pnl**](AccountApi.md#pnl) | **GET** /api/v1/pnl | pnl [**position_funding**](AccountApi.md#position_funding) | **GET** /api/v1/positionFunding | positionFunding -[**public_pools**](AccountApi.md#public_pools) | **GET** /api/v1/publicPools | publicPools [**public_pools_metadata**](AccountApi.md#public_pools_metadata) | **GET** /api/v1/publicPoolsMetadata | publicPoolsMetadata +[**tokens**](AccountApi.md#tokens) | **GET** /api/v1/tokens | tokens +[**tokens_create**](AccountApi.md#tokens_create) | **POST** /api/v1/tokens/create | tokens_create +[**tokens_revoke**](AccountApi.md#tokens_revoke) | **POST** /api/v1/tokens/revoke | tokens_revoke # **account** @@ -452,6 +455,77 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **faucet** +> ResultCode faucet(l1_address, do_l1_transfer) + +faucet + +Request funds from faucet + +### Example + + +```python +import lighter +from lighter.models.result_code import ResultCode +from lighter.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai +# See configuration.py for a list of all supported configuration parameters. +configuration = lighter.Configuration( + host = "https://mainnet.zklighter.elliot.ai" +) + + +# Enter a context with an instance of the API client +async with lighter.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = lighter.AccountApi(api_client) + l1_address = 'l1_address_example' # str | + do_l1_transfer = False # bool | (default to False) + + try: + # faucet + api_response = await api_instance.faucet(l1_address, do_l1_transfer) + print("The response of AccountApi->faucet:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling AccountApi->faucet: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **l1_address** | **str**| | + **do_l1_transfer** | **bool**| | [default to False] + +### Return type + +[**ResultCode**](ResultCode.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | A successful response. | - | +**400** | Bad request | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **l1_metadata** > L1Metadata l1_metadata(l1_address, authorization=authorization, auth=auth) @@ -637,8 +711,8 @@ async with lighter.ApiClient(configuration) as api_client: start_timestamp = 56 # int | end_timestamp = 56 # int | count_back = 56 # int | - authorization = 'authorization_example' # str | (optional) - auth = 'auth_example' # str | (optional) + authorization = 'authorization_example' # str | make required after integ is done (optional) + auth = 'auth_example' # str | made optional to support header auth clients (optional) ignore_transfers = False # bool | (optional) (default to False) try: @@ -663,8 +737,8 @@ Name | Type | Description | Notes **start_timestamp** | **int**| | **end_timestamp** | **int**| | **count_back** | **int**| | - **authorization** | **str**| | [optional] - **auth** | **str**| | [optional] + **authorization** | **str**| make required after integ is done | [optional] + **auth** | **str**| made optional to support header auth clients | [optional] **ignore_transfers** | **bool**| | [optional] [default to False] ### Return type @@ -718,8 +792,8 @@ async with lighter.ApiClient(configuration) as api_client: api_instance = lighter.AccountApi(api_client) account_index = 56 # int | limit = 56 # int | - authorization = 'authorization_example' # str | (optional) - auth = 'auth_example' # str | (optional) + authorization = 'authorization_example' # str | make required after integ is done (optional) + auth = 'auth_example' # str | made optional to support header auth clients (optional) market_id = 255 # int | (optional) (default to 255) cursor = 'cursor_example' # str | (optional) side = all # str | (optional) (default to all) @@ -742,8 +816,8 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **account_index** | **int**| | **limit** | **int**| | - **authorization** | **str**| | [optional] - **auth** | **str**| | [optional] + **authorization** | **str**| make required after integ is done | [optional] + **auth** | **str**| made optional to support header auth clients | [optional] **market_id** | **int**| | [optional] [default to 255] **cursor** | **str**| | [optional] **side** | **str**| | [optional] [default to all] @@ -770,19 +844,19 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) -# **public_pools** -> PublicPools public_pools(index, limit, authorization=authorization, auth=auth, filter=filter, account_index=account_index) +# **public_pools_metadata** +> RespPublicPoolsMetadata public_pools_metadata(index, limit, authorization=authorization, auth=auth, filter=filter, account_index=account_index) -publicPools +publicPoolsMetadata -Get public pools +Get public pools metadata ### Example ```python import lighter -from lighter.models.public_pools import PublicPools +from lighter.models.resp_public_pools_metadata import RespPublicPoolsMetadata from lighter.rest import ApiException from pprint import pprint @@ -799,18 +873,18 @@ async with lighter.ApiClient(configuration) as api_client: api_instance = lighter.AccountApi(api_client) index = 56 # int | limit = 56 # int | - authorization = 'authorization_example' # str | (optional) - auth = 'auth_example' # str | (optional) + authorization = 'authorization_example' # str | make required after integ is done (optional) + auth = 'auth_example' # str | made optional to support header auth clients (optional) filter = 'filter_example' # str | (optional) account_index = 56 # int | (optional) try: - # publicPools - api_response = await api_instance.public_pools(index, limit, authorization=authorization, auth=auth, filter=filter, account_index=account_index) - print("The response of AccountApi->public_pools:\n") + # publicPoolsMetadata + api_response = await api_instance.public_pools_metadata(index, limit, authorization=authorization, auth=auth, filter=filter, account_index=account_index) + print("The response of AccountApi->public_pools_metadata:\n") pprint(api_response) except Exception as e: - print("Exception when calling AccountApi->public_pools: %s\n" % e) + print("Exception when calling AccountApi->public_pools_metadata: %s\n" % e) ``` @@ -822,14 +896,14 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **index** | **int**| | **limit** | **int**| | - **authorization** | **str**| | [optional] - **auth** | **str**| | [optional] + **authorization** | **str**| make required after integ is done | [optional] + **auth** | **str**| made optional to support header auth clients | [optional] **filter** | **str**| | [optional] **account_index** | **int**| | [optional] ### Return type -[**PublicPools**](PublicPools.md) +[**RespPublicPoolsMetadata**](RespPublicPoolsMetadata.md) ### Authorization @@ -849,19 +923,19 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) -# **public_pools_metadata** -> RespPublicPoolsMetadata public_pools_metadata(index, limit, authorization=authorization, auth=auth, filter=filter, account_index=account_index) +# **tokens** +> RespGetApiTokens tokens(account_index, authorization=authorization) -publicPoolsMetadata +tokens -Get public pools metadata +Get api tokens of an account ### Example ```python import lighter -from lighter.models.resp_public_pools_metadata import RespPublicPoolsMetadata +from lighter.models.resp_get_api_tokens import RespGetApiTokens from lighter.rest import ApiException from pprint import pprint @@ -876,20 +950,91 @@ configuration = lighter.Configuration( async with lighter.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = lighter.AccountApi(api_client) - index = 56 # int | - limit = 56 # int | + account_index = 56 # int | + authorization = 'authorization_example' # str | make required after integ is done (optional) + + try: + # tokens + api_response = await api_instance.tokens(account_index, authorization=authorization) + print("The response of AccountApi->tokens:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling AccountApi->tokens: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **account_index** | **int**| | + **authorization** | **str**| make required after integ is done | [optional] + +### Return type + +[**RespGetApiTokens**](RespGetApiTokens.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | A successful response. | - | +**400** | Bad request | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **tokens_create** +> RespPostApiToken tokens_create(name, account_index, expiry, sub_account_access, authorization=authorization, scopes=scopes) + +tokens_create + +Create api token + +### Example + + +```python +import lighter +from lighter.models.resp_post_api_token import RespPostApiToken +from lighter.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai +# See configuration.py for a list of all supported configuration parameters. +configuration = lighter.Configuration( + host = "https://mainnet.zklighter.elliot.ai" +) + + +# Enter a context with an instance of the API client +async with lighter.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = lighter.AccountApi(api_client) + name = 'name_example' # str | + account_index = 56 # int | + expiry = 56 # int | + sub_account_access = True # bool | authorization = 'authorization_example' # str | (optional) - auth = 'auth_example' # str | (optional) - filter = 'filter_example' # str | (optional) - account_index = 56 # int | (optional) + scopes = 'read.*' # str | (optional) (default to 'read.*') try: - # publicPoolsMetadata - api_response = await api_instance.public_pools_metadata(index, limit, authorization=authorization, auth=auth, filter=filter, account_index=account_index) - print("The response of AccountApi->public_pools_metadata:\n") + # tokens_create + api_response = await api_instance.tokens_create(name, account_index, expiry, sub_account_access, authorization=authorization, scopes=scopes) + print("The response of AccountApi->tokens_create:\n") pprint(api_response) except Exception as e: - print("Exception when calling AccountApi->public_pools_metadata: %s\n" % e) + print("Exception when calling AccountApi->tokens_create: %s\n" % e) ``` @@ -899,16 +1044,16 @@ async with lighter.ApiClient(configuration) as api_client: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **index** | **int**| | - **limit** | **int**| | + **name** | **str**| | + **account_index** | **int**| | + **expiry** | **int**| | + **sub_account_access** | **bool**| | **authorization** | **str**| | [optional] - **auth** | **str**| | [optional] - **filter** | **str**| | [optional] - **account_index** | **int**| | [optional] + **scopes** | **str**| | [optional] [default to 'read.*'] ### Return type -[**RespPublicPoolsMetadata**](RespPublicPoolsMetadata.md) +[**RespPostApiToken**](RespPostApiToken.md) ### Authorization @@ -916,7 +1061,80 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | A successful response. | - | +**400** | Bad request | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **tokens_revoke** +> RespRevokeApiToken tokens_revoke(token_id, account_index, authorization=authorization) + +tokens_revoke + +Revoke api token + +### Example + + +```python +import lighter +from lighter.models.resp_revoke_api_token import RespRevokeApiToken +from lighter.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai +# See configuration.py for a list of all supported configuration parameters. +configuration = lighter.Configuration( + host = "https://mainnet.zklighter.elliot.ai" +) + + +# Enter a context with an instance of the API client +async with lighter.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = lighter.AccountApi(api_client) + token_id = 56 # int | + account_index = 56 # int | + authorization = 'authorization_example' # str | (optional) + + try: + # tokens_revoke + api_response = await api_instance.tokens_revoke(token_id, account_index, authorization=authorization) + print("The response of AccountApi->tokens_revoke:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling AccountApi->tokens_revoke: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **token_id** | **int**| | + **account_index** | **int**| | + **authorization** | **str**| | [optional] + +### Return type + +[**RespRevokeApiToken**](RespRevokeApiToken.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data - **Accept**: application/json ### HTTP response details diff --git a/docs/AccountAsset.md b/docs/AccountAsset.md new file mode 100644 index 0000000..45956b9 --- /dev/null +++ b/docs/AccountAsset.md @@ -0,0 +1,32 @@ +# AccountAsset + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**symbol** | **str** | | +**asset_id** | **int** | | +**balance** | **str** | | +**locked_balance** | **str** | | + +## Example + +```python +from lighter.models.account_asset import AccountAsset + +# TODO update the JSON string below +json = "{}" +# create an instance of AccountAsset from a JSON string +account_asset_instance = AccountAsset.from_json(json) +# print the JSON string representation of the object +print(AccountAsset.to_json()) + +# convert the object into a dict +account_asset_dict = account_asset_instance.to_dict() +# create an instance of AccountAsset from a dict +account_asset_from_dict = AccountAsset.from_dict(account_asset_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/AccountLimits.md b/docs/AccountLimits.md index 0ca7ba2..f19b1a0 100644 --- a/docs/AccountLimits.md +++ b/docs/AccountLimits.md @@ -8,7 +8,9 @@ Name | Type | Description | Notes **code** | **int** | | **message** | **str** | | [optional] **max_llp_percentage** | **int** | | +**max_llp_amount** | **str** | | **user_tier** | **str** | | +**can_create_public_pool** | **bool** | | ## Example diff --git a/docs/Announcement.md b/docs/Announcement.md index 271e6d9..3cb4b46 100644 --- a/docs/Announcement.md +++ b/docs/Announcement.md @@ -8,6 +8,7 @@ Name | Type | Description | Notes **title** | **str** | | **content** | **str** | | **created_at** | **int** | | +**expired_at** | **int** | | ## Example diff --git a/docs/ApiKey.md b/docs/ApiKey.md index 76850fa..242aad1 100644 --- a/docs/ApiKey.md +++ b/docs/ApiKey.md @@ -9,6 +9,7 @@ Name | Type | Description | Notes **api_key_index** | **int** | | **nonce** | **int** | | **public_key** | **str** | | +**transaction_time** | **int** | | ## Example diff --git a/docs/ApiToken.md b/docs/ApiToken.md new file mode 100644 index 0000000..6222603 --- /dev/null +++ b/docs/ApiToken.md @@ -0,0 +1,36 @@ +# ApiToken + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**token_id** | **int** | | +**api_token** | **str** | | +**name** | **str** | | +**account_index** | **int** | | +**expiry** | **int** | | +**sub_account_access** | **bool** | | +**revoked** | **bool** | | +**scopes** | **str** | | + +## Example + +```python +from lighter.models.api_token import ApiToken + +# TODO update the JSON string below +json = "{}" +# create an instance of ApiToken from a JSON string +api_token_instance = ApiToken.from_json(json) +# print the JSON string representation of the object +print(ApiToken.to_json()) + +# convert the object into a dict +api_token_dict = api_token_instance.to_dict() +# create an instance of ApiToken from a dict +api_token_from_dict = ApiToken.from_dict(api_token_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/Asset.md b/docs/Asset.md new file mode 100644 index 0000000..1987347 --- /dev/null +++ b/docs/Asset.md @@ -0,0 +1,37 @@ +# Asset + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**asset_id** | **int** | | +**symbol** | **str** | | +**l1_decimals** | **int** | | +**decimals** | **int** | | +**min_transfer_amount** | **str** | | +**min_withdrawal_amount** | **str** | | +**margin_mode** | **str** | | +**index_price** | **str** | | +**l1_address** | **str** | | + +## Example + +```python +from lighter.models.asset import Asset + +# TODO update the JSON string below +json = "{}" +# create an instance of Asset from a JSON string +asset_instance = Asset.from_json(json) +# print the JSON string representation of the object +print(Asset.to_json()) + +# convert the object into a dict +asset_dict = asset_instance.to_dict() +# create an instance of Asset from a dict +asset_from_dict = Asset.from_dict(asset_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/CurrentHeight.md b/docs/AssetDetails.md similarity index 53% rename from docs/CurrentHeight.md rename to docs/AssetDetails.md index f790bae..df406f7 100644 --- a/docs/CurrentHeight.md +++ b/docs/AssetDetails.md @@ -1,4 +1,4 @@ -# CurrentHeight +# AssetDetails ## Properties @@ -7,24 +7,24 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **code** | **int** | | **message** | **str** | | [optional] -**height** | **int** | | +**asset_details** | [**List[Asset]**](Asset.md) | | ## Example ```python -from lighter.models.current_height import CurrentHeight +from lighter.models.asset_details import AssetDetails # TODO update the JSON string below json = "{}" -# create an instance of CurrentHeight from a JSON string -current_height_instance = CurrentHeight.from_json(json) +# create an instance of AssetDetails from a JSON string +asset_details_instance = AssetDetails.from_json(json) # print the JSON string representation of the object -print(CurrentHeight.to_json()) +print(AssetDetails.to_json()) # convert the object into a dict -current_height_dict = current_height_instance.to_dict() -# create an instance of CurrentHeight from a dict -current_height_from_dict = CurrentHeight.from_dict(current_height_dict) +asset_details_dict = asset_details_instance.to_dict() +# create an instance of AssetDetails from a dict +asset_details_from_dict = AssetDetails.from_dict(asset_details_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/docs/Blocks.md b/docs/Auth.md similarity index 50% rename from docs/Blocks.md rename to docs/Auth.md index 09ea46c..e8c4a9c 100644 --- a/docs/Blocks.md +++ b/docs/Auth.md @@ -1,31 +1,28 @@ -# Blocks +# Auth ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**code** | **int** | | -**message** | **str** | | [optional] -**total** | **int** | | -**blocks** | [**List[Block]**](Block.md) | | +**auth** | **str** | made optional to support header auth clients | ## Example ```python -from lighter.models.blocks import Blocks +from lighter.models.auth import Auth # TODO update the JSON string below json = "{}" -# create an instance of Blocks from a JSON string -blocks_instance = Blocks.from_json(json) +# create an instance of Auth from a JSON string +auth_instance = Auth.from_json(json) # print the JSON string representation of the object -print(Blocks.to_json()) +print(Auth.to_json()) # convert the object into a dict -blocks_dict = blocks_instance.to_dict() -# create an instance of Blocks from a dict -blocks_from_dict = Blocks.from_dict(blocks_dict) +auth_dict = auth_instance.to_dict() +# create an instance of Auth from a dict +auth_from_dict = Auth.from_dict(auth_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/docs/Block.md b/docs/Block.md deleted file mode 100644 index 78ad751..0000000 --- a/docs/Block.md +++ /dev/null @@ -1,41 +0,0 @@ -# Block - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**commitment** | **str** | | -**height** | **int** | | -**state_root** | **str** | | -**priority_operations** | **int** | | -**on_chain_l2_operations** | **int** | | -**pending_on_chain_operations_pub_data** | **str** | | -**committed_tx_hash** | **str** | | -**committed_at** | **int** | | -**verified_tx_hash** | **str** | | -**verified_at** | **int** | | -**txs** | [**List[Tx]**](Tx.md) | | -**status** | **int** | | -**size** | **int** | | - -## Example - -```python -from lighter.models.block import Block - -# TODO update the JSON string below -json = "{}" -# create an instance of Block from a JSON string -block_instance = Block.from_json(json) -# print the JSON string representation of the object -print(Block.to_json()) - -# convert the object into a dict -block_dict = block_instance.to_dict() -# create an instance of Block from a dict -block_from_dict = Block.from_dict(block_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/docs/BlockApi.md b/docs/BlockApi.md deleted file mode 100644 index 6d02f71..0000000 --- a/docs/BlockApi.md +++ /dev/null @@ -1,220 +0,0 @@ -# lighter.BlockApi - -All URIs are relative to *https://mainnet.zklighter.elliot.ai* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**block**](BlockApi.md#block) | **GET** /api/v1/block | block -[**blocks**](BlockApi.md#blocks) | **GET** /api/v1/blocks | blocks -[**current_height**](BlockApi.md#current_height) | **GET** /api/v1/currentHeight | currentHeight - - -# **block** -> Blocks block(by, value) - -block - -Get block by its height or commitment - -### Example - - -```python -import lighter -from lighter.models.blocks import Blocks -from lighter.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai -# See configuration.py for a list of all supported configuration parameters. -configuration = lighter.Configuration( - host = "https://mainnet.zklighter.elliot.ai" -) - - -# Enter a context with an instance of the API client -async with lighter.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = lighter.BlockApi(api_client) - by = 'by_example' # str | - value = 'value_example' # str | - - try: - # block - api_response = await api_instance.block(by, value) - print("The response of BlockApi->block:\n") - pprint(api_response) - except Exception as e: - print("Exception when calling BlockApi->block: %s\n" % e) -``` - - - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **by** | **str**| | - **value** | **str**| | - -### Return type - -[**Blocks**](Blocks.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | A successful response. | - | -**400** | Bad request | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **blocks** -> Blocks blocks(limit, index=index, sort=sort) - -blocks - -Get blocks - -### Example - - -```python -import lighter -from lighter.models.blocks import Blocks -from lighter.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai -# See configuration.py for a list of all supported configuration parameters. -configuration = lighter.Configuration( - host = "https://mainnet.zklighter.elliot.ai" -) - - -# Enter a context with an instance of the API client -async with lighter.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = lighter.BlockApi(api_client) - limit = 56 # int | - index = 56 # int | (optional) - sort = asc # str | (optional) (default to asc) - - try: - # blocks - api_response = await api_instance.blocks(limit, index=index, sort=sort) - print("The response of BlockApi->blocks:\n") - pprint(api_response) - except Exception as e: - print("Exception when calling BlockApi->blocks: %s\n" % e) -``` - - - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **limit** | **int**| | - **index** | **int**| | [optional] - **sort** | **str**| | [optional] [default to asc] - -### Return type - -[**Blocks**](Blocks.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | A successful response. | - | -**400** | Bad request | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **current_height** -> CurrentHeight current_height() - -currentHeight - -Get current height - -### Example - - -```python -import lighter -from lighter.models.current_height import CurrentHeight -from lighter.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai -# See configuration.py for a list of all supported configuration parameters. -configuration = lighter.Configuration( - host = "https://mainnet.zklighter.elliot.ai" -) - - -# Enter a context with an instance of the API client -async with lighter.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = lighter.BlockApi(api_client) - - try: - # currentHeight - api_response = await api_instance.current_height() - print("The response of BlockApi->current_height:\n") - pprint(api_response) - except Exception as e: - print("Exception when calling BlockApi->current_height: %s\n" % e) -``` - - - -### Parameters - -This endpoint does not need any parameter. - -### Return type - -[**CurrentHeight**](CurrentHeight.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | A successful response. | - | -**400** | Bad request | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/docs/Bridge.md b/docs/Bridge.md new file mode 100644 index 0000000..9147bde --- /dev/null +++ b/docs/Bridge.md @@ -0,0 +1,43 @@ +# Bridge + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | +**version** | **int** | | +**source** | **str** | | +**source_chain_id** | **str** | | +**fast_bridge_tx_hash** | **str** | | +**batch_claim_tx_hash** | **str** | | +**cctp_burn_tx_hash** | **str** | | +**amount** | **str** | | +**intent_address** | **str** | | +**status** | **str** | | +**step** | **str** | | +**description** | **str** | | +**created_at** | **int** | | +**updated_at** | **int** | | +**is_external_deposit** | **bool** | | + +## Example + +```python +from lighter.models.bridge import Bridge + +# TODO update the JSON string below +json = "{}" +# create an instance of Bridge from a JSON string +bridge_instance = Bridge.from_json(json) +# print the JSON string representation of the object +print(Bridge.to_json()) + +# convert the object into a dict +bridge_dict = bridge_instance.to_dict() +# create an instance of Bridge from a dict +bridge_from_dict = Bridge.from_dict(bridge_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/BridgeApi.md b/docs/BridgeApi.md index 4180a8f..ecad9cc 100644 --- a/docs/BridgeApi.md +++ b/docs/BridgeApi.md @@ -4,9 +4,151 @@ All URIs are relative to *https://mainnet.zklighter.elliot.ai* Method | HTTP request | Description ------------- | ------------- | ------------- +[**bridges**](BridgeApi.md#bridges) | **GET** /api/v1/bridges | bridges +[**bridges_is_next_bridge_fast**](BridgeApi.md#bridges_is_next_bridge_fast) | **GET** /api/v1/bridges/isNextBridgeFast | bridges_isNextBridgeFast [**fastbridge_info**](BridgeApi.md#fastbridge_info) | **GET** /api/v1/fastbridge/info | fastbridge_info +[**fastwithdraw**](BridgeApi.md#fastwithdraw) | **POST** /api/v1/fastwithdraw | fastwithdraw +[**fastwithdraw_info**](BridgeApi.md#fastwithdraw_info) | **GET** /api/v1/fastwithdraw/info | fastwithdraw_info +# **bridges** +> RespGetBridgesByL1Addr bridges(l1_address) + +bridges + +Get bridges for given l1 address + +### Example + + +```python +import lighter +from lighter.models.resp_get_bridges_by_l1_addr import RespGetBridgesByL1Addr +from lighter.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai +# See configuration.py for a list of all supported configuration parameters. +configuration = lighter.Configuration( + host = "https://mainnet.zklighter.elliot.ai" +) + + +# Enter a context with an instance of the API client +async with lighter.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = lighter.BridgeApi(api_client) + l1_address = 'l1_address_example' # str | + + try: + # bridges + api_response = await api_instance.bridges(l1_address) + print("The response of BridgeApi->bridges:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling BridgeApi->bridges: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **l1_address** | **str**| | + +### Return type + +[**RespGetBridgesByL1Addr**](RespGetBridgesByL1Addr.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | A successful response. | - | +**400** | Bad request | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **bridges_is_next_bridge_fast** +> RespGetIsNextBridgeFast bridges_is_next_bridge_fast(l1_address) + +bridges_isNextBridgeFast + +Get if next bridge is fast + +### Example + + +```python +import lighter +from lighter.models.resp_get_is_next_bridge_fast import RespGetIsNextBridgeFast +from lighter.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai +# See configuration.py for a list of all supported configuration parameters. +configuration = lighter.Configuration( + host = "https://mainnet.zklighter.elliot.ai" +) + + +# Enter a context with an instance of the API client +async with lighter.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = lighter.BridgeApi(api_client) + l1_address = 'l1_address_example' # str | + + try: + # bridges_isNextBridgeFast + api_response = await api_instance.bridges_is_next_bridge_fast(l1_address) + print("The response of BridgeApi->bridges_is_next_bridge_fast:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling BridgeApi->bridges_is_next_bridge_fast: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **l1_address** | **str**| | + +### Return type + +[**RespGetIsNextBridgeFast**](RespGetIsNextBridgeFast.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | A successful response. | - | +**400** | Bad request | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **fastbridge_info** > RespGetFastBridgeInfo fastbridge_info() @@ -72,3 +214,151 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **fastwithdraw** +> ResultCode fastwithdraw(tx_info, to_address, authorization=authorization, auth=auth) + +fastwithdraw + +Fast withdraw + +### Example + + +```python +import lighter +from lighter.models.result_code import ResultCode +from lighter.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai +# See configuration.py for a list of all supported configuration parameters. +configuration = lighter.Configuration( + host = "https://mainnet.zklighter.elliot.ai" +) + + +# Enter a context with an instance of the API client +async with lighter.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = lighter.BridgeApi(api_client) + tx_info = 'tx_info_example' # str | + to_address = 'to_address_example' # str | + authorization = 'authorization_example' # str | make required after integ is done (optional) + auth = 'auth_example' # str | made optional to support header auth clients (optional) + + try: + # fastwithdraw + api_response = await api_instance.fastwithdraw(tx_info, to_address, authorization=authorization, auth=auth) + print("The response of BridgeApi->fastwithdraw:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling BridgeApi->fastwithdraw: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tx_info** | **str**| | + **to_address** | **str**| | + **authorization** | **str**| make required after integ is done | [optional] + **auth** | **str**| made optional to support header auth clients | [optional] + +### Return type + +[**ResultCode**](ResultCode.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | A successful response. | - | +**400** | Bad request | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **fastwithdraw_info** +> RespGetFastwithdrawalInfo fastwithdraw_info(account_index, authorization=authorization, auth=auth) + +fastwithdraw_info + +Get fast withdraw info + +### Example + + +```python +import lighter +from lighter.models.resp_get_fastwithdrawal_info import RespGetFastwithdrawalInfo +from lighter.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai +# See configuration.py for a list of all supported configuration parameters. +configuration = lighter.Configuration( + host = "https://mainnet.zklighter.elliot.ai" +) + + +# Enter a context with an instance of the API client +async with lighter.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = lighter.BridgeApi(api_client) + account_index = 56 # int | + authorization = 'authorization_example' # str | make required after integ is done (optional) + auth = 'auth_example' # str | made optional to support header auth clients (optional) + + try: + # fastwithdraw_info + api_response = await api_instance.fastwithdraw_info(account_index, authorization=authorization, auth=auth) + print("The response of BridgeApi->fastwithdraw_info:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling BridgeApi->fastwithdraw_info: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **account_index** | **int**| | + **authorization** | **str**| make required after integ is done | [optional] + **auth** | **str**| made optional to support header auth clients | [optional] + +### Return type + +[**RespGetFastwithdrawalInfo**](RespGetFastwithdrawalInfo.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | A successful response. | - | +**400** | Bad request | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/docs/Candle.md b/docs/Candle.md new file mode 100644 index 0000000..6742064 --- /dev/null +++ b/docs/Candle.md @@ -0,0 +1,40 @@ +# Candle + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**t** | **int** | timestamp | +**o** | **float** | open | +**h** | **float** | high | +**l** | **float** | low | +**c** | **float** | close | +**o** | **float** | open_raw | +**h** | **float** | high_raw | +**l** | **float** | low_raw | +**c** | **float** | close_raw | +**v** | **float** | volume0 | +**v** | **float** | volume1 | +**i** | **int** | last_trade_id | + +## Example + +```python +from lighter.models.candle import Candle + +# TODO update the JSON string below +json = "{}" +# create an instance of Candle from a JSON string +candle_instance = Candle.from_json(json) +# print the JSON string representation of the object +print(Candle.to_json()) + +# convert the object into a dict +candle_dict = candle_instance.to_dict() +# create an instance of Candle from a dict +candle_from_dict = Candle.from_dict(candle_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/Txs.md b/docs/Candles.md similarity index 56% rename from docs/Txs.md rename to docs/Candles.md index 634d6c6..3467403 100644 --- a/docs/Txs.md +++ b/docs/Candles.md @@ -1,4 +1,4 @@ -# Txs +# Candles ## Properties @@ -7,24 +7,25 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **code** | **int** | | **message** | **str** | | [optional] -**txs** | [**List[Tx]**](Tx.md) | | +**r** | **str** | resolution | +**c** | [**List[Candle]**](Candle.md) | candles | ## Example ```python -from lighter.models.txs import Txs +from lighter.models.candles import Candles # TODO update the JSON string below json = "{}" -# create an instance of Txs from a JSON string -txs_instance = Txs.from_json(json) +# create an instance of Candles from a JSON string +candles_instance = Candles.from_json(json) # print the JSON string representation of the object -print(Txs.to_json()) +print(Candles.to_json()) # convert the object into a dict -txs_dict = txs_instance.to_dict() -# create an instance of Txs from a dict -txs_from_dict = Txs.from_dict(txs_dict) +candles_dict = candles_instance.to_dict() +# create an instance of Candles from a dict +candles_from_dict = Candles.from_dict(candles_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/docs/Candlestick.md b/docs/Candlestick.md deleted file mode 100644 index 6071dfc..0000000 --- a/docs/Candlestick.md +++ /dev/null @@ -1,36 +0,0 @@ -# Candlestick - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**timestamp** | **int** | | -**open** | **float** | | -**high** | **float** | | -**low** | **float** | | -**close** | **float** | | -**volume0** | **float** | | -**volume1** | **float** | | -**last_trade_id** | **int** | | - -## Example - -```python -from lighter.models.candlestick import Candlestick - -# TODO update the JSON string below -json = "{}" -# create an instance of Candlestick from a JSON string -candlestick_instance = Candlestick.from_json(json) -# print the JSON string representation of the object -print(Candlestick.to_json()) - -# convert the object into a dict -candlestick_dict = candlestick_instance.to_dict() -# create an instance of Candlestick from a dict -candlestick_from_dict = Candlestick.from_dict(candlestick_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/docs/CandlestickApi.md b/docs/CandlestickApi.md index 1515e24..7975c88 100644 --- a/docs/CandlestickApi.md +++ b/docs/CandlestickApi.md @@ -4,23 +4,23 @@ All URIs are relative to *https://mainnet.zklighter.elliot.ai* Method | HTTP request | Description ------------- | ------------- | ------------- -[**candlesticks**](CandlestickApi.md#candlesticks) | **GET** /api/v1/candlesticks | candlesticks +[**candles**](CandlestickApi.md#candles) | **GET** /api/v1/candles | candles [**fundings**](CandlestickApi.md#fundings) | **GET** /api/v1/fundings | fundings -# **candlesticks** -> Candlesticks candlesticks(market_id, resolution, start_timestamp, end_timestamp, count_back, set_timestamp_to_end=set_timestamp_to_end) +# **candles** +> Candles candles(market_id, resolution, start_timestamp, end_timestamp, count_back, set_timestamp_to_end=set_timestamp_to_end) -candlesticks +candles -Get candlesticks +Get candles (optimized with shortened fields and smaller response size) ### Example ```python import lighter -from lighter.models.candlesticks import Candlesticks +from lighter.models.candles import Candles from lighter.rest import ApiException from pprint import pprint @@ -43,12 +43,12 @@ async with lighter.ApiClient(configuration) as api_client: set_timestamp_to_end = False # bool | (optional) (default to False) try: - # candlesticks - api_response = await api_instance.candlesticks(market_id, resolution, start_timestamp, end_timestamp, count_back, set_timestamp_to_end=set_timestamp_to_end) - print("The response of CandlestickApi->candlesticks:\n") + # candles + api_response = await api_instance.candles(market_id, resolution, start_timestamp, end_timestamp, count_back, set_timestamp_to_end=set_timestamp_to_end) + print("The response of CandlestickApi->candles:\n") pprint(api_response) except Exception as e: - print("Exception when calling CandlestickApi->candlesticks: %s\n" % e) + print("Exception when calling CandlestickApi->candles: %s\n" % e) ``` @@ -67,7 +67,7 @@ Name | Type | Description | Notes ### Return type -[**Candlesticks**](Candlesticks.md) +[**Candles**](Candles.md) ### Authorization diff --git a/docs/Candlesticks.md b/docs/Candlesticks.md deleted file mode 100644 index 8c24630..0000000 --- a/docs/Candlesticks.md +++ /dev/null @@ -1,32 +0,0 @@ -# Candlesticks - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**code** | **int** | | -**message** | **str** | | [optional] -**resolution** | **str** | | -**candlesticks** | [**List[Candlestick]**](Candlestick.md) | | - -## Example - -```python -from lighter.models.candlesticks import Candlesticks - -# TODO update the JSON string below -json = "{}" -# create an instance of Candlesticks from a JSON string -candlesticks_instance = Candlesticks.from_json(json) -# print the JSON string representation of the object -print(Candlesticks.to_json()) - -# convert the object into a dict -candlesticks_dict = candlesticks_instance.to_dict() -# create an instance of Candlesticks from a dict -candlesticks_from_dict = Candlesticks.from_dict(candlesticks_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/docs/DepositHistoryItem.md b/docs/DepositHistoryItem.md index 3e850fe..c046dfc 100644 --- a/docs/DepositHistoryItem.md +++ b/docs/DepositHistoryItem.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **str** | | +**asset_id** | **int** | | **amount** | **str** | | **timestamp** | **int** | | **status** | **str** | | diff --git a/docs/DetailedAccount.md b/docs/DetailedAccount.md index 768c3e2..13a7b81 100644 --- a/docs/DetailedAccount.md +++ b/docs/DetailedAccount.md @@ -17,12 +17,14 @@ Name | Type | Description | Notes **available_balance** | **str** | | **status** | **int** | | **collateral** | **str** | | +**transaction_time** | **int** | | **account_index** | **int** | | **name** | **str** | | **description** | **str** | | **can_invite** | **bool** | Remove After FE uses L1 meta endpoint | **referral_points_percentage** | **str** | Remove After FE uses L1 meta endpoint | **positions** | [**List[AccountPosition]**](AccountPosition.md) | | +**assets** | [**List[AccountAsset]**](AccountAsset.md) | | **total_asset_value** | **str** | | **cross_asset_value** | **str** | | **pool_info** | [**PublicPoolInfo**](PublicPoolInfo.md) | | diff --git a/docs/DetailedCandlestick.md b/docs/DetailedCandlestick.md index 4bba057..f00f2e1 100644 --- a/docs/DetailedCandlestick.md +++ b/docs/DetailedCandlestick.md @@ -10,6 +10,10 @@ Name | Type | Description | Notes **high** | **float** | | **low** | **float** | | **close** | **float** | | +**open_raw** | **float** | | +**high_raw** | **float** | | +**low_raw** | **float** | | +**close_raw** | **float** | | **volume0** | **float** | | **volume1** | **float** | | **last_trade_id** | **int** | | diff --git a/docs/EnrichedTx.md b/docs/EnrichedTx.md index 27d2156..61b5214 100644 --- a/docs/EnrichedTx.md +++ b/docs/EnrichedTx.md @@ -22,6 +22,8 @@ Name | Type | Description | Notes **executed_at** | **int** | | **sequence_index** | **int** | | **parent_hash** | **str** | | +**api_key_index** | **int** | | +**transaction_time** | **int** | | **committed_at** | **int** | | **verified_at** | **int** | | diff --git a/docs/InfoApi.md b/docs/InfoApi.md index 1078327..ce3c263 100644 --- a/docs/InfoApi.md +++ b/docs/InfoApi.md @@ -36,8 +36,8 @@ async with lighter.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = lighter.InfoApi(api_client) account_index = 56 # int | - authorization = 'authorization_example' # str | (optional) - auth = 'auth_example' # str | (optional) + authorization = 'authorization_example' # str | make required after integ is done (optional) + auth = 'auth_example' # str | made optional to support header auth clients (optional) to_account_index = -1 # int | (optional) (default to -1) try: @@ -57,8 +57,8 @@ async with lighter.ApiClient(configuration) as api_client: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **account_index** | **int**| | - **authorization** | **str**| | [optional] - **auth** | **str**| | [optional] + **authorization** | **str**| make required after integ is done | [optional] + **auth** | **str**| made optional to support header auth clients | [optional] **to_account_index** | **int**| | [optional] [default to -1] ### Return type diff --git a/docs/LiqTrade.md b/docs/LiqTrade.md index d9761c4..06f0a8e 100644 --- a/docs/LiqTrade.md +++ b/docs/LiqTrade.md @@ -9,6 +9,7 @@ Name | Type | Description | Notes **size** | **str** | | **taker_fee** | **str** | | **maker_fee** | **str** | | +**transaction_time** | **int** | | ## Example diff --git a/docs/MarketConfig.md b/docs/MarketConfig.md new file mode 100644 index 0000000..1a94e25 --- /dev/null +++ b/docs/MarketConfig.md @@ -0,0 +1,33 @@ +# MarketConfig + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**market_margin_mode** | **int** | | +**insurance_fund_account_index** | **int** | | +**liquidation_mode** | **int** | | +**force_reduce_only** | **bool** | | +**trading_hours** | **str** | | + +## Example + +```python +from lighter.models.market_config import MarketConfig + +# TODO update the JSON string below +json = "{}" +# create an instance of MarketConfig from a JSON string +market_config_instance = MarketConfig.from_json(json) +# print the JSON string representation of the object +print(MarketConfig.to_json()) + +# convert the object into a dict +market_config_dict = market_config_instance.to_dict() +# create an instance of MarketConfig from a dict +market_config_from_dict = MarketConfig.from_dict(market_config_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/Order.md b/docs/Order.md index a3415f4..d0e7216 100644 --- a/docs/Order.md +++ b/docs/Order.md @@ -36,6 +36,9 @@ Name | Type | Description | Notes **to_cancel_order_id_0** | **str** | | **block_height** | **int** | | **timestamp** | **int** | | +**created_at** | **int** | | +**updated_at** | **int** | | +**transaction_time** | **int** | | ## Example diff --git a/docs/OrderApi.md b/docs/OrderApi.md index 2b59510..34c7cc8 100644 --- a/docs/OrderApi.md +++ b/docs/OrderApi.md @@ -6,6 +6,7 @@ Method | HTTP request | Description ------------- | ------------- | ------------- [**account_active_orders**](OrderApi.md#account_active_orders) | **GET** /api/v1/accountActiveOrders | accountActiveOrders [**account_inactive_orders**](OrderApi.md#account_inactive_orders) | **GET** /api/v1/accountInactiveOrders | accountInactiveOrders +[**asset_details**](OrderApi.md#asset_details) | **GET** /api/v1/assetDetails | assetDetails [**exchange_stats**](OrderApi.md#exchange_stats) | **GET** /api/v1/exchangeStats | exchangeStats [**export**](OrderApi.md#export) | **GET** /api/v1/export | export [**order_book_details**](OrderApi.md#order_book_details) | **GET** /api/v1/orderBookDetails | orderBookDetails @@ -173,6 +174,75 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **asset_details** +> AssetDetails asset_details(asset_id=asset_id) + +assetDetails + +Get asset details + +### Example + + +```python +import lighter +from lighter.models.asset_details import AssetDetails +from lighter.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai +# See configuration.py for a list of all supported configuration parameters. +configuration = lighter.Configuration( + host = "https://mainnet.zklighter.elliot.ai" +) + + +# Enter a context with an instance of the API client +async with lighter.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = lighter.OrderApi(api_client) + asset_id = 0 # int | (optional) (default to 0) + + try: + # assetDetails + api_response = await api_instance.asset_details(asset_id=asset_id) + print("The response of OrderApi->asset_details:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling OrderApi->asset_details: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **asset_id** | **int**| | [optional] [default to 0] + +### Return type + +[**AssetDetails**](AssetDetails.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | A successful response. | - | +**400** | Bad request | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **exchange_stats** > ExchangeStats exchange_stats() @@ -266,8 +336,8 @@ async with lighter.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = lighter.OrderApi(api_client) type = 'type_example' # str | - authorization = 'authorization_example' # str | (optional) - auth = 'auth_example' # str | (optional) + authorization = 'authorization_example' # str | make required after integ is done (optional) + auth = 'auth_example' # str | made optional to support header auth clients (optional) account_index = -1 # int | (optional) (default to -1) market_id = 255 # int | (optional) (default to 255) @@ -288,8 +358,8 @@ async with lighter.ApiClient(configuration) as api_client: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **type** | **str**| | - **authorization** | **str**| | [optional] - **auth** | **str**| | [optional] + **authorization** | **str**| make required after integ is done | [optional] + **auth** | **str**| made optional to support header auth clients | [optional] **account_index** | **int**| | [optional] [default to -1] **market_id** | **int**| | [optional] [default to 255] @@ -316,7 +386,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **order_book_details** -> OrderBookDetails order_book_details(market_id=market_id) +> OrderBookDetails order_book_details(market_id=market_id, filter=filter) orderBookDetails @@ -343,10 +413,11 @@ async with lighter.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = lighter.OrderApi(api_client) market_id = 255 # int | (optional) (default to 255) + filter = all # str | (optional) (default to all) try: # orderBookDetails - api_response = await api_instance.order_book_details(market_id=market_id) + api_response = await api_instance.order_book_details(market_id=market_id, filter=filter) print("The response of OrderApi->order_book_details:\n") pprint(api_response) except Exception as e: @@ -361,6 +432,7 @@ async with lighter.ApiClient(configuration) as api_client: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **market_id** | **int**| | [optional] [default to 255] + **filter** | **str**| | [optional] [default to all] ### Return type @@ -456,7 +528,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **order_books** -> OrderBooks order_books(market_id=market_id) +> OrderBooks order_books(market_id=market_id, filter=filter) orderBooks @@ -483,10 +555,11 @@ async with lighter.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = lighter.OrderApi(api_client) market_id = 255 # int | (optional) (default to 255) + filter = all # str | (optional) (default to all) try: # orderBooks - api_response = await api_instance.order_books(market_id=market_id) + api_response = await api_instance.order_books(market_id=market_id, filter=filter) print("The response of OrderApi->order_books:\n") pprint(api_response) except Exception as e: @@ -501,6 +574,7 @@ async with lighter.ApiClient(configuration) as api_client: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **market_id** | **int**| | [optional] [default to 255] + **filter** | **str**| | [optional] [default to all] ### Return type @@ -596,7 +670,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **trades** -> Trades trades(sort_by, limit, authorization=authorization, auth=auth, market_id=market_id, account_index=account_index, order_index=order_index, sort_dir=sort_dir, cursor=cursor, var_from=var_from, ask_filter=ask_filter) +> Trades trades(sort_by, limit, authorization=authorization, auth=auth, market_id=market_id, account_index=account_index, order_index=order_index, sort_dir=sort_dir, cursor=cursor, var_from=var_from, ask_filter=ask_filter, role=role, type=type, aggregate=aggregate) trades @@ -624,8 +698,8 @@ async with lighter.ApiClient(configuration) as api_client: api_instance = lighter.OrderApi(api_client) sort_by = 'sort_by_example' # str | limit = 56 # int | - authorization = 'authorization_example' # str | (optional) - auth = 'auth_example' # str | (optional) + authorization = 'authorization_example' # str | make required after integ is done (optional) + auth = 'auth_example' # str | made optional to support header auth clients (optional) market_id = 255 # int | (optional) (default to 255) account_index = -1 # int | (optional) (default to -1) order_index = 56 # int | (optional) @@ -633,10 +707,13 @@ async with lighter.ApiClient(configuration) as api_client: cursor = 'cursor_example' # str | (optional) var_from = -1 # int | (optional) (default to -1) ask_filter = -1 # int | (optional) (default to -1) + role = all # str | (optional) (default to all) + type = all # str | (optional) (default to all) + aggregate = False # bool | (optional) (default to False) try: # trades - api_response = await api_instance.trades(sort_by, limit, authorization=authorization, auth=auth, market_id=market_id, account_index=account_index, order_index=order_index, sort_dir=sort_dir, cursor=cursor, var_from=var_from, ask_filter=ask_filter) + api_response = await api_instance.trades(sort_by, limit, authorization=authorization, auth=auth, market_id=market_id, account_index=account_index, order_index=order_index, sort_dir=sort_dir, cursor=cursor, var_from=var_from, ask_filter=ask_filter, role=role, type=type, aggregate=aggregate) print("The response of OrderApi->trades:\n") pprint(api_response) except Exception as e: @@ -652,8 +729,8 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **sort_by** | **str**| | **limit** | **int**| | - **authorization** | **str**| | [optional] - **auth** | **str**| | [optional] + **authorization** | **str**| make required after integ is done | [optional] + **auth** | **str**| made optional to support header auth clients | [optional] **market_id** | **int**| | [optional] [default to 255] **account_index** | **int**| | [optional] [default to -1] **order_index** | **int**| | [optional] @@ -661,6 +738,9 @@ Name | Type | Description | Notes **cursor** | **str**| | [optional] **var_from** | **int**| | [optional] [default to -1] **ask_filter** | **int**| | [optional] [default to -1] + **role** | **str**| | [optional] [default to all] + **type** | **str**| | [optional] [default to all] + **aggregate** | **bool**| | [optional] [default to False] ### Return type diff --git a/docs/OrderBook.md b/docs/OrderBook.md index 054b931..18d7edb 100644 --- a/docs/OrderBook.md +++ b/docs/OrderBook.md @@ -7,12 +7,16 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **symbol** | **str** | | **market_id** | **int** | | +**market_type** | **str** | | +**base_asset_id** | **int** | | +**quote_asset_id** | **int** | | **status** | **str** | | **taker_fee** | **str** | | **maker_fee** | **str** | | **liquidation_fee** | **str** | | **min_base_amount** | **str** | | **min_quote_amount** | **str** | | +**order_quote_limit** | **str** | | **supported_size_decimals** | **int** | | **supported_price_decimals** | **int** | | **supported_quote_decimals** | **int** | | diff --git a/docs/OrderBookDepth.md b/docs/OrderBookDepth.md index d2cafe9..6659c51 100644 --- a/docs/OrderBookDepth.md +++ b/docs/OrderBookDepth.md @@ -10,6 +10,7 @@ Name | Type | Description | Notes **asks** | [**List[PriceLevel]**](PriceLevel.md) | | **bids** | [**List[PriceLevel]**](PriceLevel.md) | | **offset** | **int** | | +**nonce** | **int** | | ## Example diff --git a/docs/OrderBookDepthWithBeginNonce.md b/docs/OrderBookDepthWithBeginNonce.md new file mode 100644 index 0000000..7a5d7a1 --- /dev/null +++ b/docs/OrderBookDepthWithBeginNonce.md @@ -0,0 +1,33 @@ +# OrderBookDepthWithBeginNonce + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**asks** | [**List[PriceLevel]**](PriceLevel.md) | | +**bids** | [**List[PriceLevel]**](PriceLevel.md) | | +**offset** | **int** | | +**nonce** | **int** | | +**begin_nonce** | **int** | | + +## Example + +```python +from lighter.models.order_book_depth_with_begin_nonce import OrderBookDepthWithBeginNonce + +# TODO update the JSON string below +json = "{}" +# create an instance of OrderBookDepthWithBeginNonce from a JSON string +order_book_depth_with_begin_nonce_instance = OrderBookDepthWithBeginNonce.from_json(json) +# print the JSON string representation of the object +print(OrderBookDepthWithBeginNonce.to_json()) + +# convert the object into a dict +order_book_depth_with_begin_nonce_dict = order_book_depth_with_begin_nonce_instance.to_dict() +# create an instance of OrderBookDepthWithBeginNonce from a dict +order_book_depth_with_begin_nonce_from_dict = OrderBookDepthWithBeginNonce.from_dict(order_book_depth_with_begin_nonce_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/OrderBookDetails.md b/docs/OrderBookDetails.md index 8480c35..0256daa 100644 --- a/docs/OrderBookDetails.md +++ b/docs/OrderBookDetails.md @@ -7,7 +7,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **code** | **int** | | **message** | **str** | | [optional] -**order_book_details** | [**List[OrderBookDetail]**](OrderBookDetail.md) | | +**order_book_details** | [**List[PerpsOrderBookDetail]**](PerpsOrderBookDetail.md) | | +**spot_order_book_details** | [**List[SpotOrderBookDetail]**](SpotOrderBookDetail.md) | | ## Example diff --git a/docs/MarketInfo.md b/docs/PerpsMarketStats.md similarity index 61% rename from docs/MarketInfo.md rename to docs/PerpsMarketStats.md index 7b495c7..bd2ed7b 100644 --- a/docs/MarketInfo.md +++ b/docs/PerpsMarketStats.md @@ -1,14 +1,18 @@ -# MarketInfo +# PerpsMarketStats ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**symbol** | **str** | | **market_id** | **int** | | **index_price** | **str** | | **mark_price** | **str** | | **open_interest** | **str** | | +**open_interest_limit** | **str** | | +**funding_clamp_small** | **str** | | +**funding_clamp_big** | **str** | | **last_trade_price** | **str** | | **current_funding_rate** | **str** | | **funding_rate** | **str** | | @@ -22,19 +26,19 @@ Name | Type | Description | Notes ## Example ```python -from lighter.models.market_info import MarketInfo +from lighter.models.perps_market_stats import PerpsMarketStats # TODO update the JSON string below json = "{}" -# create an instance of MarketInfo from a JSON string -market_info_instance = MarketInfo.from_json(json) +# create an instance of PerpsMarketStats from a JSON string +perps_market_stats_instance = PerpsMarketStats.from_json(json) # print the JSON string representation of the object -print(MarketInfo.to_json()) +print(PerpsMarketStats.to_json()) # convert the object into a dict -market_info_dict = market_info_instance.to_dict() -# create an instance of MarketInfo from a dict -market_info_from_dict = MarketInfo.from_dict(market_info_dict) +perps_market_stats_dict = perps_market_stats_instance.to_dict() +# create an instance of PerpsMarketStats from a dict +perps_market_stats_from_dict = PerpsMarketStats.from_dict(perps_market_stats_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/docs/OrderBookDetail.md b/docs/PerpsOrderBookDetail.md similarity index 68% rename from docs/OrderBookDetail.md rename to docs/PerpsOrderBookDetail.md index 69de4ba..ad69ae3 100644 --- a/docs/OrderBookDetail.md +++ b/docs/PerpsOrderBookDetail.md @@ -1,4 +1,4 @@ -# OrderBookDetail +# PerpsOrderBookDetail ## Properties @@ -7,12 +7,16 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **symbol** | **str** | | **market_id** | **int** | | +**market_type** | **str** | | +**base_asset_id** | **int** | | +**quote_asset_id** | **int** | | **status** | **str** | | **taker_fee** | **str** | | **maker_fee** | **str** | | **liquidation_fee** | **str** | | **min_base_amount** | **str** | | **min_quote_amount** | **str** | | +**order_quote_limit** | **str** | | **supported_size_decimals** | **int** | | **supported_price_decimals** | **int** | | **supported_quote_decimals** | **int** | | @@ -32,23 +36,24 @@ Name | Type | Description | Notes **daily_price_change** | **float** | | **open_interest** | **float** | | **daily_chart** | **Dict[str, float]** | | +**market_config** | [**MarketConfig**](MarketConfig.md) | | ## Example ```python -from lighter.models.order_book_detail import OrderBookDetail +from lighter.models.perps_order_book_detail import PerpsOrderBookDetail # TODO update the JSON string below json = "{}" -# create an instance of OrderBookDetail from a JSON string -order_book_detail_instance = OrderBookDetail.from_json(json) +# create an instance of PerpsOrderBookDetail from a JSON string +perps_order_book_detail_instance = PerpsOrderBookDetail.from_json(json) # print the JSON string representation of the object -print(OrderBookDetail.to_json()) +print(PerpsOrderBookDetail.to_json()) # convert the object into a dict -order_book_detail_dict = order_book_detail_instance.to_dict() -# create an instance of OrderBookDetail from a dict -order_book_detail_from_dict = OrderBookDetail.from_dict(order_book_detail_dict) +perps_order_book_detail_dict = perps_order_book_detail_instance.to_dict() +# create an instance of PerpsOrderBookDetail from a dict +perps_order_book_detail_from_dict = PerpsOrderBookDetail.from_dict(perps_order_book_detail_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/docs/PnLEntry.md b/docs/PnLEntry.md index 6f80183..6032475 100644 --- a/docs/PnLEntry.md +++ b/docs/PnLEntry.md @@ -7,8 +7,11 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **timestamp** | **int** | | **trade_pnl** | **float** | | +**trade_spot_pnl** | **float** | | **inflow** | **float** | | **outflow** | **float** | | +**spot_outflow** | **float** | | +**spot_inflow** | **float** | | **pool_pnl** | **float** | | **pool_inflow** | **float** | | **pool_outflow** | **float** | | diff --git a/docs/PublicPool.md b/docs/PublicPool.md deleted file mode 100644 index 527e94e..0000000 --- a/docs/PublicPool.md +++ /dev/null @@ -1,49 +0,0 @@ -# PublicPool - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**code** | **int** | | -**message** | **str** | | [optional] -**account_type** | **int** | | -**index** | **int** | | -**l1_address** | **str** | | -**cancel_all_time** | **int** | | -**total_order_count** | **int** | | -**total_isolated_order_count** | **int** | | -**pending_order_count** | **int** | | -**available_balance** | **str** | | -**status** | **int** | | -**collateral** | **str** | | -**account_index** | **int** | | -**name** | **str** | | -**description** | **str** | | -**can_invite** | **bool** | Remove After FE uses L1 meta endpoint | -**referral_points_percentage** | **str** | Remove After FE uses L1 meta endpoint | -**total_asset_value** | **str** | | -**cross_asset_value** | **str** | | -**pool_info** | [**PublicPoolInfo**](PublicPoolInfo.md) | | -**account_share** | [**PublicPoolShare**](PublicPoolShare.md) | | [optional] - -## Example - -```python -from lighter.models.public_pool import PublicPool - -# TODO update the JSON string below -json = "{}" -# create an instance of PublicPool from a JSON string -public_pool_instance = PublicPool.from_json(json) -# print the JSON string representation of the object -print(PublicPool.to_json()) - -# convert the object into a dict -public_pool_dict = public_pool_instance.to_dict() -# create an instance of PublicPool from a dict -public_pool_from_dict = PublicPool.from_dict(public_pool_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/docs/PublicPoolInfo.md b/docs/PublicPoolInfo.md index d3aac46..da382c3 100644 --- a/docs/PublicPoolInfo.md +++ b/docs/PublicPoolInfo.md @@ -11,6 +11,7 @@ Name | Type | Description | Notes **total_shares** | **int** | | **operator_shares** | **int** | | **annual_percentage_yield** | **float** | | +**sharpe_ratio** | **float** | | **daily_returns** | [**List[DailyReturn]**](DailyReturn.md) | | **share_prices** | [**List[SharePrice]**](SharePrice.md) | | diff --git a/docs/PublicPoolMetadata.md b/docs/PublicPoolMetadata.md index f3769c2..453108f 100644 --- a/docs/PublicPoolMetadata.md +++ b/docs/PublicPoolMetadata.md @@ -8,10 +8,13 @@ Name | Type | Description | Notes **code** | **int** | | **message** | **str** | | [optional] **account_index** | **int** | | +**created_at** | **int** | | +**master_account_index** | **int** | | **account_type** | **int** | | **name** | **str** | | **l1_address** | **str** | | **annual_percentage_yield** | **float** | | +**sharpe_ratio** | **float** | | **status** | **int** | | **operator_fee** | **str** | | **total_asset_value** | **str** | | diff --git a/docs/ReferralApi.md b/docs/ReferralApi.md deleted file mode 100644 index 0ee3c8b..0000000 --- a/docs/ReferralApi.md +++ /dev/null @@ -1,82 +0,0 @@ -# lighter.ReferralApi - -All URIs are relative to *https://mainnet.zklighter.elliot.ai* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**referral_points**](ReferralApi.md#referral_points) | **GET** /api/v1/referral/points | referral_points - - -# **referral_points** -> ReferralPoints referral_points(account_index, authorization=authorization, auth=auth) - -referral_points - -Get referral points - -### Example - - -```python -import lighter -from lighter.models.referral_points import ReferralPoints -from lighter.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai -# See configuration.py for a list of all supported configuration parameters. -configuration = lighter.Configuration( - host = "https://mainnet.zklighter.elliot.ai" -) - - -# Enter a context with an instance of the API client -async with lighter.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = lighter.ReferralApi(api_client) - account_index = 56 # int | - authorization = 'authorization_example' # str | make required after integ is done (optional) - auth = 'auth_example' # str | made optional to support header auth clients (optional) - - try: - # referral_points - api_response = await api_instance.referral_points(account_index, authorization=authorization, auth=auth) - print("The response of ReferralApi->referral_points:\n") - pprint(api_response) - except Exception as e: - print("Exception when calling ReferralApi->referral_points: %s\n" % e) -``` - - - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **account_index** | **int**| | - **authorization** | **str**| make required after integ is done | [optional] - **auth** | **str**| made optional to support header auth clients | [optional] - -### Return type - -[**ReferralPoints**](ReferralPoints.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | A successful response. | - | -**400** | Bad request | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/docs/ReferralPointEntry.md b/docs/ReferralPointEntry.md deleted file mode 100644 index 2bb70bb..0000000 --- a/docs/ReferralPointEntry.md +++ /dev/null @@ -1,34 +0,0 @@ -# ReferralPointEntry - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**l1_address** | **str** | | -**total_points** | **int** | | -**week_points** | **int** | | -**total_reward_points** | **int** | | -**week_reward_points** | **int** | | -**reward_point_multiplier** | **str** | | - -## Example - -```python -from lighter.models.referral_point_entry import ReferralPointEntry - -# TODO update the JSON string below -json = "{}" -# create an instance of ReferralPointEntry from a JSON string -referral_point_entry_instance = ReferralPointEntry.from_json(json) -# print the JSON string representation of the object -print(ReferralPointEntry.to_json()) - -# convert the object into a dict -referral_point_entry_dict = referral_point_entry_instance.to_dict() -# create an instance of ReferralPointEntry from a dict -referral_point_entry_from_dict = ReferralPointEntry.from_dict(referral_point_entry_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/docs/ReferralPoints.md b/docs/ReferralPoints.md deleted file mode 100644 index 3ed5f35..0000000 --- a/docs/ReferralPoints.md +++ /dev/null @@ -1,34 +0,0 @@ -# ReferralPoints - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**referrals** | [**List[ReferralPointEntry]**](ReferralPointEntry.md) | | -**user_total_points** | **int** | | -**user_last_week_points** | **int** | | -**user_total_referral_reward_points** | **int** | | -**user_last_week_referral_reward_points** | **int** | | -**reward_point_multiplier** | **str** | | - -## Example - -```python -from lighter.models.referral_points import ReferralPoints - -# TODO update the JSON string below -json = "{}" -# create an instance of ReferralPoints from a JSON string -referral_points_instance = ReferralPoints.from_json(json) -# print the JSON string representation of the object -print(ReferralPoints.to_json()) - -# convert the object into a dict -referral_points_dict = referral_points_instance.to_dict() -# create an instance of ReferralPoints from a dict -referral_points_from_dict = ReferralPoints.from_dict(referral_points_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/docs/ReqDoFaucet.md b/docs/ReqDoFaucet.md new file mode 100644 index 0000000..75bdd3b --- /dev/null +++ b/docs/ReqDoFaucet.md @@ -0,0 +1,30 @@ +# ReqDoFaucet + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**l1_address** | **str** | | +**do_l1_transfer** | **bool** | | [default to False] + +## Example + +```python +from lighter.models.req_do_faucet import ReqDoFaucet + +# TODO update the JSON string below +json = "{}" +# create an instance of ReqDoFaucet from a JSON string +req_do_faucet_instance = ReqDoFaucet.from_json(json) +# print the JSON string representation of the object +print(ReqDoFaucet.to_json()) + +# convert the object into a dict +req_do_faucet_dict = req_do_faucet_instance.to_dict() +# create an instance of ReqDoFaucet from a dict +req_do_faucet_from_dict = ReqDoFaucet.from_dict(req_do_faucet_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/ReqExportData.md b/docs/ReqExportData.md index 0222e94..0038c48 100644 --- a/docs/ReqExportData.md +++ b/docs/ReqExportData.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**auth** | **str** | | [optional] +**auth** | **str** | made optional to support header auth clients | [optional] **account_index** | **int** | | [optional] [default to -1] **market_id** | **int** | | [optional] **type** | **str** | | diff --git a/docs/ReqGetAccountActiveOrders.md b/docs/ReqGetAccountActiveOrders.md index d596417..9900779 100644 --- a/docs/ReqGetAccountActiveOrders.md +++ b/docs/ReqGetAccountActiveOrders.md @@ -5,9 +5,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**auth** | **str** | made optional to support header auth clients | [optional] **account_index** | **int** | | **market_id** | **int** | | -**auth** | **str** | made optional to support header auth clients | [optional] ## Example diff --git a/docs/ReqGetAccountPnL.md b/docs/ReqGetAccountPnL.md index 4f5f48d..77233f8 100644 --- a/docs/ReqGetAccountPnL.md +++ b/docs/ReqGetAccountPnL.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**auth** | **str** | | [optional] +**auth** | **str** | made optional to support header auth clients | [optional] **by** | **str** | | **value** | **str** | | **resolution** | **str** | | diff --git a/docs/ReqGetAccountTxs.md b/docs/ReqGetAccountTxs.md index dbf8ffb..0072602 100644 --- a/docs/ReqGetAccountTxs.md +++ b/docs/ReqGetAccountTxs.md @@ -9,8 +9,8 @@ Name | Type | Description | Notes **limit** | **int** | | [optional] **by** | **str** | | [optional] **value** | **str** | | [optional] +**auth** | **str** | made optional to support header auth clients | [optional] **types** | **List[int]** | | [optional] -**auth** | **str** | | [optional] ## Example diff --git a/docs/ReqGetApiTokens.md b/docs/ReqGetApiTokens.md new file mode 100644 index 0000000..7dc459b --- /dev/null +++ b/docs/ReqGetApiTokens.md @@ -0,0 +1,29 @@ +# ReqGetApiTokens + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**account_index** | **int** | | + +## Example + +```python +from lighter.models.req_get_api_tokens import ReqGetApiTokens + +# TODO update the JSON string below +json = "{}" +# create an instance of ReqGetApiTokens from a JSON string +req_get_api_tokens_instance = ReqGetApiTokens.from_json(json) +# print the JSON string representation of the object +print(ReqGetApiTokens.to_json()) + +# convert the object into a dict +req_get_api_tokens_dict = req_get_api_tokens_instance.to_dict() +# create an instance of ReqGetApiTokens from a dict +req_get_api_tokens_from_dict = ReqGetApiTokens.from_dict(req_get_api_tokens_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/ReqGetAssetDetails.md b/docs/ReqGetAssetDetails.md new file mode 100644 index 0000000..ee1e39d --- /dev/null +++ b/docs/ReqGetAssetDetails.md @@ -0,0 +1,29 @@ +# ReqGetAssetDetails + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**asset_id** | **int** | | [optional] + +## Example + +```python +from lighter.models.req_get_asset_details import ReqGetAssetDetails + +# TODO update the JSON string below +json = "{}" +# create an instance of ReqGetAssetDetails from a JSON string +req_get_asset_details_instance = ReqGetAssetDetails.from_json(json) +# print the JSON string representation of the object +print(ReqGetAssetDetails.to_json()) + +# convert the object into a dict +req_get_asset_details_dict = req_get_asset_details_instance.to_dict() +# create an instance of ReqGetAssetDetails from a dict +req_get_asset_details_from_dict = ReqGetAssetDetails.from_dict(req_get_asset_details_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/ReqGetBridgesByL1Addr.md b/docs/ReqGetBridgesByL1Addr.md new file mode 100644 index 0000000..a06ef98 --- /dev/null +++ b/docs/ReqGetBridgesByL1Addr.md @@ -0,0 +1,29 @@ +# ReqGetBridgesByL1Addr + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**l1_address** | **str** | | + +## Example + +```python +from lighter.models.req_get_bridges_by_l1_addr import ReqGetBridgesByL1Addr + +# TODO update the JSON string below +json = "{}" +# create an instance of ReqGetBridgesByL1Addr from a JSON string +req_get_bridges_by_l1_addr_instance = ReqGetBridgesByL1Addr.from_json(json) +# print the JSON string representation of the object +print(ReqGetBridgesByL1Addr.to_json()) + +# convert the object into a dict +req_get_bridges_by_l1_addr_dict = req_get_bridges_by_l1_addr_instance.to_dict() +# create an instance of ReqGetBridgesByL1Addr from a dict +req_get_bridges_by_l1_addr_from_dict = ReqGetBridgesByL1Addr.from_dict(req_get_bridges_by_l1_addr_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/ReqGetCandlesticks.md b/docs/ReqGetCandles.md similarity index 59% rename from docs/ReqGetCandlesticks.md rename to docs/ReqGetCandles.md index f6a322f..830834d 100644 --- a/docs/ReqGetCandlesticks.md +++ b/docs/ReqGetCandles.md @@ -1,4 +1,4 @@ -# ReqGetCandlesticks +# ReqGetCandles ## Properties @@ -15,19 +15,19 @@ Name | Type | Description | Notes ## Example ```python -from lighter.models.req_get_candlesticks import ReqGetCandlesticks +from lighter.models.req_get_candles import ReqGetCandles # TODO update the JSON string below json = "{}" -# create an instance of ReqGetCandlesticks from a JSON string -req_get_candlesticks_instance = ReqGetCandlesticks.from_json(json) +# create an instance of ReqGetCandles from a JSON string +req_get_candles_instance = ReqGetCandles.from_json(json) # print the JSON string representation of the object -print(ReqGetCandlesticks.to_json()) +print(ReqGetCandles.to_json()) # convert the object into a dict -req_get_candlesticks_dict = req_get_candlesticks_instance.to_dict() -# create an instance of ReqGetCandlesticks from a dict -req_get_candlesticks_from_dict = ReqGetCandlesticks.from_dict(req_get_candlesticks_dict) +req_get_candles_dict = req_get_candles_instance.to_dict() +# create an instance of ReqGetCandles from a dict +req_get_candles_from_dict = ReqGetCandles.from_dict(req_get_candles_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/docs/ReqGetDepositHistory.md b/docs/ReqGetDepositHistory.md index d0f0cc1..37fccdc 100644 --- a/docs/ReqGetDepositHistory.md +++ b/docs/ReqGetDepositHistory.md @@ -5,8 +5,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**account_index** | **int** | | **auth** | **str** | made optional to support header auth clients | [optional] +**account_index** | **int** | | **l1_address** | **str** | | **cursor** | **str** | | [optional] **filter** | **str** | | [optional] diff --git a/docs/ReqGetFastWithdrawInfo.md b/docs/ReqGetFastWithdrawInfo.md index 99a79ec..ce0a224 100644 --- a/docs/ReqGetFastWithdrawInfo.md +++ b/docs/ReqGetFastWithdrawInfo.md @@ -5,8 +5,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**account_index** | **int** | | **auth** | **str** | made optional to support header auth clients | [optional] +**account_index** | **int** | | ## Example diff --git a/docs/ReqGetOrderBookDetails.md b/docs/ReqGetOrderBookDetails.md index 333f27a..81d1cf8 100644 --- a/docs/ReqGetOrderBookDetails.md +++ b/docs/ReqGetOrderBookDetails.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **market_id** | **int** | | [optional] +**filter** | **str** | | [optional] [default to 'all'] ## Example diff --git a/docs/ReqGetOrderBooks.md b/docs/ReqGetOrderBooks.md index 4cb4b5d..0b89605 100644 --- a/docs/ReqGetOrderBooks.md +++ b/docs/ReqGetOrderBooks.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **market_id** | **int** | | [optional] +**filter** | **str** | | [optional] [default to 'all'] ## Example diff --git a/docs/ReqGetPositionFunding.md b/docs/ReqGetPositionFunding.md index 83399b2..af72ef1 100644 --- a/docs/ReqGetPositionFunding.md +++ b/docs/ReqGetPositionFunding.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**auth** | **str** | | [optional] +**auth** | **str** | made optional to support header auth clients | [optional] **account_index** | **int** | | **market_id** | **int** | | [optional] **cursor** | **str** | | [optional] diff --git a/docs/ReqGetPublicPools.md b/docs/ReqGetPublicPools.md deleted file mode 100644 index 367eef0..0000000 --- a/docs/ReqGetPublicPools.md +++ /dev/null @@ -1,33 +0,0 @@ -# ReqGetPublicPools - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**auth** | **str** | | [optional] -**filter** | **str** | | [optional] -**index** | **int** | | -**limit** | **int** | | -**account_index** | **int** | | [optional] - -## Example - -```python -from lighter.models.req_get_public_pools import ReqGetPublicPools - -# TODO update the JSON string below -json = "{}" -# create an instance of ReqGetPublicPools from a JSON string -req_get_public_pools_instance = ReqGetPublicPools.from_json(json) -# print the JSON string representation of the object -print(ReqGetPublicPools.to_json()) - -# convert the object into a dict -req_get_public_pools_dict = req_get_public_pools_instance.to_dict() -# create an instance of ReqGetPublicPools from a dict -req_get_public_pools_from_dict = ReqGetPublicPools.from_dict(req_get_public_pools_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/docs/ReqGetPublicPoolsMetadata.md b/docs/ReqGetPublicPoolsMetadata.md index e62dbf5..b1cc952 100644 --- a/docs/ReqGetPublicPoolsMetadata.md +++ b/docs/ReqGetPublicPoolsMetadata.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**auth** | **str** | | [optional] +**auth** | **str** | made optional to support header auth clients | [optional] **filter** | **str** | | [optional] **index** | **int** | | **limit** | **int** | | diff --git a/docs/ReqGetReferralPoints.md b/docs/ReqGetReferralPoints.md deleted file mode 100644 index 609ae7b..0000000 --- a/docs/ReqGetReferralPoints.md +++ /dev/null @@ -1,30 +0,0 @@ -# ReqGetReferralPoints - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**auth** | **str** | made optional to support header auth clients | [optional] -**account_index** | **int** | | - -## Example - -```python -from lighter.models.req_get_referral_points import ReqGetReferralPoints - -# TODO update the JSON string below -json = "{}" -# create an instance of ReqGetReferralPoints from a JSON string -req_get_referral_points_instance = ReqGetReferralPoints.from_json(json) -# print the JSON string representation of the object -print(ReqGetReferralPoints.to_json()) - -# convert the object into a dict -req_get_referral_points_dict = req_get_referral_points_instance.to_dict() -# create an instance of ReqGetReferralPoints from a dict -req_get_referral_points_from_dict = ReqGetReferralPoints.from_dict(req_get_referral_points_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/docs/ReqGetTrades.md b/docs/ReqGetTrades.md index 947005c..6ec8aad 100644 --- a/docs/ReqGetTrades.md +++ b/docs/ReqGetTrades.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**auth** | **str** | | [optional] +**auth** | **str** | made optional to support header auth clients | [optional] **market_id** | **int** | | [optional] **account_index** | **int** | | [optional] [default to -1] **order_index** | **int** | | [optional] @@ -14,7 +14,10 @@ Name | Type | Description | Notes **cursor** | **str** | | [optional] **var_from** | **int** | | [optional] [default to -1] **ask_filter** | **int** | | [optional] +**role** | **str** | | [optional] [default to 'all'] +**type** | **str** | | [optional] [default to 'all'] **limit** | **int** | | +**aggregate** | **bool** | | [optional] [default to False] ## Example diff --git a/docs/ReqGetTransferFeeInfo.md b/docs/ReqGetTransferFeeInfo.md index 84824f7..4715488 100644 --- a/docs/ReqGetTransferFeeInfo.md +++ b/docs/ReqGetTransferFeeInfo.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**auth** | **str** | | [optional] +**auth** | **str** | made optional to support header auth clients | [optional] **account_index** | **int** | | **to_account_index** | **int** | | [optional] [default to -1] diff --git a/docs/ReqGetTransferHistory.md b/docs/ReqGetTransferHistory.md index cb548fa..8db4675 100644 --- a/docs/ReqGetTransferHistory.md +++ b/docs/ReqGetTransferHistory.md @@ -5,8 +5,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**account_index** | **int** | | **auth** | **str** | made optional to support header auth clients | [optional] +**account_index** | **int** | | **cursor** | **str** | | [optional] ## Example diff --git a/docs/ReqGetWithdrawHistory.md b/docs/ReqGetWithdrawHistory.md index a8297ba..65c6485 100644 --- a/docs/ReqGetWithdrawHistory.md +++ b/docs/ReqGetWithdrawHistory.md @@ -5,8 +5,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**account_index** | **int** | | **auth** | **str** | made optional to support header auth clients | [optional] +**account_index** | **int** | | **cursor** | **str** | | [optional] **filter** | **str** | | [optional] diff --git a/docs/PublicPools.md b/docs/RespGetApiTokens.md similarity index 50% rename from docs/PublicPools.md rename to docs/RespGetApiTokens.md index 5ebeb86..d05063f 100644 --- a/docs/PublicPools.md +++ b/docs/RespGetApiTokens.md @@ -1,4 +1,4 @@ -# PublicPools +# RespGetApiTokens ## Properties @@ -7,25 +7,24 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **code** | **int** | | **message** | **str** | | [optional] -**total** | **int** | | -**public_pools** | [**List[PublicPool]**](PublicPool.md) | | +**api_tokens** | [**List[ApiToken]**](ApiToken.md) | | ## Example ```python -from lighter.models.public_pools import PublicPools +from lighter.models.resp_get_api_tokens import RespGetApiTokens # TODO update the JSON string below json = "{}" -# create an instance of PublicPools from a JSON string -public_pools_instance = PublicPools.from_json(json) +# create an instance of RespGetApiTokens from a JSON string +resp_get_api_tokens_instance = RespGetApiTokens.from_json(json) # print the JSON string representation of the object -print(PublicPools.to_json()) +print(RespGetApiTokens.to_json()) # convert the object into a dict -public_pools_dict = public_pools_instance.to_dict() -# create an instance of PublicPools from a dict -public_pools_from_dict = PublicPools.from_dict(public_pools_dict) +resp_get_api_tokens_dict = resp_get_api_tokens_instance.to_dict() +# create an instance of RespGetApiTokens from a dict +resp_get_api_tokens_from_dict = RespGetApiTokens.from_dict(resp_get_api_tokens_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/docs/RespGetBridgesByL1Addr.md b/docs/RespGetBridgesByL1Addr.md new file mode 100644 index 0000000..3d797bd --- /dev/null +++ b/docs/RespGetBridgesByL1Addr.md @@ -0,0 +1,31 @@ +# RespGetBridgesByL1Addr + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **int** | | +**message** | **str** | | [optional] +**bridges** | [**List[Bridge]**](Bridge.md) | | + +## Example + +```python +from lighter.models.resp_get_bridges_by_l1_addr import RespGetBridgesByL1Addr + +# TODO update the JSON string below +json = "{}" +# create an instance of RespGetBridgesByL1Addr from a JSON string +resp_get_bridges_by_l1_addr_instance = RespGetBridgesByL1Addr.from_json(json) +# print the JSON string representation of the object +print(RespGetBridgesByL1Addr.to_json()) + +# convert the object into a dict +resp_get_bridges_by_l1_addr_dict = resp_get_bridges_by_l1_addr_instance.to_dict() +# create an instance of RespGetBridgesByL1Addr from a dict +resp_get_bridges_by_l1_addr_from_dict = RespGetBridgesByL1Addr.from_dict(resp_get_bridges_by_l1_addr_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/RespGetFastwithdrawalInfo.md b/docs/RespGetFastwithdrawalInfo.md new file mode 100644 index 0000000..91b1919 --- /dev/null +++ b/docs/RespGetFastwithdrawalInfo.md @@ -0,0 +1,33 @@ +# RespGetFastwithdrawalInfo + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **int** | | +**message** | **str** | | [optional] +**to_account_index** | **int** | | +**withdraw_limit** | **str** | | +**max_withdrawal_amount** | **str** | | + +## Example + +```python +from lighter.models.resp_get_fastwithdrawal_info import RespGetFastwithdrawalInfo + +# TODO update the JSON string below +json = "{}" +# create an instance of RespGetFastwithdrawalInfo from a JSON string +resp_get_fastwithdrawal_info_instance = RespGetFastwithdrawalInfo.from_json(json) +# print the JSON string representation of the object +print(RespGetFastwithdrawalInfo.to_json()) + +# convert the object into a dict +resp_get_fastwithdrawal_info_dict = resp_get_fastwithdrawal_info_instance.to_dict() +# create an instance of RespGetFastwithdrawalInfo from a dict +resp_get_fastwithdrawal_info_from_dict = RespGetFastwithdrawalInfo.from_dict(resp_get_fastwithdrawal_info_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/RespGetIsNextBridgeFast.md b/docs/RespGetIsNextBridgeFast.md new file mode 100644 index 0000000..09ccf87 --- /dev/null +++ b/docs/RespGetIsNextBridgeFast.md @@ -0,0 +1,31 @@ +# RespGetIsNextBridgeFast + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **int** | | +**message** | **str** | | [optional] +**is_next_bridge_fast** | **bool** | | + +## Example + +```python +from lighter.models.resp_get_is_next_bridge_fast import RespGetIsNextBridgeFast + +# TODO update the JSON string below +json = "{}" +# create an instance of RespGetIsNextBridgeFast from a JSON string +resp_get_is_next_bridge_fast_instance = RespGetIsNextBridgeFast.from_json(json) +# print the JSON string representation of the object +print(RespGetIsNextBridgeFast.to_json()) + +# convert the object into a dict +resp_get_is_next_bridge_fast_dict = resp_get_is_next_bridge_fast_instance.to_dict() +# create an instance of RespGetIsNextBridgeFast from a dict +resp_get_is_next_bridge_fast_from_dict = RespGetIsNextBridgeFast.from_dict(resp_get_is_next_bridge_fast_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/RespPostApiToken.md b/docs/RespPostApiToken.md new file mode 100644 index 0000000..baf886f --- /dev/null +++ b/docs/RespPostApiToken.md @@ -0,0 +1,38 @@ +# RespPostApiToken + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **int** | | +**message** | **str** | | [optional] +**token_id** | **int** | | +**api_token** | **str** | | +**name** | **str** | | +**account_index** | **int** | | +**expiry** | **int** | | +**sub_account_access** | **bool** | | +**revoked** | **bool** | | +**scopes** | **str** | | + +## Example + +```python +from lighter.models.resp_post_api_token import RespPostApiToken + +# TODO update the JSON string below +json = "{}" +# create an instance of RespPostApiToken from a JSON string +resp_post_api_token_instance = RespPostApiToken.from_json(json) +# print the JSON string representation of the object +print(RespPostApiToken.to_json()) + +# convert the object into a dict +resp_post_api_token_dict = resp_post_api_token_instance.to_dict() +# create an instance of RespPostApiToken from a dict +resp_post_api_token_from_dict = RespPostApiToken.from_dict(resp_post_api_token_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/RespRevokeApiToken.md b/docs/RespRevokeApiToken.md new file mode 100644 index 0000000..0359746 --- /dev/null +++ b/docs/RespRevokeApiToken.md @@ -0,0 +1,32 @@ +# RespRevokeApiToken + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **int** | | +**message** | **str** | | [optional] +**token_id** | **int** | | +**revoked** | **bool** | | + +## Example + +```python +from lighter.models.resp_revoke_api_token import RespRevokeApiToken + +# TODO update the JSON string below +json = "{}" +# create an instance of RespRevokeApiToken from a JSON string +resp_revoke_api_token_instance = RespRevokeApiToken.from_json(json) +# print the JSON string representation of the object +print(RespRevokeApiToken.to_json()) + +# convert the object into a dict +resp_revoke_api_token_dict = resp_revoke_api_token_instance.to_dict() +# create an instance of RespRevokeApiToken from a dict +resp_revoke_api_token_from_dict = RespRevokeApiToken.from_dict(resp_revoke_api_token_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/RespSendTx.md b/docs/RespSendTx.md index 5d58479..1fa1758 100644 --- a/docs/RespSendTx.md +++ b/docs/RespSendTx.md @@ -9,6 +9,7 @@ Name | Type | Description | Notes **message** | **str** | | [optional] **tx_hash** | **str** | | **predicted_execution_time_ms** | **int** | | +**volume_quota_remaining** | **int** | | ## Example diff --git a/docs/RespSendTxBatch.md b/docs/RespSendTxBatch.md index 1b02a5b..cf70435 100644 --- a/docs/RespSendTxBatch.md +++ b/docs/RespSendTxBatch.md @@ -9,6 +9,7 @@ Name | Type | Description | Notes **message** | **str** | | [optional] **tx_hash** | **List[str]** | | **predicted_execution_time_ms** | **int** | | +**volume_quota_remaining** | **int** | | ## Example diff --git a/docs/SimpleOrder.md b/docs/SimpleOrder.md index c32315e..8ab2be2 100644 --- a/docs/SimpleOrder.md +++ b/docs/SimpleOrder.md @@ -12,6 +12,7 @@ Name | Type | Description | Notes **remaining_base_amount** | **str** | | **price** | **str** | | **order_expiry** | **int** | | +**transaction_time** | **int** | | ## Example diff --git a/docs/SpotMarketStats.md b/docs/SpotMarketStats.md new file mode 100644 index 0000000..d471d39 --- /dev/null +++ b/docs/SpotMarketStats.md @@ -0,0 +1,38 @@ +# SpotMarketStats + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**symbol** | **str** | | +**market_id** | **int** | | +**index_price** | **str** | | +**mid_price** | **str** | | +**last_trade_price** | **str** | | +**daily_base_token_volume** | **float** | | +**daily_quote_token_volume** | **float** | | +**daily_price_low** | **float** | | +**daily_price_high** | **float** | | +**daily_price_change** | **float** | | + +## Example + +```python +from lighter.models.spot_market_stats import SpotMarketStats + +# TODO update the JSON string below +json = "{}" +# create an instance of SpotMarketStats from a JSON string +spot_market_stats_instance = SpotMarketStats.from_json(json) +# print the JSON string representation of the object +print(SpotMarketStats.to_json()) + +# convert the object into a dict +spot_market_stats_dict = spot_market_stats_instance.to_dict() +# create an instance of SpotMarketStats from a dict +spot_market_stats_from_dict = SpotMarketStats.from_dict(spot_market_stats_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/SpotOrderBookDetail.md b/docs/SpotOrderBookDetail.md new file mode 100644 index 0000000..a41e15e --- /dev/null +++ b/docs/SpotOrderBookDetail.md @@ -0,0 +1,53 @@ +# SpotOrderBookDetail + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**symbol** | **str** | | +**market_id** | **int** | | +**market_type** | **str** | | +**base_asset_id** | **int** | | +**quote_asset_id** | **int** | | +**status** | **str** | | +**taker_fee** | **str** | | +**maker_fee** | **str** | | +**liquidation_fee** | **str** | | +**min_base_amount** | **str** | | +**min_quote_amount** | **str** | | +**order_quote_limit** | **str** | | +**supported_size_decimals** | **int** | | +**supported_price_decimals** | **int** | | +**supported_quote_decimals** | **int** | | +**size_decimals** | **int** | | +**price_decimals** | **int** | | +**last_trade_price** | **float** | | +**daily_trades_count** | **int** | | +**daily_base_token_volume** | **float** | | +**daily_quote_token_volume** | **float** | | +**daily_price_low** | **float** | | +**daily_price_high** | **float** | | +**daily_price_change** | **float** | | +**daily_chart** | **Dict[str, float]** | | + +## Example + +```python +from lighter.models.spot_order_book_detail import SpotOrderBookDetail + +# TODO update the JSON string below +json = "{}" +# create an instance of SpotOrderBookDetail from a JSON string +spot_order_book_detail_instance = SpotOrderBookDetail.from_json(json) +# print the JSON string representation of the object +print(SpotOrderBookDetail.to_json()) + +# convert the object into a dict +spot_order_book_detail_dict = spot_order_book_detail_instance.to_dict() +# create an instance of SpotOrderBookDetail from a dict +spot_order_book_detail_from_dict = SpotOrderBookDetail.from_dict(spot_order_book_detail_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/docs/Trade.md b/docs/Trade.md index ac611a0..43a5191 100644 --- a/docs/Trade.md +++ b/docs/Trade.md @@ -14,6 +14,8 @@ Name | Type | Description | Notes **usd_amount** | **str** | | **ask_id** | **int** | | **bid_id** | **int** | | +**ask_client_id** | **int** | | +**bid_client_id** | **int** | | **ask_account_id** | **int** | | **bid_account_id** | **int** | | **is_maker_ask** | **bool** | | @@ -29,6 +31,7 @@ Name | Type | Description | Notes **maker_entry_quote_before** | **str** | | **maker_initial_margin_fraction_before** | **int** | | **maker_position_sign_changed** | **bool** | | +**transaction_time** | **int** | | ## Example diff --git a/docs/TransactionApi.md b/docs/TransactionApi.md index 01b0ec1..54ab1b3 100644 --- a/docs/TransactionApi.md +++ b/docs/TransactionApi.md @@ -4,8 +4,6 @@ All URIs are relative to *https://mainnet.zklighter.elliot.ai* Method | HTTP request | Description ------------- | ------------- | ------------- -[**account_txs**](TransactionApi.md#account_txs) | **GET** /api/v1/accountTxs | accountTxs -[**block_txs**](TransactionApi.md#block_txs) | **GET** /api/v1/blockTxs | blockTxs [**deposit_history**](TransactionApi.md#deposit_history) | **GET** /api/v1/deposit/history | deposit_history [**next_nonce**](TransactionApi.md#next_nonce) | **GET** /api/v1/nextNonce | nextNonce [**send_tx**](TransactionApi.md#send_tx) | **POST** /api/v1/sendTx | sendTx @@ -13,162 +11,9 @@ Method | HTTP request | Description [**transfer_history**](TransactionApi.md#transfer_history) | **GET** /api/v1/transfer/history | transfer_history [**tx**](TransactionApi.md#tx) | **GET** /api/v1/tx | tx [**tx_from_l1_tx_hash**](TransactionApi.md#tx_from_l1_tx_hash) | **GET** /api/v1/txFromL1TxHash | txFromL1TxHash -[**txs**](TransactionApi.md#txs) | **GET** /api/v1/txs | txs [**withdraw_history**](TransactionApi.md#withdraw_history) | **GET** /api/v1/withdraw/history | withdraw_history -# **account_txs** -> Txs account_txs(limit, by, value, authorization=authorization, index=index, types=types, auth=auth) - -accountTxs - -Get transactions of a specific account - -### Example - - -```python -import lighter -from lighter.models.txs import Txs -from lighter.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai -# See configuration.py for a list of all supported configuration parameters. -configuration = lighter.Configuration( - host = "https://mainnet.zklighter.elliot.ai" -) - - -# Enter a context with an instance of the API client -async with lighter.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = lighter.TransactionApi(api_client) - limit = 56 # int | - by = 'by_example' # str | - value = 'value_example' # str | - authorization = 'authorization_example' # str | (optional) - index = 56 # int | (optional) - types = [56] # List[int] | (optional) - auth = 'auth_example' # str | (optional) - - try: - # accountTxs - api_response = await api_instance.account_txs(limit, by, value, authorization=authorization, index=index, types=types, auth=auth) - print("The response of TransactionApi->account_txs:\n") - pprint(api_response) - except Exception as e: - print("Exception when calling TransactionApi->account_txs: %s\n" % e) -``` - - - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **limit** | **int**| | - **by** | **str**| | - **value** | **str**| | - **authorization** | **str**| | [optional] - **index** | **int**| | [optional] - **types** | [**List[int]**](int.md)| | [optional] - **auth** | **str**| | [optional] - -### Return type - -[**Txs**](Txs.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | A successful response. | - | -**400** | Bad request | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **block_txs** -> Txs block_txs(by, value) - -blockTxs - -Get transactions in a block - -### Example - - -```python -import lighter -from lighter.models.txs import Txs -from lighter.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai -# See configuration.py for a list of all supported configuration parameters. -configuration = lighter.Configuration( - host = "https://mainnet.zklighter.elliot.ai" -) - - -# Enter a context with an instance of the API client -async with lighter.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = lighter.TransactionApi(api_client) - by = 'by_example' # str | - value = 'value_example' # str | - - try: - # blockTxs - api_response = await api_instance.block_txs(by, value) - print("The response of TransactionApi->block_txs:\n") - pprint(api_response) - except Exception as e: - print("Exception when calling TransactionApi->block_txs: %s\n" % e) -``` - - - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **by** | **str**| | - **value** | **str**| | - -### Return type - -[**Txs**](Txs.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | A successful response. | - | -**400** | Bad request | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - # **deposit_history** > DepositHistory deposit_history(account_index, l1_address, authorization=authorization, auth=auth, cursor=cursor, filter=filter) @@ -678,77 +523,6 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) -# **txs** -> Txs txs(limit, index=index) - -txs - -Get transactions which are already packed into blocks - -### Example - - -```python -import lighter -from lighter.models.txs import Txs -from lighter.rest import ApiException -from pprint import pprint - -# Defining the host is optional and defaults to https://mainnet.zklighter.elliot.ai -# See configuration.py for a list of all supported configuration parameters. -configuration = lighter.Configuration( - host = "https://mainnet.zklighter.elliot.ai" -) - - -# Enter a context with an instance of the API client -async with lighter.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = lighter.TransactionApi(api_client) - limit = 56 # int | - index = 56 # int | (optional) - - try: - # txs - api_response = await api_instance.txs(limit, index=index) - print("The response of TransactionApi->txs:\n") - pprint(api_response) - except Exception as e: - print("Exception when calling TransactionApi->txs: %s\n" % e) -``` - - - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **limit** | **int**| | - **index** | **int**| | [optional] - -### Return type - -[**Txs**](Txs.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | A successful response. | - | -**400** | Bad request | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - # **withdraw_history** > WithdrawHistory withdraw_history(account_index, authorization=authorization, auth=auth, cursor=cursor, filter=filter) diff --git a/docs/TransferHistoryItem.md b/docs/TransferHistoryItem.md index 4d7f5df..56b71aa 100644 --- a/docs/TransferHistoryItem.md +++ b/docs/TransferHistoryItem.md @@ -6,13 +6,17 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **str** | | +**asset_id** | **int** | | **amount** | **str** | | +**fee** | **str** | | **timestamp** | **int** | | **type** | **str** | | **from_l1_address** | **str** | | **to_l1_address** | **str** | | **from_account_index** | **int** | | **to_account_index** | **int** | | +**from_route** | **str** | | +**to_route** | **str** | | **tx_hash** | **str** | | ## Example diff --git a/docs/Tx.md b/docs/Tx.md deleted file mode 100644 index 76f8f11..0000000 --- a/docs/Tx.md +++ /dev/null @@ -1,43 +0,0 @@ -# Tx - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**hash** | **str** | | -**type** | **int** | | -**info** | **str** | | -**event_info** | **str** | | -**status** | **int** | | -**transaction_index** | **int** | | -**l1_address** | **str** | | -**account_index** | **int** | | -**nonce** | **int** | | -**expire_at** | **int** | | -**block_height** | **int** | | -**queued_at** | **int** | | -**executed_at** | **int** | | -**sequence_index** | **int** | | -**parent_hash** | **str** | | - -## Example - -```python -from lighter.models.tx import Tx - -# TODO update the JSON string below -json = "{}" -# create an instance of Tx from a JSON string -tx_instance = Tx.from_json(json) -# print the JSON string representation of the object -print(Tx.to_json()) - -# convert the object into a dict -tx_dict = tx_instance.to_dict() -# create an instance of Tx from a dict -tx_from_dict = Tx.from_dict(tx_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/docs/WithdrawHistoryItem.md b/docs/WithdrawHistoryItem.md index 1ae6002..8ce329d 100644 --- a/docs/WithdrawHistoryItem.md +++ b/docs/WithdrawHistoryItem.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **str** | | +**asset_id** | **int** | | **amount** | **str** | | **timestamp** | **int** | | **status** | **str** | | diff --git a/examples/.gitignore b/examples/.gitignore new file mode 100644 index 0000000..87b6ebd --- /dev/null +++ b/examples/.gitignore @@ -0,0 +1 @@ +api_key_config.json \ No newline at end of file diff --git a/examples/README.md b/examples/README.md index b506b7c..f565290 100644 --- a/examples/README.md +++ b/examples/README.md @@ -5,18 +5,152 @@ - this will require you to enter your Ethereum private key - the eth private key will only be used in the Py SDK to sign a message - the eth private key is not required in order to trade on the platform - - the eth private key is not passed to the binary - - copy the output of the script and post it into `create_cancel_order.py` - - the output should look like -``` -BASE_URL = 'https://testnet.zklighter.elliot.ai' -API_KEY_PRIVATE_KEY = '0xea5d2eca5be67eca056752eaf27b173518b8a5550117c09d2b58c7ea7d306cc4426f913ccf27ab19' -ACCOUNT_INDEX = 595 -API_KEY_INDEX = 1 -``` -- start trading using - - `create_cancel_order.py` has an example which created an order on testnet & cancels it - - you'll need to set up both your account index, api key index & API Key private key + - the eth private key is not passed to the binary + - the API key config is saved in a local file `./api_key_config.json` + +## Start trading on testnet +- `create_modify_cancel_order_http.py` + - creates an ask (sell) order for 0.1 ETH @ $4050 + - modified the order and increases the size to 0.11 ETH and increases the price to $4100 + - cancels the order + - Note: all of these operations use the client order index of the order. You can use the order from the exchange as well + +- `create_modify_cancel_order_ws.py` + - same flow as `create_modify_cancel_order_http.py` + - sends TXs over WS instead of HTTP + +- `create_market_order_eth_buy.py` + - creates a market buy order for 0.1 ETH @ market price +- `create_market_order_eth_sell.py` + - creates a market sell order for 0.1 ETH @ market price + +- `create_grouped_ioc_with_attached_sl_tp.py` + - creates an ask (sell) IoC order for 0.1 ETH + - along w/ the order, it sets up a Stop Loss (SL) and a Take Profit (TP) order for the whole size of the order + - the size of the SL/TP will be equal to the executed size of the order + - the SL/TP orders are canceled when the sign of your position changes + +- `create_position_tied_sl_tp.py` + - creates a bid (buy) Stop Loss (SL) and a Take Profit (TP) to close your short position + - the size of the orders will be for your whole position (because BaseAmount=0) + - the orders will grow / shrink as you accumulate more position + - the SL/TP orders are canceled when the sign of your position changes + +## On SL/TP orders +SL/TP orders need to be configured beyond just setting the trigger price. When the trigger price is set, +the order will just be executed, like a normal order. This means that a market order, for example, might not have enough slippage! \ +Let's say that you have a 1 BTC long position, and the current price is $110'000. \ +You want to set up a take profit at $120'000 +- order should be an ask (sell) order, to close your position +- the trigger price should be $120'000 + +What about the order types? Just as normal orders, SL/TP orders trigger an order, which can be: +- market order +- limit IOC / GTC + +## Modify leverage / Margin Mode (Cross, Isolated) / Add Collateral to isolated-only positions +- `margin_eth_20x_cross_http` + - sets ETH market to 20x leverage and cross-margin mode, using HTTP +- `margin_eth_50x_isolate_ws` + - sets ETH market to 50x leverage and isolated margin mode, using HTTP +- `margin_eth_add_collateral_http.py` + - adds $10.5 USDC to the ETH position (must be opened and in isolated mode) +- `margin_eth_remove_collateral_ws.py` + - removes $5 USDC from the ETH position (must be opened and in isolated mode) + +## Batch orders +- `send_batch_tx_http.py` + - sends multiple orders in a single HTTP request +- `send_batch_tx_ws.py` + - sends multiple orders in a single WS request` + +Batch TXs will be executed back to back, without the possibility of other TXs interfering. + +## Spot Trading +To trade spot markets, you need to have spot USDC. USDC used in your perpetual account will be used as collateral for your cross-positions. +USDC deposited in the spot account can only be used to buy spot assets. +To transfer USDC between spot <> perp balance, or vice verse, check out +- `spot_self_transfer_perp_spot.py` +- `spot_self_transfer_spot_perp.py` + +Order placement / trades work in the same way as for perpetual markets. +The fee will be paid in the received asset for premium spot trades. +This means that if you sell ETH, you'll receive less USDC, and if you BUY 1 ETH, you'll receive slightly less than 1 ETH. +You can check out the following examples, which should work on spot ETH by changing the market index to 2048 instead of 0. +- `create_modify_cancel_order_http.py` +- `create_modify_cancel_order_ws.py` +- `create_market_order_eth_buy.py` +- `create_market_order_eth_sell.py` +- `send_batch_tx_http.py` +- `send_batch_tx_ws.py` + +Trading setup is very similar to perpetual markets. +The only difference is that you'll need to hold USDC / ETH before placing an order. +For example, on perp markets you can place an order to short (sell) ETH without having to worry that much. +The limitation there would be to have enough available collateral to cover the order. +On spot orders, you need to have enough assets in your spot account to cover all open orders. +If you want to place two orders, to buy 1000 USDC worth of ETH and 1000 USDC worth of ZK, you'll need to have at least 2000 available USDC. + +You can get the order book details (including symbol and market index) as well as quote asset id (ETH) and base asset id (USDC) +by following the example below: +- `spot_get_order_books.py` + +Note: you'll need the quote asset id and base asset id to check available balance. +Available balance is not locked in open orders. + +To keep track of your spot balance, you can use HTTP calls or a websocket subscription. +Examples on how to do this can be found here: +- `spot_get_account_assets_http.py` +- `spot_get_account_assets_ws.py` + +Moving money to / from subaccounts is possible for spot assets. +For USDC, you can move directly from main perp balance to subaccount spot balance, for example. +More details can be found in the following example: +- `sub_account_create.py` +- `sub_account_transfer_eth.py` +- `sub_account_transfer_usdc.py` + +## Public Pools +Public pools behave just like subaccounts, except that anyone can join them. +You can create / modify a public pool using the SDK. Check out the following example: +- `public_pool_create_modify.py` + +To create API keys for a public pool, you need to run the setup script but specify the `ACCOUNT_INDEX` to be the one of the public pool. +After that, you can trade from the public as from any other account. + +If you want to deposit / withdraw from a public pool, check the following example: +- `public_pool_deposit.py` +- `public_pool_withdraw.py` + +To get information about pools, check: +- `public_pool_info.py` + +## Moving funds around +- `withdraw_fast.py` + - send USDC directly from Lighter to Arbitrum +- `withdraw_normal.py` + - send USDC/ETH from Lighter to Ethereum +- `transfer.py` + - generic example of how to transfer funds between accounts. + - same functionality as `sub_account_transfer_eth` and `sub_account_transfer_usdc` + +## Transfer Notes +The `memo` field is a user message, and it has to be exactly 32 bytes long. In case of fast withdrawals, you need to specify the recipient in the memo. +This is the case since the memo is part of the signature. This way, the recipient is verified. + +When calling `client.transfer`, you pass the amount without needing to worry about the decimals. +When calling `client.sign_transfer` on the other hand, you need to specify the decimals and pass an integer. + +The `fee` field can be obtained by calling `info_api.transfer_fee_info(...)`. The field can be passed as it is. +Transfers between subaccounts are free for all assets. + +When sending assets, you can specify the source and destination routes. +A route is either `perp` or `spot`. You can send USDC directly from your perp balance to another person's spot balance. +If you receive USDC in your perp account, it will be instantly used as collateral for open positions. +This also allows you to move USDC from your spot balance to your perp balance. +Spot assets (like ETH) need to have both the from and to route set to `spot`. +You can get all `asset_id`s by following the example below: +- `spot_get_order_books.py` ## Setup steps for mainnet - deposit money on Lighter to create an account first diff --git a/examples/create_cancel_order.py b/examples/create_cancel_order.py deleted file mode 100644 index f757296..0000000 --- a/examples/create_cancel_order.py +++ /dev/null @@ -1,70 +0,0 @@ -import asyncio -import logging -import lighter - -logging.basicConfig(level=logging.DEBUG) - -# The API_KEY_PRIVATE_KEY provided belongs to a dummy account registered on Testnet. -# It was generated using the setup_system.py script, and servers as an example. -# Alternatively, you can go to https://app.lighter.xyz/apikeys for mainnet api keys -BASE_URL = "https://testnet.zklighter.elliot.ai" -API_KEY_PRIVATE_KEY = "0xed636277f3753b6c0275f7a28c2678a7f3a95655e09deaebec15179b50c5da7f903152e50f594f7b" -ACCOUNT_INDEX = 65 -API_KEY_INDEX = 1 - - -def trim_exception(e: Exception) -> str: - return str(e).strip().split("\n")[-1] - - -async def main(): - api_client = lighter.ApiClient(configuration=lighter.Configuration(host=BASE_URL)) - - client = lighter.SignerClient( - url=BASE_URL, - private_key=API_KEY_PRIVATE_KEY, - account_index=ACCOUNT_INDEX, - api_key_index=API_KEY_INDEX, - ) - - err = client.check_client() - if err is not None: - print(f"CheckClient error: {trim_exception(err)}") - return - - # create order - tx, tx_hash, err = await client.create_order( - market_index=0, - client_order_index=123, - base_amount=100000, - price=405000, - is_ask=True, - order_type=lighter.SignerClient.ORDER_TYPE_LIMIT, - time_in_force=lighter.SignerClient.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, - reduce_only=False, - trigger_price=0, - ) - print(f"Create Order {tx=} {tx_hash=} {err=}") - if err is not None: - raise Exception(err) - - auth, err = client.create_auth_token_with_expiry(lighter.SignerClient.DEFAULT_10_MIN_AUTH_EXPIRY) - print(f"{auth=}") - if err is not None: - raise Exception(err) - - # cancel order - tx, tx_hash, err = await client.cancel_order( - market_index=0, - order_index=123, - ) - print(f"Cancel Order {tx=} {tx_hash=} {err=}") - if err is not None: - raise Exception(err) - - await client.close() - await api_client.close() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/examples/create_grouped_ioc_with_attached_sl_tp.py b/examples/create_grouped_ioc_with_attached_sl_tp.py new file mode 100644 index 0000000..4fd9012 --- /dev/null +++ b/examples/create_grouped_ioc_with_attached_sl_tp.py @@ -0,0 +1,69 @@ +import asyncio +from lighter.signer_client import CreateOrderTxReq +from utils import default_example_setup + + +async def main(): + client, api_client, _ = default_example_setup() + + # Sell some ETH at $2500 + # The size of the SL/TP orders will be equal to the size of the executed order + + # set SL trigger price at 5000 and limit price at 5050 + # set TP trigger price at 1500 and limit price at 1550 + # Note: set the limit price to be higher than the SL/TP trigger price to ensure the order will be filled + # If the mark price of ETH reaches 1500, there might be no one willing to sell you ETH at 1500, so trying to buy at 1550 would increase the fill rate + + ioc_order = CreateOrderTxReq( + MarketIndex=0, + ClientOrderIndex=0, + BaseAmount=1000, # 0.1 ETH + Price=2500_00, # $2500 + IsAsk=1, # sell + Type=client.ORDER_TYPE_LIMIT, + TimeInForce=client.ORDER_TIME_IN_FORCE_IMMEDIATE_OR_CANCEL, + ReduceOnly=0, + TriggerPrice=0, + OrderExpiry=0, + ) + + # Create a One-Cancels-the-Other grouped order with a take-profit and a stop-loss order + take_profit_order = CreateOrderTxReq( + MarketIndex=0, + ClientOrderIndex=0, + BaseAmount=0, + Price=1550_00, + IsAsk=0, + Type=client.ORDER_TYPE_TAKE_PROFIT_LIMIT, + TimeInForce=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, + ReduceOnly=1, + TriggerPrice=1500_00, + OrderExpiry=-1, + ) + + stop_loss_order = CreateOrderTxReq( + MarketIndex=0, + ClientOrderIndex=0, + BaseAmount=0, + Price=5050_00, + IsAsk=0, + Type=client.ORDER_TYPE_STOP_LOSS_LIMIT, + TimeInForce=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, + ReduceOnly=1, + TriggerPrice=5000_00, + OrderExpiry=-1, + ) + + transaction = await client.create_grouped_orders( + grouping_type=client.GROUPING_TYPE_ONE_TRIGGERS_A_ONE_CANCELS_THE_OTHER, + orders=[ioc_order, take_profit_order, stop_loss_order], + ) + + print("Create Grouped Order Tx:", transaction) + + await client.close() + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/create_grouped_orders.py b/examples/create_grouped_orders.py deleted file mode 100644 index 6dfa3a5..0000000 --- a/examples/create_grouped_orders.py +++ /dev/null @@ -1,60 +0,0 @@ -import asyncio -import lighter -import logging - -from lighter.signer_client import CreateOrderTxReq - -logging.basicConfig(level=logging.DEBUG) - -# The API_KEY_PRIVATE_KEY provided belongs to a dummy account registered on Testnet. -# It was generated using the setup_system.py script, and serves as an example. -BASE_URL = "https://testnet.zklighter.elliot.ai" -API_KEY_PRIVATE_KEY = "0xed636277f3753b6c0275f7a28c2678a7f3a95655e09deaebec15179b50c5da7f903152e50f594f7b" -ACCOUNT_INDEX = 65 -API_KEY_INDEX = 3 - -async def main(): - client = lighter.SignerClient( - url=BASE_URL, - private_key=API_KEY_PRIVATE_KEY, - account_index=ACCOUNT_INDEX, - api_key_index=API_KEY_INDEX, - ) - - # Create a One-Cancels-the-Other grouped order with a take-profit and a stop-loss order - take_profit_order = CreateOrderTxReq( - MarketIndex=0, - ClientOrderIndex=0, - BaseAmount=1000, - Price=300000, - IsAsk=0, - Type=lighter.SignerClient.ORDER_TYPE_TAKE_PROFIT_LIMIT, - TimeInForce=lighter.SignerClient.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, - ReduceOnly=1, - TriggerPrice=300000, - OrderExpiry=-1, - ) - - stop_loss_order = CreateOrderTxReq( - MarketIndex=0, - ClientOrderIndex=0, - BaseAmount=1000, - Price=500000, - IsAsk=0, - Type=lighter.SignerClient.ORDER_TYPE_STOP_LOSS_LIMIT, - TimeInForce=lighter.SignerClient.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, - ReduceOnly=1, - TriggerPrice=500000, - OrderExpiry=-1, - ) - - transaction = await client.create_grouped_orders( - grouping_type=lighter.SignerClient.GROUPING_TYPE_ONE_CANCELS_THE_OTHER, - orders=[take_profit_order, stop_loss_order], - ) - - print("Create Grouped Order Tx:", transaction) - await client.close() - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/examples/create_market_order.py b/examples/create_market_order.py deleted file mode 100644 index 069d2db..0000000 --- a/examples/create_market_order.py +++ /dev/null @@ -1,39 +0,0 @@ -import asyncio -import logging -import lighter - -logging.basicConfig(level=logging.DEBUG) - -# The API_KEY_PRIVATE_KEY provided belongs to a dummy account registered on Testnet. -# It was generated using the setup_system.py script, and serves as an example. -BASE_URL = "https://testnet.zklighter.elliot.ai" -API_KEY_PRIVATE_KEY = "0xed636277f3753b6c0275f7a28c2678a7f3a95655e09deaebec15179b50c5da7f903152e50f594f7b" -ACCOUNT_INDEX = 65 -API_KEY_INDEX = 3 - - -def trim_exception(e: Exception) -> str: - return str(e).strip().split("\n")[-1] - - -async def main(): - client = lighter.SignerClient( - url=BASE_URL, - private_key=API_KEY_PRIVATE_KEY, - account_index=ACCOUNT_INDEX, - api_key_index=API_KEY_INDEX, - ) - - tx = await client.create_market_order( - market_index=0, - client_order_index=0, - base_amount=1000, # 0.1 ETH - avg_execution_price=170000, # $1700 -- worst acceptable price for the order - is_ask=True, - ) - print("Create Order Tx:", tx) - await client.close() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/examples/create_market_order_eth_buy.py b/examples/create_market_order_eth_buy.py new file mode 100644 index 0000000..32a6128 --- /dev/null +++ b/examples/create_market_order_eth_buy.py @@ -0,0 +1,28 @@ +import asyncio +from utils import default_example_setup + + +async def main(): + client, api_client, _ = default_example_setup() + client.check_client() + + # Note: change this to 2048 to trade spot ETH. Make sure you have at least 0.1 ETH to trade spot. + market_index = 0 + + tx, tx_hash, err = await client.create_market_order( + market_index=market_index, + client_order_index=0, + base_amount=1000, # 0.1 ETH + avg_execution_price=4000_00, # $4000 -- worst acceptable price for the order + is_ask=False, + ) + print(f"Create Order {tx=} {tx_hash=} {err=}") + if err is not None: + raise Exception(err) + + await client.close() + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/create_market_order_eth_sell.py b/examples/create_market_order_eth_sell.py new file mode 100644 index 0000000..1eac770 --- /dev/null +++ b/examples/create_market_order_eth_sell.py @@ -0,0 +1,28 @@ +import asyncio +from utils import default_example_setup + + +async def main(): + client, api_client, _ = default_example_setup() + client.check_client() + + # Note: change this to 2048 to trade spot ETH. Make sure you have at least 0.1 ETH to trade spot. + market_index = 0 + + tx, tx_hash, err = await client.create_market_order( + market_index=market_index, + client_order_index=0, + base_amount=1000, # 0.1 ETH + avg_execution_price=1700_00, # $1700 -- worst acceptable price for the order + is_ask=True, + ) + print(f"Create Order {tx=} {tx_hash=} {err=}") + if err is not None: + raise Exception(err) + + await client.close() + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/create_market_order_max_slippage.py b/examples/create_market_order_max_slippage.py index f219a22..b05fa40 100644 --- a/examples/create_market_order_max_slippage.py +++ b/examples/create_market_order_max_slippage.py @@ -1,33 +1,21 @@ import asyncio -import logging -import lighter - -logging.basicConfig(level=logging.DEBUG) - -# The API_KEY_PRIVATE_KEY provided belongs to a dummy account registered on Testnet. -# It was generated using the setup_system.py script, and serves as an example. -BASE_URL = "https://testnet.zklighter.elliot.ai" -API_KEY_PRIVATE_KEY = "0xe0fa55e11d6b5575d54c0500bd2f3b240221ae90241e3b573f2307e27de20c04ea628de3f1936e56" -ACCOUNT_INDEX = 22 -API_KEY_INDEX = 3 - - -def trim_exception(e: Exception) -> str: - return str(e).strip().split("\n")[-1] +from utils import default_example_setup async def main(): - client = lighter.SignerClient( - url=BASE_URL, - private_key=API_KEY_PRIVATE_KEY, - account_index=ACCOUNT_INDEX, - api_key_index=API_KEY_INDEX, - ) + client, api_client, _ = default_example_setup() # tx = await client.create_market_order_limited_slippage(market_index=0, client_order_index=0, base_amount=30000000, # max_slippage=0.001, is_ask=True) - tx = await client.create_market_order_if_slippage(market_index=0, client_order_index=0, base_amount=30000000, - max_slippage=0.01, is_ask=True, ideal_price=300000) + tx = await client.create_market_order_if_slippage( + market_index=0, # ETH + client_order_index=0, + base_amount=1000, # 0.1 ETH + max_slippage=0.01, # 1% + is_ask=True, + ideal_price=300000 # $3000 + ) + print("Create Order Tx:", tx) await client.close() diff --git a/examples/create_modify_cancel_order_http.py b/examples/create_modify_cancel_order_http.py new file mode 100644 index 0000000..4cab96d --- /dev/null +++ b/examples/create_modify_cancel_order_http.py @@ -0,0 +1,65 @@ +import asyncio +from utils import default_example_setup + + +async def main(): + client, api_client, _ = default_example_setup() + client.check_client() + + # Note: change this to 2048 to trade spot ETH. Make sure you have at least 0.1 ETH to trade spot. + market_index = 0 + + # create order + api_key_index, nonce = client.nonce_manager.next_nonce() + tx, tx_hash, err = await client.create_order( + market_index=market_index, + client_order_index=123, + base_amount=1000, # 0.1 ETH + price=4050_00, # $4050 + is_ask=True, + order_type=client.ORDER_TYPE_LIMIT, + time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, + reduce_only=False, + trigger_price=0, + nonce=nonce, + api_key_index=api_key_index, + ) + print(f"Create Order {tx=} {tx_hash=} {err=}") + if err is not None: + raise Exception(err) + + ## modify order + # use the same API key so the TX goes after the create order TX + api_key_index, nonce = client.nonce_manager.next_nonce(api_key_index) + tx, tx_hash, err = await client.modify_order( + market_index=market_index, + order_index=123, + base_amount=1100, # 0.11 ETH + price=4100_00, # $4100 + trigger_price=0, + nonce=nonce, + api_key_index=api_key_index, + ) + print(f"Modify Order {tx=} {tx_hash=} {err=}") + if err is not None: + raise Exception(err) + + ## cancel order + # use the same API key so the TX goes after the modify order TX + api_key_index, nonce = client.nonce_manager.next_nonce(api_key_index) + tx, tx_hash, err = await client.cancel_order( + market_index=market_index, + order_index=123, + nonce=nonce, + api_key_index=api_key_index, + ) + print(f"Cancel Order {tx=} {tx_hash=} {err=}") + if err is not None: + raise Exception(err) + + await client.close() + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/create_modify_cancel_order_ws.py b/examples/create_modify_cancel_order_ws.py new file mode 100644 index 0000000..1c8f2d6 --- /dev/null +++ b/examples/create_modify_cancel_order_ws.py @@ -0,0 +1,72 @@ +import websockets +import asyncio +from utils import default_example_setup, ws_send_tx + + +# this example does the same thing as the create_modify_cancel_order.py example, but sends the TX over WS instead of HTTP +async def main(): + client, api_client, ws_client_promise = default_example_setup() + client.check_client() + + # set up WS client and print a connected message + ws_client: websockets.ClientConnection = await ws_client_promise + print("Received:", await ws_client.recv()) + + # Note: change this to 2048 to trade spot ETH. Make sure you have at least 0.1 ETH to trade spot. + market_index = 0 + + # create order + api_key_index, nonce = client.nonce_manager.next_nonce() + tx_type, tx_info, tx_hash, err = client.sign_create_order( + market_index=market_index, + client_order_index=123, + base_amount=1000, # 0.1 ETH + price=4050_00, # $4050 + is_ask=True, + order_type=client.ORDER_TYPE_LIMIT, + time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, + reduce_only=False, + trigger_price=0, + nonce=nonce, + api_key_index=api_key_index, + ) + if err is not None: + raise Exception(err) + await ws_send_tx(ws_client, tx_type, tx_info, tx_hash) + + ## modify order + # use the same API key so the TX goes after the create order TX + api_key_index, nonce = client.nonce_manager.next_nonce(api_key_index) + tx_type, tx_info, tx_hash, err = client.sign_modify_order( + market_index=market_index, + order_index=123, + base_amount=1100, # 0.11 ETH + price=4100_00, # $4100 + trigger_price=0, + nonce=nonce, + api_key_index=api_key_index, + ) + if err is not None: + raise Exception(err) + await ws_send_tx(ws_client, tx_type, tx_info, tx_hash) + + ## cancel order + # use the same API key so the TX goes after the modify order TX + api_key_index, nonce = client.nonce_manager.next_nonce(api_key_index) + tx_type, tx_info, tx_hash, err = client.sign_cancel_order( + market_index=market_index, + order_index=123, + nonce=nonce, + api_key_index=api_key_index, + ) + if err is not None: + raise Exception(err) + await ws_send_tx(ws_client, tx_type, tx_info, tx_hash) + + await client.close() + await api_client.close() + await ws_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/create_position_tied_sl_tp.py b/examples/create_position_tied_sl_tp.py new file mode 100644 index 0000000..0b691e1 --- /dev/null +++ b/examples/create_position_tied_sl_tp.py @@ -0,0 +1,56 @@ +import asyncio +from lighter.signer_client import CreateOrderTxReq +from utils import default_example_setup + + +async def main(): + client, api_client, _ = default_example_setup() + + # Creates a position tied SL/TP pair + # The SL/TP orders will close your whole position, even if you add/remove from it later on + # if the positions reach 0 or switches from short -> long, the orders are canceled + + # this particular example, sets the SL/TP for a short position + # set SL trigger price at 5000 and limit price at 5050 + # set TP trigger price at 1500 and limit price at 1550 + # Note: set the limit price to be higher than the SL/TP trigger price to ensure the order will be filled + # If the mark price of ETH reaches 1500, there might be no one willing to sell you ETH at 1500, so trying to buy at 1550 would increase the fill rate + + # Create a One-Cancels-the-Other grouped order with a take-profit and a stop-loss order + take_profit_order = CreateOrderTxReq( + MarketIndex=0, + ClientOrderIndex=0, + BaseAmount=0, + Price=1550_00, + IsAsk=0, + Type=client.ORDER_TYPE_TAKE_PROFIT_LIMIT, + TimeInForce=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, + ReduceOnly=1, + TriggerPrice=1500_00, + OrderExpiry=-1, + ) + + stop_loss_order = CreateOrderTxReq( + MarketIndex=0, + ClientOrderIndex=0, + BaseAmount=0, + Price=4050_00, + IsAsk=0, + Type=client.ORDER_TYPE_STOP_LOSS_LIMIT, + TimeInForce=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, + ReduceOnly=1, + TriggerPrice=4000_00, + OrderExpiry=-1, + ) + + transaction = await client.create_grouped_orders( + grouping_type=client.GROUPING_TYPE_ONE_CANCELS_THE_OTHER, + orders=[take_profit_order, stop_loss_order], + ) + + print("Create Grouped Order Tx:", transaction) + await client.close() + await api_client.close() + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/create_sl_tp.py b/examples/create_sl_tp.py deleted file mode 100644 index a6b4b6d..0000000 --- a/examples/create_sl_tp.py +++ /dev/null @@ -1,70 +0,0 @@ -import asyncio -import logging -import lighter - -logging.basicConfig(level=logging.DEBUG) - -# The API_KEY_PRIVATE_KEY provided belongs to a dummy account registered on Testnet. -# It was generated using the setup_system.py script, and servers as an example. -BASE_URL = "https://testnet.zklighter.elliot.ai" -API_KEY_PRIVATE_KEY = "0xe0fa55e11d6b5575d54c0500bd2f3b240221ae90241e3b573f2307e27de20c04ea628de3f1936e56" -ACCOUNT_INDEX = 22 -API_KEY_INDEX = 3 - - -def trim_exception(e: Exception) -> str: - return str(e).strip().split("\n")[-1] - - -async def main(): - client = lighter.SignerClient( - url=BASE_URL, - private_key=API_KEY_PRIVATE_KEY, - account_index=ACCOUNT_INDEX, - api_key_index=API_KEY_INDEX, - ) - - tx = await client.create_tp_order( - market_index=0, - client_order_index=0, - base_amount=1000, # 0.1 ETH - trigger_price=500000, - price=500000, - is_ask=False - ) - print("Create Order Tx:", tx) - - - tx = await client.create_sl_order( - market_index=0, - client_order_index=0, - base_amount=1000, # 0.1 ETH - trigger_price=500000, - price=500000, - is_ask=False - ) - print("Create Order Tx:", tx) - - tx = await client.create_tp_limit_order( - market_index=0, - client_order_index=0, - base_amount=1000, # 0.1 ETH - trigger_price=500000, - price=500000, - is_ask=False - ) - - tx = await client.create_sl_limit_order( - market_index=0, - client_order_index=0, - base_amount=1000, # 0.1 ETH - trigger_price=500000, - price=500000, - is_ask=False - ) - print("Create Order Tx:", tx) - await client.close() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/examples/create_with_multiple_keys.py b/examples/create_with_multiple_keys.py index 3a99200..94e0b2e 100644 --- a/examples/create_with_multiple_keys.py +++ b/examples/create_with_multiple_keys.py @@ -1,47 +1,30 @@ +import time import asyncio -import lighter - - -BASE_URL = "https://testnet.zklighter.elliot.ai" -# use examples/system_setup.py or the apikeys page (for mainnet) to generate new api keys -KEYS = { - 5: "API_PRIVATE_KEY_5", - 6: "API_PRIVATE_KEY_6", - 7: "API_PRIVATE_KEY_7", -} -ACCOUNT_INDEX = 100 # replace with your account_index +from utils import default_example_setup async def main(): - client = lighter.SignerClient( - url=BASE_URL, - private_key=KEYS[5], - account_index=ACCOUNT_INDEX, - api_key_index=5, - max_api_key_index=7, - private_keys=KEYS, - ) + client, api_client, _ = default_example_setup() - err = client.check_client() - if err is not None: - print(f"CheckClient error: {err}") - return + # create 20 orders. The client will use as many API keys as it was configured. for i in range(20): res_tuple = await client.create_order( market_index=0, client_order_index=123 + i, - base_amount=100000 + i, - price=385000 + i, + base_amount=1000 + i, # 0.1 ETH + dust + price=3850_00 + i, is_ask=True, - order_type=lighter.SignerClient.ORDER_TYPE_LIMIT, - time_in_force=lighter.SignerClient.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, + order_type=client.ORDER_TYPE_LIMIT, + time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, reduce_only=False, trigger_price=0, ) print(res_tuple) - await client.cancel_all_orders(time_in_force=client.CANCEL_ALL_TIF_IMMEDIATE, time=0) + # wait for orders to be created + time.sleep(1) + await client.cancel_all_orders(time_in_force=client.CANCEL_ALL_TIF_IMMEDIATE, timestamp_ms=0) if __name__ == "__main__": diff --git a/examples/get_info.py b/examples/get_info.py index fd44dd2..057f81e 100644 --- a/examples/get_info.py +++ b/examples/get_info.py @@ -21,23 +21,15 @@ async def account_apis(client: lighter.ApiClient): await print_api(account_instance.account, by="l1_address", value=L1_ADDRESS) await print_api(account_instance.account, by="index", value=str(ACCOUNT_INDEX)) await print_api(account_instance.accounts_by_l1_address, l1_address=L1_ADDRESS) - await print_api(account_instance.apikeys, account_index=ACCOUNT_INDEX, api_key_index=1) - await print_api(account_instance.public_pools, filter="all", limit=1, index=0) + await print_api(account_instance.apikeys, account_index=ACCOUNT_INDEX, api_key_index=3) -async def block_apis(client: lighter.ApiClient): - logging.info("BLOCK APIS") - block_instance = lighter.BlockApi(client) - await print_api(block_instance.block, by="height", value="1") - await print_api(block_instance.blocks, index=0, limit=2, sort="asc") - await print_api(block_instance.current_height) - async def candlestick_apis(client: lighter.ApiClient): logging.info("CANDLESTICK APIS") candlestick_instance = lighter.CandlestickApi(client) await print_api( - candlestick_instance.candlesticks, + candlestick_instance.candles, market_id=0, resolution="1h", start_timestamp=int(datetime.datetime.now().timestamp() - 60 * 60 * 24), @@ -66,15 +58,7 @@ async def order_apis(client: lighter.ApiClient): async def transaction_apis(client: lighter.ApiClient): logging.info("TRANSACTION APIS") transaction_instance = lighter.TransactionApi(client) - await print_api(transaction_instance.block_txs, by="block_height", value="1") - await print_api( - transaction_instance.next_nonce, - account_index=int(ACCOUNT_INDEX), - api_key_index=0, - ) - # use with a valid sequence index - # await print_api(transaction_instance.tx, by="sequence_index", value="5") - await print_api(transaction_instance.txs, index=0, limit=2) + # .... async def funding_apis(client: lighter.ApiClient): logging.info("FUNDING APIS") @@ -84,7 +68,6 @@ async def funding_apis(client: lighter.ApiClient): async def main(): client = lighter.ApiClient(configuration=lighter.Configuration(host="https://testnet.zklighter.elliot.ai")) await account_apis(client) - await block_apis(client) await candlestick_apis(client) await order_apis(client) await transaction_apis(client) diff --git a/examples/margin_eth_20x_cross_http.py b/examples/margin_eth_20x_cross_http.py new file mode 100644 index 0000000..afdb023 --- /dev/null +++ b/examples/margin_eth_20x_cross_http.py @@ -0,0 +1,29 @@ +import asyncio +from utils import default_example_setup + + +async def main(): + client, api_client, _ = default_example_setup() + + # Note: the HTTP method `update_leverage` receives `leverage` as the argument, + # while the WS one that calls `sign_update_leverage` to get the TX to send it directly over WS + # receives `fraction` as the argument, which is 10_000 / leverage + # this was kept this way to not break backwards compatibility. Ideally, they would be consistent. + + tx, tx_hash, err = await client.update_leverage( + market_index=0, + leverage=20, + margin_mode=client.CROSS_MARGIN_MODE + ) + + print(f"Update Leverage {tx=} {tx_hash=} {err=}") + if err is not None: + raise Exception(err) + + await client.close() + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) + diff --git a/examples/margin_eth_50x_isolate_ws.py b/examples/margin_eth_50x_isolate_ws.py new file mode 100644 index 0000000..dd08b4c --- /dev/null +++ b/examples/margin_eth_50x_isolate_ws.py @@ -0,0 +1,33 @@ +import websockets +import asyncio +from utils import default_example_setup, ws_send_tx + + +async def main(): + client, api_client, ws_client_promise = default_example_setup() + + # set up WS client and print a connected message + ws_client: websockets.ClientConnection = await ws_client_promise + print("Received:", await ws_client.recv()) + + # Note: the HTTP method `update_leverage` receives `leverage` as the argument, + # while the WS one that calls `sign_update_leverage` to get the TX to send it directly over WS + # receives `fraction` as the argument, which is 10_000 / leverage + # this was kept this way to not break backwards compatibility. Ideally, they would be consistent. + + tx_type, tx_info, tx_hash, err = client.sign_update_leverage( + market_index=0, + fraction=10_000 // 50, + margin_mode=client.ISOLATED_MARGIN_MODE + ) + if err is not None: + raise Exception(err) + await ws_send_tx(ws_client, tx_type, tx_info, tx_hash) + + await client.close() + await api_client.close() + await ws_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/margin_eth_add_collateral_http.py b/examples/margin_eth_add_collateral_http.py new file mode 100644 index 0000000..c0d1fed --- /dev/null +++ b/examples/margin_eth_add_collateral_http.py @@ -0,0 +1,29 @@ +import asyncio +from utils import default_example_setup + + +async def main(): + client, api_client, _ = default_example_setup() + + # Note: the HTTP method `update_margin` receives `usdc_amount` (float) as the argument, + # while the WS one that calls `sign_update_margin` to get the TX to send it directly over WS + # receives `usdc_amount` (int) as the argument, which is the float one * 1_000_000 + # this was kept this way to not break backwards compatibility. Ideally, they would be consistent. + + tx, tx_hash, err = await client.update_margin( + market_index=0, + usdc_amount=10.5, + direction=client.ISOLATED_MARGIN_ADD_COLLATERAL + ) + + print(f"Update Margin {tx=} {tx_hash=} {err=}") + if err is not None: + raise Exception(err) + + await client.close() + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) + diff --git a/examples/margin_eth_remove_collateral_ws.py b/examples/margin_eth_remove_collateral_ws.py new file mode 100644 index 0000000..11dbadc --- /dev/null +++ b/examples/margin_eth_remove_collateral_ws.py @@ -0,0 +1,32 @@ +import asyncio +import websockets +from utils import default_example_setup, ws_send_tx + + +async def main(): + client, api_client, ws_client_promise = default_example_setup() + + # set up WS client and print a connected message + ws_client: websockets.ClientConnection = await ws_client_promise + print("Received:", await ws_client.recv()) + + # Note: the HTTP method `update_margin` receives `usdc_amount` (float) as the argument, + # while the WS one that calls `sign_update_margin` to get the TX to send it directly over WS + # receives `usdc_amount` (int) as the argument, which is the float one * 1_000_000 + # this was kept this way to not break backwards compatibility. Ideally, they would be consistent. + + tx_type, tx_info, tx_hash, err = client.sign_update_margin( + market_index=0, + usdc_amount=5_000_000, # 5 USDC + direction=client.ISOLATED_MARGIN_REMOVE_COLLATERAL + ) + if err is not None: + raise Exception(err) + await ws_send_tx(ws_client, tx_type, tx_info, tx_hash) + + await client.close() + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/public_pool_create_modify.py b/examples/public_pool_create_modify.py new file mode 100644 index 0000000..dbffee7 --- /dev/null +++ b/examples/public_pool_create_modify.py @@ -0,0 +1,59 @@ +import time +import json +import asyncio +import lighter +from utils import default_example_setup + + +async def main(): + client, api_client, _ = default_example_setup() + tx_api = lighter.TransactionApi(api_client) + + err = client.check_client() + if err is not None: + print(f"CheckClient error: {err}") + return + + auth, _ = client.create_auth_token_with_expiry() + + # create a public pool + tx_info, response, err = await client.create_public_pool( + operator_fee=100000, # 10% + initial_total_shares=1_000_000, # 1000 USDC + min_operator_share_rate=100, # 1% + ) + if err is not None: + raise Exception(f'failed to create public pool {err}') + tx_hash = response.tx_hash + print(f"✅ send create public pool tx. hash: {tx_hash}") + + # fetch pool account index from tx hash + pool_account_index = -1 + for i in range(10): + time.sleep(1) + try: + response = await tx_api.tx(by="hash", value=tx_hash) + event_info_j = json.loads(response.event_info) + pool_account_index = event_info_j['a'] + except Exception as e: + pass + if pool_account_index != -1: + break + if pool_account_index == -1: + raise Exception(f"failed to find pool account index for tx {tx_hash}") + print(f"✅ pool account index: {pool_account_index}") + + # Note: ❗️operator_fee can only decrease + # modify pool metadata + tx_info, response, err = await client.update_public_pool( + public_pool_index=pool_account_index, + status=0, # 0 is active | 1 is frozen + operator_fee=50000, # 5% + min_operator_share_rate=1000, # 10% + ) + if err is not None: + raise Exception(f'failed to create update pool {err}') + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/public_pool_deposit.py b/examples/public_pool_deposit.py new file mode 100644 index 0000000..dae44fe --- /dev/null +++ b/examples/public_pool_deposit.py @@ -0,0 +1,25 @@ +import asyncio + +from utils import default_example_setup + +POOL_ACCOUNT_INDEX = 281474976710651 + + +async def main(): + client, api_client, _ = default_example_setup() + + err = client.check_client() + if err is not None: + print(f"CheckClient error: {err}") + return + + tx_info, response, err = await client.mint_shares(public_pool_index=POOL_ACCOUNT_INDEX, share_amount=10_000) + if err is not None: + raise Exception(f'failed to mint shares {err}') + + await client.close() + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/public_pool_info.py b/examples/public_pool_info.py new file mode 100644 index 0000000..e519407 --- /dev/null +++ b/examples/public_pool_info.py @@ -0,0 +1,33 @@ +import asyncio +import lighter +from utils import default_example_setup + +POOL_ACCOUNT_INDEX = 281474976710651 + + +async def main(): + client, api_client, _ = default_example_setup() + account_api = lighter.AccountApi(api_client) + + err = client.check_client() + if err is not None: + print(f"CheckClient error: {err}") + return + + account = await account_api.account(by="index", value=str(client.account_index)) + + # Note: ❗️shares field does not return the shared you have in pools that you're the operator + for pool in account.accounts[0].shares: + pool_resp = await account_api.account(by="index", value=str(pool.public_pool_index)) + pool_account = pool_resp.accounts[0] + + share_price = float(pool_account.total_asset_value) / float(pool_account.pool_info.total_shares) + print( + f"poolAccountId: {pool.public_pool_index} numShared: {pool.shares_amount} sharePrice: {share_price:.6f} value: {share_price * pool.shares_amount:.2f} pnl: {share_price * pool.shares_amount - float(pool.entry_usdc):.2f}") + + await client.close() + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/public_pool_withdraw.py b/examples/public_pool_withdraw.py new file mode 100644 index 0000000..f3ce3f3 --- /dev/null +++ b/examples/public_pool_withdraw.py @@ -0,0 +1,26 @@ +import asyncio +from utils import default_example_setup + +POOL_ACCOUNT_INDEX = 281474976710651 + + +async def main(): + client, api_client, _ = default_example_setup() + + err = client.check_client() + if err is not None: + print(f"CheckClient error: {err}") + return + + auth, _ = client.create_auth_token_with_expiry() + + tx_info, response, err = await client.burn_shares(public_pool_index=POOL_ACCOUNT_INDEX, share_amount=10_000) + if err is not None: + raise Exception(f'failed to mint shares {err}') + + await client.close() + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/read-only-auth/.gitignore b/examples/read-only-auth/.gitignore new file mode 100644 index 0000000..94a2dd1 --- /dev/null +++ b/examples/read-only-auth/.gitignore @@ -0,0 +1 @@ +*.json \ No newline at end of file diff --git a/examples/read-only-auth/README.md b/examples/read-only-auth/README.md new file mode 100644 index 0000000..90d3208 --- /dev/null +++ b/examples/read-only-auth/README.md @@ -0,0 +1,168 @@ +# Read-Only Auth Token Pre-Generation + +This example demonstrates how to pre-generate authentication tokens for read-only operations on the Lighter platform. By generating tokens ahead of time, you can avoid needing access to your API private keys during runtime for read-only queries. + +## Overview + +Authentication tokens on Lighter have a maximum expiry of 8 hours. This example allows you to: + +1. Configure a dedicated API key (index 253) for all your accounts +2. Pre-generate authentication tokens for future time periods +3. Use these tokens for read-only operations without exposing your private keys + +The tokens are generated at 6-hour intervals (aligned to Unix timestamp // 6 hours), with each token valid for 8 hours. This provides an overlap period ensuring continuous coverage. + +## Setup + +The setup script configures API key 253 for all accounts associated with your Ethereum private key. + +### Running Setup + +```bash +cd examples/read-only-auth +python3 setup.py config.json +``` + +This will: +- Query all accounts for your L1 address +- Generate new API key pairs for each account +- Change API key 253 to use the new keys +- Output configuration in JSON format + +### Configuration Variables + +Edit the constants in `setup.py`: + +```python +BASE_URL = "https://testnet.zklighter.elliot.ai" +ETH_PRIVATE_KEY = "your_ethereum_private_key_here" +API_KEY_INDEX = 253 # Using 253 as it's typically unused +``` + +### Config Format + +```json +{ + "BASE_URL": "https://testnet.zklighter.elliot.ai", + "ACCOUNTS": [ + { + "api_key_private_key": "...", + "account_index": 0, + "api_key_index": 253 + }, + { + "api_key_private_key": "...", + "account_index": 1, + "api_key_index": 253 + } + ] +} +``` + +## Generating Tokens + +The generation script creates authentication tokens for future time periods. + +### Running Generation + +```bash +NUM_DAYS=10 python3 generate.py config.json +``` + +If no config file is specified, it defaults to `config.json`. + +### Duration Configuration + +You can specify the duration in days using the `NUM_DAYS` environment variable, as in the command above. +If the value is not specified, it defaults to 28 days. + +### Output Format + +The script generates `auth-tokens.json`: + +```json +{ + "0": { + "1697184000": "auth_token_string_1", + "1697205600": "auth_token_string_2", + "1697227200": "auth_token_string_3" + }, + "1": { + "1697184000": "auth_token_string_1", + "1697205600": "auth_token_string_2" + } +} +``` + +Where: +- First level key: account index +- Second level key: Unix timestamp (aligned to 6-hour boundaries) +- Value: authentication token + +## Usage + +### Looking Up Tokens + +Check the `get_auth_token.py` script which prints the Auth Token that should be used **at this moment**, as this will be invalidated in at most 8 hours. + +### Time Alignment + +All timestamps are aligned to 6-hour boundaries: +- Timestamps are divisible by 21600 seconds (6 hours) +- Calculation: `unix_timestamp // (6 * 3600) * (6 * 3600)` +- This ensures consistent token lookup across different systems + +### Token Expiry + +Each token is valid for 8 hours from its timestamp: +- Token timestamp: aligned to 6-hour boundary +- Valid until: timestamp + 8 hours +- This provides 2 hours of overlap between consecutive tokens + +## Security + +### API Key 253 + +We use API key index 253 because: +- It's the last available index [0-253] +- It's not typically used by trading +- Easy to remember for this specific use case +- Easy to change and invalidate all tokens. + +### Invalidating Tokens + +To invalidate all existing tokens: + +```bash +python3 setup.py config.json +``` + +Re-running the setup script generates new API keys for index 253, which invalidates all previously generated authentication tokens. This is useful if: +- You suspect your tokens have been compromised +- You want to rotate your tokens periodically +- You need to revoke access immediately + +### Best Practices + +1. **Store tokens securely**: The `auth-tokens.json` file contains sensitive data (read only, but still) +2. **Dedicated API key**: Use API key 253 for read-only token generation, as it can be invalidated easely. + + +## Troubleshooting + +### "Account not found" error + +Make sure your Ethereum private key corresponds to an account registered on the Lighter platform. + +### "Failed to change API key" error + +This could happen if: +- The API key change transaction failed +- Network connectivity issues +- The account is not active + +## Additional Notes + +- Tokens are specific to each account index +- Each account has its own set of time-aligned tokens +- The system uses the SignerClient's native `create_auth_token_with_expiry` method diff --git a/examples/read-only-auth/generate.py b/examples/read-only-auth/generate.py new file mode 100644 index 0000000..bd5c407 --- /dev/null +++ b/examples/read-only-auth/generate.py @@ -0,0 +1,103 @@ +import asyncio +import json +import logging +import os +import time +import sys +import lighter + +logging.basicConfig(level=logging.INFO, force=True) + + +def create_auth_token_for_timestamp(signer_client, timestamp, expiry_hours): + auth_token, error = signer_client.create_auth_token_with_expiry(expiry_hours * 3600, timestamp=timestamp) + if error is not None: + raise Exception(f"Failed to create auth token: {error}") + return auth_token + + +async def generate_tokens_for_account(account_info, base_url, duration_days): + account_index = account_info["account_index"] + api_key_private_key = account_info["api_key_private_key"] + api_key_index = account_info["api_key_index"] + + logging.info(f"Generating tokens for account {account_index}") + + signer_client = lighter.SignerClient( + url=base_url, + private_key=api_key_private_key, + account_index=account_index, + api_key_index=api_key_index, + ) + + current_time = int(time.time()) + interval_seconds = 6 * 3600 + start_timestamp = (current_time // interval_seconds) * interval_seconds + + num_tokens = 4 * duration_days + expiry_hours = 8 + + tokens = {} + for i in range(num_tokens): + timestamp = start_timestamp + (i * interval_seconds) + try: + auth_token = create_auth_token_for_timestamp(signer_client, timestamp, expiry_hours) + tokens[str(timestamp)] = auth_token + logging.debug(f"Generated token for timestamp {timestamp}") + except Exception as e: + logging.error(f"Failed to generate token for timestamp {timestamp}: {e}") + + await signer_client.close() + + return account_index, tokens + + +async def main(): + config_file = "config.json" + if len(sys.argv) > 1: + config_file = sys.argv[1] + + try: + with open(config_file, "r") as f: + config = json.load(f) + except FileNotFoundError: + logging.error(f"Config file '{config_file}' not found") + logging.error("Run setup.py first: python3 setup.py > config.json") + sys.exit(1) + except json.JSONDecodeError as e: + logging.error(f"Invalid JSON in config file: {e}") + sys.exit(1) + + num_days = int(os.getenv("NUM_DAYS") or 28) + base_url = config.get("BASE_URL") + accounts = config.get("ACCOUNTS", []) + duration_days = config.get("DURATION_IN_DAYS", num_days) + + if not base_url: + logging.error("BASE_URL not found in config") + sys.exit(1) + + if not accounts: + logging.error("No accounts found in config") + sys.exit(1) + + logging.info(f"Generating tokens for {len(accounts)} account(s)") + logging.info(f"Duration: {duration_days} days ({4 * duration_days} tokens per account)") + + auth_tokens = {} + for account_info in accounts: + account_index, tokens = await generate_tokens_for_account(account_info, base_url, duration_days) + auth_tokens[str(account_index)] = tokens + + output_file = "auth-tokens.json" + with open(output_file, "w") as f: + json.dump(auth_tokens, f, indent=2) + + logging.info(f"Successfully generated tokens and saved to {output_file}") + logging.info(f"Total accounts: {len(auth_tokens)}") + for account_index, tokens in auth_tokens.items(): + logging.info(f" Account {account_index}: {len(tokens)} tokens") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/read-only-auth/get_auth_token.py b/examples/read-only-auth/get_auth_token.py new file mode 100644 index 0000000..e12522a --- /dev/null +++ b/examples/read-only-auth/get_auth_token.py @@ -0,0 +1,30 @@ +import json +import logging +import sys +import time + +logging.basicConfig(level=logging.INFO, force=True) + + +def main(): + if len(sys.argv) == 1: + logging.error("No account index specified") + return + + account_index = sys.argv[1] + + # Load pre-generated tokens + with open('auth-tokens.json') as f: + auth_tokens = json.load(f) + + # Get current aligned timestamp (6-hour boundary) + current_timestamp = (int(time.time()) // (6 * 3600)) * (6 * 3600) + + # Look up token for specific account + auth_token = auth_tokens[account_index][str(current_timestamp)] + + print(f"{auth_token=}") + + +if __name__ == "__main__": + main() diff --git a/examples/read-only-auth/setup.py b/examples/read-only-auth/setup.py new file mode 100644 index 0000000..31790ad --- /dev/null +++ b/examples/read-only-auth/setup.py @@ -0,0 +1,113 @@ +import asyncio +import json +import logging +import sys +import time +import eth_account +import lighter + +logging.basicConfig(level=logging.INFO, force=True) + +# use https://mainnet.zklighter.elliot.ai for mainnet +BASE_URL = "https://testnet.zklighter.elliot.ai" +ETH_PRIVATE_KEY = "1234567812345678123456781234567812345678123456781234567812345678" +API_KEY_INDEX = 253 + + +async def setup_account(eth_private_key, account_index, base_url, api_key_index): + private_key, public_key, err = lighter.create_api_key() + if err is not None: + return None, f"Failed to create API key for account {account_index}: {err}" + + tx_client = lighter.SignerClient( + url=base_url, + private_key=private_key, + account_index=account_index, + api_key_index=api_key_index, + ) + + response, err = await tx_client.change_api_key( + eth_private_key=eth_private_key, + new_pubkey=public_key, + ) + if err is not None: + await tx_client.close() + return None, f"Failed to change API key for account {account_index}: {err}" + + time.sleep(5) + + err = tx_client.check_client() + if err is not None: + await tx_client.close() + return None, f"Failed to verify API key for account {account_index}: {err}" + + await tx_client.close() + + return { + "api_key_private_key": private_key, + "account_index": account_index, + "api_key_index": api_key_index, + }, None + + +async def main(): + config_file = "config.json" + if len(sys.argv) > 1: + config_file = sys.argv[1] + + api_client = lighter.ApiClient(configuration=lighter.Configuration(host=BASE_URL)) + eth_acc = eth_account.Account.from_key(ETH_PRIVATE_KEY) + eth_address = eth_acc.address + + try: + response = await lighter.AccountApi(api_client).accounts_by_l1_address( + l1_address=eth_address + ) + except lighter.ApiException as e: + if e.data.message == "account not found": + print(f"error: account not found for {eth_address}", file=__import__('sys').stderr) + await api_client.close() + return + else: + await api_client.close() + raise e + + if len(response.sub_accounts) == 0: + print(f"error: no accounts found for {eth_address}", file=__import__('sys').stderr) + await api_client.close() + return + + logging.info(f"Found {len(response.sub_accounts)} account(s)") + + # don't do this async + accounts = [] + for sub_account in response.sub_accounts: + logging.info(f"Setting up account index: {sub_account.index}") + result, err = await setup_account( + ETH_PRIVATE_KEY, + sub_account.index, + BASE_URL, + API_KEY_INDEX, + ) + + if err is not None: + logging.error(err) + else: + accounts.append(result) + + if not accounts: + print("error: failed to setup any accounts", file=__import__('sys').stderr) + await api_client.close() + return + + with open(config_file, "w", encoding="utf-8") as f: + json.dump({ + "BASE_URL": BASE_URL, + "ACCOUNTS": accounts, + }, f, ensure_ascii=False, indent=2) + + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/send_batch_tx_http.py b/examples/send_batch_tx_http.py new file mode 100644 index 0000000..d9ac8c1 --- /dev/null +++ b/examples/send_batch_tx_http.py @@ -0,0 +1,156 @@ +import asyncio +import time +from utils import default_example_setup, trim_exception + + +# this example does the same thing as the send_batch_tx_ws.py example, but sends the TX over HTTP instead of WS +async def main(): + client, api_client, _ = default_example_setup() + + # Note: change this to 2048 to trade spot ETH. Make sure you have at least 0.1 ETH to trade spot. + market_index = 0 + + api_key_index, nonce = client.nonce_manager.next_nonce() + ask_tx_type, ask_tx_info, ask_tx_hash, error = client.sign_create_order( + market_index=market_index, + client_order_index=1001, # Unique identifier for this order + base_amount=1000, # 0.1 ETH + price=5000_00, # $5000 + is_ask=True, + order_type=client.ORDER_TYPE_LIMIT, + time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, + reduce_only=False, + trigger_price=0, + nonce=nonce, + api_key_index=api_key_index, + ) + + if error is not None: + print(f"Error signing ask order (first batch): {trim_exception(error)}") + return + + # intentionally pass api_key_index to the client.nonce_manager so it increases the nonce, without changing the API key. + # in batch TXs, all TXs must come from the same API key. + api_key_index, nonce = client.nonce_manager.next_nonce(api_key_index) + bid_tx_type, bid_tx_info, bid_tx_hash, error = client.sign_create_order( + market_index=market_index, + client_order_index=1002, # Different unique identifier + base_amount=1000, # 0.1 ETH + price=1500_00, # $1500 + is_ask=False, + order_type=client.ORDER_TYPE_LIMIT, + time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, + reduce_only=False, + trigger_price=0, + nonce=nonce, + api_key_index=api_key_index, + ) + + if error is not None: + print(f"Error signing second order (first batch): {trim_exception(error)}") + return + + tx_types = [ask_tx_type, bid_tx_type] + tx_infos = [ask_tx_info, bid_tx_info] + tx_hashes = [ask_tx_hash, bid_tx_hash] + + try: + response = await client.send_tx_batch(tx_types=tx_types, tx_infos=tx_infos) + print(f"Batch transaction successful: {response} expected: {tx_hashes}") + except Exception as e: + print(f"Error sending batch transaction: {trim_exception(e)}") + + # In case we want to see the changes in the UI, sleep a bit + time.sleep(5) + + # since this is a new batch, we can request a fresh API key + api_key_index, nonce = client.nonce_manager.next_nonce() + cancel_tx_type, cancel_tx_info, cancel_tx_hash, error = client.sign_cancel_order( + market_index=market_index, + order_index=1001, # the index of the order we want cancelled + nonce=nonce, + api_key_index=api_key_index, + ) + + if error is not None: + print(f"Error signing first order (second batch): {trim_exception(error)}") + return + + # intentionally pass api_key_index to the client.nonce_manager so it increases the nonce, without changing the API key. + # in batch TXs, all TXs must come from the same API key. + api_key_index, nonce = client.nonce_manager.next_nonce(api_key_index) + new_ask_tx_type, new_ask_tx_info, new_ask_tx_hash, error = client.sign_create_order( + market_index=market_index, + client_order_index=1003, # Different unique identifier + base_amount=2000, # 0.2 ETH + price=5500_00, # $5500 + is_ask=True, + order_type=client.ORDER_TYPE_LIMIT, + time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, + reduce_only=False, + trigger_price=0, + nonce=nonce, + api_key_index=api_key_index, + ) + + if error is not None: + print(f"Error signing second order (second batch): {trim_exception(error)}") + return + + tx_types = [cancel_tx_type, new_ask_tx_type] + tx_infos = [cancel_tx_info, new_ask_tx_info] + tx_hashes = [cancel_tx_hash, new_ask_tx_hash] + + try: + response = await client.send_tx_batch(tx_types=tx_types, tx_infos=tx_infos) + print(f"Batch transaction successful: {response} expected: {tx_hashes}") + except Exception as e: + print(f"Error sending batch transaction: {trim_exception(e)}") + + # In case we want to see the changes in the UI, sleep a bit + time.sleep(5) + + # since this is a new batch, we can request a fresh API key + api_key_index, nonce = client.nonce_manager.next_nonce() + cancel_1_tx_type, cancel_1_tx_info, cancel_1_tx_hash, error = client.sign_cancel_order( + market_index=market_index, + order_index=1002, # the index of the order we want cancelled + nonce=nonce, + api_key_index=api_key_index, + ) + + if error is not None: + print(f"Error signing first order (third batch): {trim_exception(error)}") + return + + api_key_index, nonce = client.nonce_manager.next_nonce(api_key_index) + cancel_2_tx_type, cancel_2_tx_info, cancel_2_tx_hash, error = client.sign_cancel_order( + market_index=market_index, + order_index=1003, # the index of the order we want cancelled + nonce=nonce, + api_key_index=api_key_index, + ) + + if error is not None: + print(f"Error signing second order (third batch): {trim_exception(error)}") + return + + tx_types = [cancel_1_tx_type, cancel_2_tx_type] + tx_infos = [cancel_1_tx_info, cancel_2_tx_info] + tx_hashes = [cancel_1_tx_hash, cancel_2_tx_hash] + + try: + response = await client.send_tx_batch(tx_types=tx_types, tx_infos=tx_infos) + print(f"Batch transaction successful: {response} expected: {tx_hashes}") + except Exception as e: + print(f"Error sending batch transaction: {trim_exception(e)}") + + + # Clean up + await client.close() + await api_client.close() + + +# Run the async main function +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/send_batch_tx_ws.py b/examples/send_batch_tx_ws.py new file mode 100644 index 0000000..8266b53 --- /dev/null +++ b/examples/send_batch_tx_ws.py @@ -0,0 +1,150 @@ +import websockets +import asyncio +import time + +from utils import default_example_setup, ws_send_batch_tx, trim_exception + + +# this example does the same thing as the send_batch_tx_http.py example, but sends the TX over WS instead of HTTP +async def main(): + client, api_client, ws_client_promise = default_example_setup() + + # set up WS client and print a connected message + ws_client: websockets.ClientConnection = await ws_client_promise + print("Received:", await ws_client.recv()) + + # Note: change this to 2048 to trade spot ETH. Make sure you have at least 0.1 ETH to trade spot. + market_index = 2048 + + api_key_index, nonce = client.nonce_manager.next_nonce() + ask_tx_type, ask_tx_info, ask_tx_hash, error = client.sign_create_order( + market_index=market_index, + client_order_index=1001, # Unique identifier for this order + base_amount=1000, # 0.1 ETH + price=5000_00, # $5000 + is_ask=True, + order_type=client.ORDER_TYPE_LIMIT, + time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, + reduce_only=False, + trigger_price=0, + nonce=nonce, + api_key_index=api_key_index, + ) + + if error is not None: + print(f"Error signing ask order (first batch): {trim_exception(error)}") + return + + # intentionally pass api_key_index to the client.nonce_manager so it increases the nonce, without changing the API key. + # in batch TXs, all TXs must come from the same API key. + api_key_index, nonce = client.nonce_manager.next_nonce(api_key_index) + bid_tx_type, bid_tx_info, bid_tx_hash, error = client.sign_create_order( + market_index=market_index, + client_order_index=1002, # Different unique identifier + base_amount=1000, # 0.1 ETH + price=1500_00, # $1500 + is_ask=False, + order_type=client.ORDER_TYPE_LIMIT, + time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, + reduce_only=False, + trigger_price=0, + nonce=nonce, + api_key_index=api_key_index, + ) + + if error is not None: + print(f"Error signing second order (first batch): {trim_exception(error)}") + return + + tx_types = [ask_tx_type, bid_tx_type] + tx_infos = [ask_tx_info, bid_tx_info] + tx_hashes = [ask_tx_hash, bid_tx_hash] + + await ws_send_batch_tx(ws_client, tx_types, tx_infos, tx_hashes) + + # In case we want to see the changes in the UI, sleep a bit + time.sleep(5) + + # since this is a new batch, we can request a fresh API key + api_key_index, nonce = client.nonce_manager.next_nonce() + cancel_tx_type, cancel_tx_info, cancel_tx_hash, error = client.sign_cancel_order( + market_index=market_index, + order_index=1001, # the index of the order we want cancelled + nonce=nonce, + api_key_index=api_key_index, + ) + + if error is not None: + print(f"Error signing first order (second batch): {trim_exception(error)}") + return + + # intentionally pass api_key_index to the client.nonce_manager so it increases the nonce, without changing the API key. + # in batch TXs, all TXs must come from the same API key. + api_key_index, nonce = client.nonce_manager.next_nonce(api_key_index) + new_ask_tx_type, new_ask_tx_info, new_ask_tx_hash, error = client.sign_create_order( + market_index=market_index, + client_order_index=1003, # Different unique identifier + base_amount=2000, # 0.2 ETH + price=5500_00, # $5500 + is_ask=True, + order_type=client.ORDER_TYPE_LIMIT, + time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, + reduce_only=False, + trigger_price=0, + nonce=nonce, + api_key_index=api_key_index, + ) + + if error is not None: + print(f"Error signing second order (second batch): {trim_exception(error)}") + return + + tx_types = [cancel_tx_type, new_ask_tx_type] + tx_infos = [cancel_tx_info, new_ask_tx_info] + tx_hashes = [cancel_tx_hash, new_ask_tx_hash] + + await ws_send_batch_tx(ws_client, tx_types, tx_infos, tx_hashes) + + # In case we want to see the changes in the UI, sleep a bit + time.sleep(5) + + # since this is a new batch, we can request a fresh API key + api_key_index, nonce = client.nonce_manager.next_nonce() + cancel_1_tx_type, cancel_1_tx_info, cancel_1_tx_hash, error = client.sign_cancel_order( + market_index=market_index, + order_index=1002, # the index of the order we want cancelled + nonce=nonce, + api_key_index=api_key_index, + ) + + if error is not None: + print(f"Error signing first order (third batch): {trim_exception(error)}") + return + + api_key_index, nonce = client.nonce_manager.next_nonce(api_key_index) + cancel_2_tx_type, cancel_2_tx_info, cancel_2_tx_hash, error = client.sign_cancel_order( + market_index=market_index, + order_index=1003, # the index of the order we want cancelled + nonce=nonce, + api_key_index=api_key_index, + ) + + if error is not None: + print(f"Error signing second order (third batch): {trim_exception(error)}") + return + + tx_types = [cancel_1_tx_type, cancel_2_tx_type] + tx_infos = [cancel_1_tx_info, cancel_2_tx_info] + tx_hashes = [cancel_1_tx_hash, cancel_2_tx_hash] + + await ws_send_batch_tx(ws_client, tx_types, tx_infos, tx_hashes) + + + # Clean up + await client.close() + await api_client.close() + await ws_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/send_tx_batch.py b/examples/send_tx_batch.py deleted file mode 100644 index b6bc3e7..0000000 --- a/examples/send_tx_batch.py +++ /dev/null @@ -1,138 +0,0 @@ -import asyncio -import logging -import lighter -import json - -logging.basicConfig(level=logging.DEBUG) - -# The API_KEY_PRIVATE_KEY provided belongs to a dummy account registered on Testnet. -# It was generated using the setup_system.py script, and servers as an example. -BASE_URL = "https://testnet.zklighter.elliot.ai" -API_KEY_PRIVATE_KEY = "0xed636277f3753b6c0275f7a28c2678a7f3a95655e09deaebec15179b50c5da7f903152e50f594f7b" -ACCOUNT_INDEX = 65 -API_KEY_INDEX = 1 - -def trim_exception(e: Exception) -> str: - return str(e).strip().split("\n")[-1] - - -async def main(): - # Initialize configuration and clients - configuration = lighter.Configuration(BASE_URL) - api_client = lighter.ApiClient(configuration) - transaction_api = lighter.TransactionApi(api_client) - - # Initialize signer client - client = lighter.SignerClient( - url=BASE_URL, - private_key=API_KEY_PRIVATE_KEY, - account_index=ACCOUNT_INDEX, - api_key_index=API_KEY_INDEX - ) - - # Check client connection - err = client.check_client() - if err is not None: - print(f"CheckClient error: {trim_exception(err)}") - return - - # use next nonce for getting nonces - next_nonce = await transaction_api.next_nonce(account_index=ACCOUNT_INDEX, api_key_index=API_KEY_INDEX) - nonce_value = next_nonce.nonce - - ask_tx_info, error = client.sign_create_order( - market_index=0, - client_order_index=1001, # Unique identifier for this order - base_amount=100000, - price=280000, - is_ask=True, - order_type=client.ORDER_TYPE_LIMIT, - time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, - reduce_only=False, - trigger_price=0, - nonce=nonce_value - ) - nonce_value += 1 - - if error is not None: - print(f"Error signing first order (first batch): {trim_exception(error)}") - return - - # Sign second order - bid_tx_info, error = client.sign_create_order( - market_index=0, - client_order_index=1002, # Different unique identifier - base_amount=200000, - price=200000, - is_ask=False, - order_type=client.ORDER_TYPE_LIMIT, - time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, - reduce_only=False, - trigger_price=0, - nonce=nonce_value - ) - nonce_value += 1 - - if error is not None: - print(f"Error signing second order (first batch): {trim_exception(error)}") - return - - tx_types = json.dumps([client.TX_TYPE_CREATE_ORDER, client.TX_TYPE_CREATE_ORDER]) - tx_infos = json.dumps([ask_tx_info, bid_tx_info]) - - try: - tx_hashes = await transaction_api.send_tx_batch(tx_types=tx_types, tx_infos=tx_infos) - print(f"Batch transaction successful: {tx_hashes}") - except Exception as e: - print(f"Error sending batch transaction: {trim_exception(e)}") - - # In case we want to see the changes in the UI, sleep a bit - import time - time.sleep(5) - - cancel_tx_info, error = client.sign_cancel_order( - market_index=0, - order_index=1001, # the index of the order we want cancelled - nonce=nonce_value - ) - nonce_value += 1 - - if error is not None: - print(f"Error signing first order (second batch): {trim_exception(error)}") - return - - # Sign second order - new_ask_tx_info, error = client.sign_create_order( - market_index=0, - client_order_index=1003, # Different unique identifier - base_amount=300000, - price=310000, - is_ask=True, - order_type=client.ORDER_TYPE_LIMIT, - time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, - reduce_only=False, - trigger_price=0, - nonce=nonce_value - ) - nonce_value += 1 - - if error is not None: - print(f"Error signing second order (second batch): {trim_exception(error)}") - return - - tx_types = json.dumps([client.TX_TYPE_CANCEL_ORDER, client.TX_TYPE_CREATE_ORDER]) - tx_infos = json.dumps([cancel_tx_info, new_ask_tx_info]) - - try: - tx_hashes = await transaction_api.send_tx_batch(tx_types=tx_types, tx_infos=tx_infos) - print(f"Batch 2 transaction successful: {tx_hashes}") - except Exception as e: - print(f"Error sending batch transaction 2: {trim_exception(e)}") - - # Clean up - await client.close() - await api_client.close() - -# Run the async main function -if __name__ == "__main__": - asyncio.run(main()) \ No newline at end of file diff --git a/examples/spot_get_account_assets_http.py b/examples/spot_get_account_assets_http.py new file mode 100644 index 0000000..dd5d1d6 --- /dev/null +++ b/examples/spot_get_account_assets_http.py @@ -0,0 +1,31 @@ +import logging +import asyncio +import lighter +from utils import default_example_setup + + +async def main(): + client, api_client, _ = default_example_setup() + logging.basicConfig(level=logging.INFO) + + account_api = lighter.AccountApi(api_client) + response = await account_api.account(by="index", value=str(client.account_index)) + if len(response.accounts) == 0: + raise "No account found" + + account = response.accounts[0] + # Note: cross-account value does not take into account isolated positions, but total does + print("=== perp assets ===") + print(f"total: {account.total_asset_value} available: {account.available_balance}") + print(f"cross: {account.cross_asset_value} isolated: {float(account.total_asset_value) - float(account.cross_asset_value)}") + + # Spot Assets + print("=== spot assets ===") + for asset in account.assets: + print(f"{asset.symbol} total: {asset.balance} available: {float(asset.balance) - float(asset.locked_balance)}") + + await client.close() + await api_client.close() + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/spot_get_account_assets_ws.py b/examples/spot_get_account_assets_ws.py new file mode 100644 index 0000000..de5522e --- /dev/null +++ b/examples/spot_get_account_assets_ws.py @@ -0,0 +1,53 @@ +import json +import logging +import asyncio +import websockets + +from lighter.models import WSAccountAssets +from utils import default_example_setup, ws_subscribe, ws_ping + + +async def consume_messages(ws): + while True: + msg_str = await ws.recv() + if isinstance(msg_str, str): + msg = json.loads(msg_str) + else: + raise msg_str + + # handle ping here; if we receive, send pong + if msg["type"] == "ping": + await ws_ping(ws) + continue + + # handle account_all_assets updates -- just print stuff + if msg["type"] == "subscribed/account_all_assets" or msg["type"] == "update/account_all_assets" : + o = WSAccountAssets.from_dict(msg) + for asset in o.assets.values(): + print(f"{asset.symbol} total: {asset.balance} available: {float(asset.balance) - float(asset.locked_balance)} accountId: {o.account_id}") + + +async def main(): + client, api_client, ws_client_promise = default_example_setup() + logging.basicConfig(level=logging.INFO) + + # set up WS client and print a connected message + ws_client: websockets.ClientConnection = await ws_client_promise + await ws_client.recv() + + consume_task = asyncio.create_task(consume_messages(ws_client)) + + auth, _ = client.create_auth_token_with_expiry() + await ws_subscribe(ws_client, f"account_all_assets/{client.account_index}", auth) + + # wait a bit to print messages + await asyncio.sleep(1000) + + consume_task.cancel() + await client.close() + await api_client.close() + await ws_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/spot_get_order_books.py b/examples/spot_get_order_books.py new file mode 100644 index 0000000..d5b84e6 --- /dev/null +++ b/examples/spot_get_order_books.py @@ -0,0 +1,42 @@ +import logging +import asyncio +import lighter +from lighter import Asset +from utils import default_example_setup + +# This example shows how to fetch order books and assets details +# This information should be enough to be able to trade on Lighter +# Select the market ID accordingly to the symbol. +# For spot markets, the order book contains base asset (ETH) and quote asset (USDC) +# You can use these to keep track of your inventory +async def main(): + client, api_client, _ = default_example_setup() + logging.basicConfig(level=logging.INFO) + + orders_api = lighter.OrderApi(api_client) + response = await orders_api.order_books() + response.order_books.sort(key=lambda x: x.market_id) + + # fetch all assets + assets_response = await orders_api.asset_details() + + assets_dict: dict[int, Asset] = {} + for asset in assets_response.asset_details: + assets_dict[asset.asset_id] = asset + + for order_book in response.order_books: + if order_book.market_type == 'perp': + print(f'symbol={order_book.symbol} id={order_book.market_id} type={order_book.market_type} sizeDecimals={order_book.supported_size_decimals} priceDecimals={order_book.supported_price_decimals}') + else: + print(f'symbol={order_book.symbol} id={order_book.market_id} type={order_book.market_type} sizeDecimals={order_book.supported_size_decimals} priceDecimals={order_book.supported_price_decimals} baseAssetId={order_book.base_asset_id} quoteAssetId={order_book.quote_asset_id}') + b = assets_dict[order_book.base_asset_id] + q = assets_dict[order_book.quote_asset_id] + print(f' baseAsset: symbol={b.symbol} assetId={b.asset_id} decimals={b.decimals} price={b.index_price} min_withdraw={b.min_withdrawal_amount}') + print(f' quoteAsset: symbol={q.symbol} assetId={q.asset_id} decimals={q.decimals} price={q.index_price} min_withdraw={q.min_withdrawal_amount}') + + + await client.close() + await api_client.close() + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/spot_self_transfer_perp_spot.py b/examples/spot_self_transfer_perp_spot.py new file mode 100644 index 0000000..2df6268 --- /dev/null +++ b/examples/spot_self_transfer_perp_spot.py @@ -0,0 +1,30 @@ +import asyncio +from utils import default_example_setup + +async def main(): + client, api_client, _ = default_example_setup() + + err = client.check_client() + if err is not None: + print(f"CheckClient error: {err}") + return + + # You can find more notes on transfers in the README.md file, under `Transfer Notes` + transfer_tx, response, err = await client.transfer_same_master_account( + to_account_index=client.account_index, + asset_id=client.ASSET_ID_USDC, + amount=1.234567, # decimals are added by sdk + route_from=client.ROUTE_PERP, + route_to=client.ROUTE_SPOT, + fee=0, + memo="0x" + "00" * 32, + ) + if err is not None: + raise Exception(f"error transferring {err}") + print(transfer_tx, response) + + lev_tx, response, err = await client.update_leverage(4, client.CROSS_MARGIN_MODE, 3) + print(lev_tx, response, err) + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/examples/spot_self_transfer_spot_perp.py b/examples/spot_self_transfer_spot_perp.py new file mode 100644 index 0000000..cfdc158 --- /dev/null +++ b/examples/spot_self_transfer_spot_perp.py @@ -0,0 +1,35 @@ +import asyncio +from utils import default_example_setup + + + +async def main(): + client, api_client, _ = default_example_setup() + + err = client.check_client() + if err is not None: + print(f"CheckClient error: {err}") + return + + # You can find more notes on transfers in the README.md file, under `Transfer Notes` + transfer_tx, response, err = await client.transfer_same_master_account( + to_account_index=client.account_index, + asset_id=client.ASSET_ID_USDC, + amount=1.234567, # decimals are added by sdk + route_from=client.ROUTE_SPOT, + route_to=client.ROUTE_PERP, + fee=0, + memo="0x" + "00" * 32, + ) + if err is not None: + raise Exception(f"error transferring {err}") + print(transfer_tx, response) + + lev_tx, response, err = await client.update_leverage(4, client.CROSS_MARGIN_MODE, 3) + print(lev_tx, response, err) + + await client.close() + await api_client.close() + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/examples/sub_account_create.py b/examples/sub_account_create.py new file mode 100644 index 0000000..e634b25 --- /dev/null +++ b/examples/sub_account_create.py @@ -0,0 +1,17 @@ +import asyncio +from utils import default_example_setup + + +async def main(): + client, api_client, _ = default_example_setup() + + err = client.check_client() + if err is not None: + print(f"CheckClient error: {err}") + return + + tx_info, response, err = await client.create_sub_account() + print(tx_info, response, err) + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/examples/sub_account_transfer_eth.py b/examples/sub_account_transfer_eth.py new file mode 100644 index 0000000..b5d088a --- /dev/null +++ b/examples/sub_account_transfer_eth.py @@ -0,0 +1,30 @@ +import asyncio +from utils import default_example_setup + +TO_ACCOUNT_INDEX = 281474976710648 + +async def main(): + client, api_client, _ = default_example_setup() + + err = client.check_client() + if err is not None: + print(f"CheckClient error: {err}") + return + + # You can find more notes on transfers in the README.md file, under `Transfer Notes` + transfer_tx, response, err = await client.transfer_same_master_account( + to_account_index=TO_ACCOUNT_INDEX, + asset_id=client.ASSET_ID_ETH, + amount=0.4, # decimals are added by sdk + route_from=client.ROUTE_SPOT, + route_to=client.ROUTE_SPOT, + fee=0, + memo="0x" + "00" * 32, + ) + if err is not None: + raise Exception(f"error transferring {err}") + print(transfer_tx, response) + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/examples/sub_account_transfer_usdc.py b/examples/sub_account_transfer_usdc.py new file mode 100644 index 0000000..6ed8032 --- /dev/null +++ b/examples/sub_account_transfer_usdc.py @@ -0,0 +1,32 @@ +import asyncio +from utils import default_example_setup + +TO_ACCOUNT_INDEX = 281474976710648 + +async def main(): + client, api_client, _ = default_example_setup() + + err = client.check_client() + if err is not None: + print(f"CheckClient error: {err}") + return + + # You can find more notes on transfers in the README.md file, under `Transfer Notes` + transfer_tx, response, err = await client.transfer_same_master_account( + to_account_index=TO_ACCOUNT_INDEX, + asset_id=client.ASSET_ID_USDC, + amount=100, # decimals are added by sdk + route_from=client.ROUTE_PERP, + route_to=client.ROUTE_SPOT, + fee=0, + memo="0x" + "00" * 32, + ) + if err is not None: + raise Exception(f"error transferring {err}") + print(transfer_tx, response) + await client.close() + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/examples/system_setup.py b/examples/system_setup.py index 0896d7d..859274b 100644 --- a/examples/system_setup.py +++ b/examples/system_setup.py @@ -3,15 +3,21 @@ import time import eth_account import lighter +from utils import save_api_key_config logging.basicConfig(level=logging.DEBUG) -# this is a dummy private key which is registered on Testnet. +# this is a dummy private key registered on Testnet. # It serves as a good example BASE_URL = "https://testnet.zklighter.elliot.ai" ETH_PRIVATE_KEY = "1234567812345678123456781234567812345678123456781234567812345678" API_KEY_INDEX = 3 +NUM_API_KEYS = 5 +# If you set this to something other than None, the script will use that account index instead of using the master account index. +# This is useful if you have multiple accounts on the same L1 address or are the owner of a public pool. +# You need to use the private key associated to the master account or the owner of the public pool to change the API keys. +ACCOUNT_INDEX = None async def main(): # verify that the account exists & fetch account index @@ -19,47 +25,58 @@ async def main(): eth_acc = eth_account.Account.from_key(ETH_PRIVATE_KEY) eth_address = eth_acc.address - try: - response = await lighter.AccountApi(api_client).accounts_by_l1_address( - l1_address=eth_address - ) - except lighter.ApiException as e: - if e.data.message == "account not found": - print(f"error: account not found for {eth_address}") - return + if ACCOUNT_INDEX is not None: + account_index = ACCOUNT_INDEX + else: + try: + response = await lighter.AccountApi(api_client).accounts_by_l1_address(l1_address=eth_address) + except lighter.ApiException as e: + if e.data.message == "account not found": + print(f"error: account not found for {eth_address}") + return + else: + raise e + + if len(response.sub_accounts) > 1: + for sub_account in response.sub_accounts: + print(f"found accountIndex: {sub_account.index}") + + account = min(response.sub_accounts, key=lambda x: int(x.index)) + account_index = account.index + print(f"multiple accounts found, using the master account {account_index}") else: - raise e + account_index = response.sub_accounts[0].index - if len(response.sub_accounts) > 1: - for sub_account in response.sub_accounts: - print(f"found accountIndex: {sub_account.index}") - - print("multiple accounts found, using the first one") - account_index = response.sub_accounts[0].index - else: - account_index = response.sub_accounts[0].index # create a private/public key pair for the new API key # pass any string to be used as seed for create_api_key like # create_api_key("Hello world random seed to make things more secure") - private_key, public_key, err = lighter.create_api_key() - if err is not None: - raise Exception(err) + + private_keys = {} + public_keys = [] + + for i in range(NUM_API_KEYS): + private_key, public_key, err = lighter.create_api_key() + if err is not None: + raise Exception(err) + public_keys.append(public_key) + private_keys[API_KEY_INDEX + i] = private_key tx_client = lighter.SignerClient( url=BASE_URL, - private_key=private_key, account_index=account_index, - api_key_index=API_KEY_INDEX, + api_private_keys=private_keys, ) - # change the API key - response, err = await tx_client.change_api_key( - eth_private_key=ETH_PRIVATE_KEY, - new_pubkey=public_key, - ) - if err is not None: - raise Exception(err) + # change all API keys + for i in range(NUM_API_KEYS): + response, err = await tx_client.change_api_key( + eth_private_key=ETH_PRIVATE_KEY, + new_pubkey=public_keys[i], + api_key_index=API_KEY_INDEX + i + ) + if err is not None: + raise Exception(err) # wait some time so that we receive the new API key in the response time.sleep(10) @@ -69,14 +86,7 @@ async def main(): if err is not None: raise Exception(err) - print( - f""" -BASE_URL = '{BASE_URL}' -API_KEY_PRIVATE_KEY = '{private_key}' -ACCOUNT_INDEX = {account_index} -API_KEY_INDEX = {API_KEY_INDEX} - """ - ) + save_api_key_config(BASE_URL, account_index, private_keys) await tx_client.close() await api_client.close() diff --git a/examples/transfer.py b/examples/transfer.py new file mode 100644 index 0000000..0b14d2e --- /dev/null +++ b/examples/transfer.py @@ -0,0 +1,37 @@ +import asyncio +import lighter +from utils import default_example_setup + +ETH_PRIVATE_KEY = "1234567812345678123456781234567812345678123456781234567812345678" +TO_ACCOUNT_INDEX = 9 + + +async def main(): + client, api_client, _ = default_example_setup() + info_api = lighter.InfoApi(api_client) + + auth_token, err = client.create_auth_token_with_expiry() + if err: + raise Exception(f"Auth token failed: {err}") + + fee_info = await info_api.transfer_fee_info(client.account_index, authorization=auth_token, auth=auth_token, to_account_index=TO_ACCOUNT_INDEX) + + # You can find more notes on transfers in the README.md file, under `Transfer Notes` + transfer_tx, response, err = await client.transfer( + eth_private_key=ETH_PRIVATE_KEY, + to_account_index=TO_ACCOUNT_INDEX, + asset_id=client.ASSET_ID_USDC, + route_from=client.ROUTE_PERP, + route_to=client.ROUTE_PERP, + amount=5, # decimals are added by sdk + fee=fee_info.transfer_fee_usdc, + memo="0x" + "00" * 32, + ) + if err is not None: + raise Exception(f"error transferring {err}") + + print(transfer_tx, response) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/transfer_same_master_account.py b/examples/transfer_same_master_account.py new file mode 100644 index 0000000..e3474a9 --- /dev/null +++ b/examples/transfer_same_master_account.py @@ -0,0 +1,37 @@ +import asyncio +import lighter +from utils import default_example_setup + +TO_ACCOUNT_INDEX = 281474976710648 # same master account + + +async def main(): + client, api_client, _ = default_example_setup() + info_api = lighter.InfoApi(api_client) + + auth_token, err = client.create_auth_token_with_expiry() + if err: + raise Exception(f"Auth token failed: {err}") + + fee_info = await info_api.transfer_fee_info(client.account_index, authorization=auth_token, auth=auth_token, to_account_index=TO_ACCOUNT_INDEX) + + # You can find more notes on transfers in the README.md file, under `Transfer Notes` + transfer_tx, response, err = await client.transfer_same_master_account( + to_account_index=TO_ACCOUNT_INDEX, + asset_id=client.ASSET_ID_USDC, + route_from=client.ROUTE_PERP, + route_to=client.ROUTE_PERP, + amount=5, # decimals are added by sdk + fee=fee_info.transfer_fee_usdc, + memo="0x" + "00" * 32, + ) + if err is not None: + raise Exception(f"error transferring {err}") + + print(transfer_tx, response) + await client.close() + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/transfer_update_leverage.py b/examples/transfer_update_leverage.py deleted file mode 100644 index e5593b7..0000000 --- a/examples/transfer_update_leverage.py +++ /dev/null @@ -1,47 +0,0 @@ -import asyncio -import lighter - - -from examples.secrets import BASE_URL, API_KEY_PRIVATE_KEY, ETH_PRIVATE_KEY - -API_KEY_INDEX = 10 -TO_ACCOUNT_INDEX = 9 -ACCOUNT_INDEX = 10 # replace with your account_index - - -async def main(): - client = lighter.SignerClient( - url=BASE_URL, - private_key=API_KEY_PRIVATE_KEY, - account_index=ACCOUNT_INDEX, - api_key_index=API_KEY_INDEX, - ) - api_client = lighter.ApiClient(configuration=lighter.Configuration(host=BASE_URL)) - info_api = lighter.InfoApi(api_client) - order_api = lighter.OrderApi(api_client) - - auth_token, _ = client.create_auth_token_with_expiry() - fee_info = await info_api.transfer_fee_info(ACCOUNT_INDEX, authorization=auth_token, auth=auth_token, to_account_index=TO_ACCOUNT_INDEX) - print(fee_info) - - err = client.check_client() - if err is not None: - print(f"CheckClient error: {err}") - return - memo = "a"*32 # memo is a user message and it has to be exactly 32 bytes long - transfer_tx, response, err = await client.transfer( - ETH_PRIVATE_KEY, - usdc_amount=100, # decimals are added by sdk - to_account_index=TO_ACCOUNT_INDEX, - fee=fee_info.transfer_fee_usdc, - memo=memo, - ) - if err != None: - raise Exception(f"error transferring {err}") - print(transfer_tx, response) - - lev_tx, response, err = await client.update_leverage(4, client.CROSS_MARGIN_MODE, 3) - print(lev_tx, response, err) - -if __name__ == "__main__": - asyncio.run(main()) \ No newline at end of file diff --git a/examples/utils.py b/examples/utils.py new file mode 100644 index 0000000..8ae2f29 --- /dev/null +++ b/examples/utils.py @@ -0,0 +1,100 @@ +from typing import Tuple, Optional +import logging +import json +import websockets +import lighter + + +def trim_exception(e: Exception) -> str: + return str(e).strip().split("\n")[-1] + + +def save_api_key_config(base_url, account_index, private_keys, config_file="./api_key_config.json"): + with open(config_file, "w", encoding="utf-8") as f: + json.dump({ + "baseUrl": base_url, + "accountIndex": account_index, + "privateKeys": private_keys, + }, f, ensure_ascii=False, indent=2) + + +def get_api_key_config(config_file="./api_key_config.json"): + with open(config_file) as f: + cfg = json.load(f) + + private_keys_original = cfg["privateKeys"] + private_key = {} + for key in private_keys_original.keys(): + private_key[int(key)] = private_keys_original[key] + + return cfg["baseUrl"], cfg["accountIndex"], private_key + + +def default_example_setup(config_file="./api_key_config.json") -> Optional[Tuple[lighter.SignerClient, lighter.ApiClient, websockets.connect]]: + logging.basicConfig(level=logging.DEBUG) + + base_url, account_index, private_keys = get_api_key_config(config_file) + api_client = lighter.ApiClient(configuration=lighter.Configuration(host=base_url)) + client = lighter.SignerClient( + url=base_url, + account_index=account_index, + api_private_keys=private_keys, + ) + + err = client.check_client() + if err is not None: + print(f"CheckClient error: {trim_exception(err)}") + return + + return client, api_client, websockets.connect(f"{base_url.replace('https', 'wss')}/stream") + + +async def ws_ping(ws_client: websockets.ClientConnection): + await ws_client.send(json.dumps({"type": "pong"})) + +async def ws_subscribe(ws_client: websockets.ClientConnection, channel: str, auth: Optional[str] = None): + if auth is None: + await ws_client.send(json.dumps({"type": "subscribe", "channel": channel})) + else: + await ws_client.send(json.dumps({"type": "subscribe", "channel": channel, "auth": auth})) + +async def ws_send_tx(ws_client: websockets.ClientConnection, tx_type, tx_info, tx_hash): + # Note: you have the TX Hash from signing the TX + # You can use this TX Hash to check the status of the TX later on + # if the server generates a different hash, the signature will fail, so the hash will always be correct + # because of this, the hash returned by the server will always be the same + await ws_client.send( + json.dumps( + { + "type": "jsonapi/sendtx", + "data": { + "id": f"my_random_id_{12345678}", # optional helps id the response + "tx_type": tx_type, + "tx_info": json.loads(tx_info), + }, + } + ) + ) + + print(f"expectedHash {tx_hash} response {await ws_client.recv()}") + + +async def ws_send_batch_tx(ws_client: websockets.ClientConnection, tx_types, tx_infos, tx_hashes): + # Note: you have the TX Hash from signing the TX + # You can use this TX Hash to check the status of the TX later on + # if the server generates a different hash, the signature will fail, so the hash will always be correct + # because of this, the hash returned by the server will always be the same + await ws_client.send( + json.dumps( + { + "type": "jsonapi/sendtxbatch", + "data": { + "id": f"my_random_id_{12345678}", # optional helps id the response + "tx_types": json.dumps(tx_types), + "tx_infos": json.dumps(tx_infos), + }, + } + ) + ) + + print(f"expectedHash {tx_hashes} response {await ws_client.recv()}") diff --git a/examples/withdraw_fast.py b/examples/withdraw_fast.py new file mode 100644 index 0000000..7532e4e --- /dev/null +++ b/examples/withdraw_fast.py @@ -0,0 +1,104 @@ +import asyncio +import json +import lighter +from utils import default_example_setup + +ETH_PRIVATE_KEY = "1234567812345678123456781234567812345678123456781234567812345678" +WITHDRAW_ADDRESS = "0x0000..." +AMOUNT_USDC = 5.0 + +async def main(): + client, api_client, _ = default_example_setup() + + auth_token, err = client.create_auth_token_with_expiry() + if err: + raise Exception(f"Auth token failed: {err}") + + info_api = lighter.InfoApi(api_client) + + try: + # Get fast withdraw pool + params = api_client.param_serialize( + method='GET', + resource_path='/api/v1/fastwithdraw/info', + query_params=[('account_index', client.account_index)], + header_params={'Authorization': auth_token} + ) + response = await api_client.call_api(*params) + await response.read() + data = response.data + assert data is not None + + # get account to which to send money + pool_info = json.loads(data.decode('utf-8')) + if pool_info.get('code') != 200: + raise Exception(f"Pool info failed: {pool_info.get('message')}") + to_account = pool_info['to_account_index'] + print(f"Pool: {to_account}, Limit: {pool_info.get('withdraw_limit')}") + + # get transfer fee + fee_info = await info_api.transfer_fee_info( + account_index=client.account_index, + to_account_index=to_account, + auth=auth_token + ) + fee = fee_info.transfer_fee_usdc # this is already int + + # Get Nonce & API key -- you can get this using HTTP call as well + api_key_index, nonce = client.nonce_manager.next_nonce() + + # Build memo (20-byte address + 12 zeros) + addr_hex = WITHDRAW_ADDRESS.lower().removeprefix("0x") + addr_bytes = bytes.fromhex(addr_hex) + if len(addr_bytes) != 20: + raise ValueError(f"Invalid address length: {len(addr_bytes)}") + memo_list = list(addr_bytes + b"\x00" * 12) + memo_hex = ''.join(format(b, '02x') for b in memo_list) + + # create TX + tx_type, tx_info_str, tx_hash, err = client.sign_transfer( + eth_private_key=ETH_PRIVATE_KEY, + to_account_index=to_account, + asset_id=client.ASSET_ID_USDC, + route_from=client.ROUTE_PERP, + route_to=client.ROUTE_PERP, + usdc_amount=int(AMOUNT_USDC) * 10 ** 6, + fee=fee, + memo=memo_hex, + api_key_index=api_key_index, + nonce=nonce + ) + if err: + raise Exception(f"L2 signing failed: {err}") + + # Submit + params = api_client.param_serialize( + method='POST', + resource_path='/api/v1/fastwithdraw', + post_params=[ + ('tx_info', tx_info_str), + ('to_address', WITHDRAW_ADDRESS) + ], + header_params={ + 'Authorization': auth_token, + 'Content-Type': 'application/x-www-form-urlencoded' + } + ) + response = await api_client.call_api(*params) + await response.read() + data = response.data + assert data is not None + result = json.loads(data.decode('utf-8')) + + if result.get('code') == 200: + print(f"✓ Success! TX: {result.get('tx_hash')}") + else: + raise Exception(f"Failed: {result.get('message')}") + + finally: + await client.close() + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/examples/withdraw_normal.py b/examples/withdraw_normal.py new file mode 100644 index 0000000..acd3611 --- /dev/null +++ b/examples/withdraw_normal.py @@ -0,0 +1,25 @@ +import asyncio +from utils import default_example_setup + +AMOUNT = 5.0 + +async def main(): + client, api_client, _ = default_example_setup() + + # Note: There is no limit or fee for normal withdrawal + withdraw_tx, response, err = await client.withdraw( + asset_id=client.ASSET_ID_USDC, # change this to `client.ASSET_ID_ETH` to withdraw ETH. Also, change route_type to spot + route_type=client.ROUTE_PERP, # change this to `client.ROUTE_SPOT` to withdraw from spot balance + amount=AMOUNT, + ) + if err is not None: + raise Exception(f"error withdrawing {err}") + + print(withdraw_tx, response) + + await client.close() + await api_client.close() + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/examples/ws_send_batch_tx.py b/examples/ws_send_batch_tx.py deleted file mode 100644 index 375d8fb..0000000 --- a/examples/ws_send_batch_tx.py +++ /dev/null @@ -1,101 +0,0 @@ -import lighter -import json -import websockets -import asyncio - -# The API_KEY_PRIVATE_KEY provided belongs to a dummy account registered on Testnet. -# It was generated using the setup_system.py script, and servers as an example. -# Alternatively, you can go to https://app.lighter.xyz/apikeys for mainnet api keys -BASE_URL = "https://testnet.zklighter.elliot.ai" -API_KEY_PRIVATE_KEY = ( - "0xed636277f3753b6c0275f7a28c2678a7f3a95655e09deaebec15179b50c5da7f903152e50f594f7b" -) -ACCOUNT_INDEX = 65 -API_KEY_INDEX = 1 - - -async def ws_flow(tx_types, tx_infos): - async with websockets.connect(f"{BASE_URL.replace('https', 'wss')}/stream") as ws: - msg = await ws.recv() - print("Received:", msg) - - await ws.send( - json.dumps( - { - "type": "jsonapi/sendtxbatch", - "data": { - "id": f"my_random_batch_id_{12345678}", # optional, helps id the response - "tx_types": json.dumps(tx_types), - "tx_infos": json.dumps(tx_infos), - }, - } - ) - ) - - print("Response:", await ws.recv()) - - -async def main(): - client = lighter.SignerClient( - url=BASE_URL, - private_key=API_KEY_PRIVATE_KEY, - account_index=ACCOUNT_INDEX, - api_key_index=API_KEY_INDEX, - ) - configuration = lighter.Configuration(BASE_URL) - api_client = lighter.ApiClient(configuration) - transaction_api = lighter.TransactionApi(api_client) - - # use next nonce for getting nonces - next_nonce = await transaction_api.next_nonce( - account_index=ACCOUNT_INDEX, api_key_index=API_KEY_INDEX - ) - nonce_value = next_nonce.nonce - - ask_tx_info, error = client.sign_create_order( - market_index=0, - client_order_index=1001, # Unique identifier for this order - base_amount=100000, - price=280000, - is_ask=True, - order_type=client.ORDER_TYPE_LIMIT, - time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, - reduce_only=False, - trigger_price=0, - nonce=nonce_value, - ) - nonce_value += 1 - - if error is not None: - print(f"Error signing first order (first batch): {error}") - return - - # Sign second order - bid_tx_info, error = client.sign_create_order( - market_index=0, - client_order_index=1002, # Different unique identifier - base_amount=200000, - price=200000, - is_ask=False, - order_type=client.ORDER_TYPE_LIMIT, - time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, - reduce_only=False, - trigger_price=0, - nonce=nonce_value, - ) - - if error is not None: - print(f"Error signing second order (first batch): {error}") - return - - tx_types = [ - lighter.SignerClient.TX_TYPE_CREATE_ORDER, - lighter.SignerClient.TX_TYPE_CREATE_ORDER, - ] - tx_infos = [ask_tx_info, bid_tx_info] - - await ws_flow(tx_types, tx_infos) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/examples/ws_send_tx.py b/examples/ws_send_tx.py deleted file mode 100644 index c120b83..0000000 --- a/examples/ws_send_tx.py +++ /dev/null @@ -1,74 +0,0 @@ -import lighter -import json -import websockets -import asyncio - -# The API_KEY_PRIVATE_KEY provided belongs to a dummy account registered on Testnet. -# It was generated using the setup_system.py script, and servers as an example. -# Alternatively, you can go to https://app.lighter.xyz/apikeys for mainnet api keys -BASE_URL = "https://testnet.zklighter.elliot.ai" -API_KEY_PRIVATE_KEY = ( - "0xed636277f3753b6c0275f7a28c2678a7f3a95655e09deaebec15179b50c5da7f903152e50f594f7b" -) -ACCOUNT_INDEX = 65 -API_KEY_INDEX = 3 - - -async def ws_flow(tx_type, tx_info): - async with websockets.connect(f"{BASE_URL.replace('https', 'wss')}/stream") as ws: - msg = await ws.recv() - print("Received:", msg) - - await ws.send( - json.dumps( - { - "type": "jsonapi/sendtx", - "data": { - "id": f"my_random_id_{12345678}", # optional, helps id the response - "tx_type": tx_type, - "tx_info": json.loads(tx_info), - }, - } - ) - ) - - print("Response:", await ws.recv()) - - -async def main(): - client = lighter.SignerClient( - url=BASE_URL, - private_key=API_KEY_PRIVATE_KEY, - account_index=ACCOUNT_INDEX, - api_key_index=API_KEY_INDEX, - ) - configuration = lighter.Configuration(BASE_URL) - api_client = lighter.ApiClient(configuration) - transaction_api = lighter.TransactionApi(api_client) - - next_nonce = await transaction_api.next_nonce( - account_index=ACCOUNT_INDEX, api_key_index=API_KEY_INDEX - ) - nonce_value = next_nonce.nonce - - tx_info, error = client.sign_create_order( - market_index=0, - client_order_index=1002, # Different unique identifier - base_amount=200000, - price=200000, - is_ask=False, - order_type=client.ORDER_TYPE_LIMIT, - time_in_force=client.ORDER_TIME_IN_FORCE_GOOD_TILL_TIME, - reduce_only=False, - trigger_price=0, - nonce=nonce_value, - ) - if error is not None: - print(f"Error signing order: {error}") - return - - await ws_flow(lighter.SignerClient.TX_TYPE_CREATE_ORDER, tx_info) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/lighter/__init__.py b/lighter/__init__.py index a0af3c2..06f063c 100644 --- a/lighter/__init__.py +++ b/lighter/__init__.py @@ -19,14 +19,12 @@ # import apis into sdk package from lighter.api.account_api import AccountApi from lighter.api.announcement_api import AnnouncementApi -from lighter.api.block_api import BlockApi from lighter.api.bridge_api import BridgeApi from lighter.api.candlestick_api import CandlestickApi from lighter.api.funding_api import FundingApi from lighter.api.info_api import InfoApi from lighter.api.notification_api import NotificationApi from lighter.api.order_api import OrderApi -from lighter.api.referral_api import ReferralApi from lighter.api.root_api import RootApi from lighter.api.transaction_api import TransactionApi @@ -44,6 +42,7 @@ # import models into sdk package from lighter.models.account import Account from lighter.models.account_api_keys import AccountApiKeys +from lighter.models.account_asset import AccountAsset from lighter.models.account_limits import AccountLimits from lighter.models.account_margin_stats import AccountMarginStats from lighter.models.account_market_stats import AccountMarketStats @@ -56,13 +55,15 @@ from lighter.models.announcement import Announcement from lighter.models.announcements import Announcements from lighter.models.api_key import ApiKey -from lighter.models.block import Block -from lighter.models.blocks import Blocks +from lighter.models.api_token import ApiToken +from lighter.models.asset import Asset +from lighter.models.asset_details import AssetDetails +from lighter.models.auth import Auth +from lighter.models.bridge import Bridge from lighter.models.bridge_supported_network import BridgeSupportedNetwork -from lighter.models.candlestick import Candlestick -from lighter.models.candlesticks import Candlesticks +from lighter.models.candle import Candle +from lighter.models.candles import Candles from lighter.models.contract_address import ContractAddress -from lighter.models.current_height import CurrentHeight from lighter.models.cursor import Cursor from lighter.models.daily_return import DailyReturn from lighter.models.deposit_history import DepositHistory @@ -83,28 +84,27 @@ from lighter.models.liquidation import Liquidation from lighter.models.liquidation_info import LiquidationInfo from lighter.models.liquidation_infos import LiquidationInfos -from lighter.models.market_info import MarketInfo +from lighter.models.market_config import MarketConfig from lighter.models.next_nonce import NextNonce from lighter.models.order import Order from lighter.models.order_book import OrderBook from lighter.models.order_book_depth import OrderBookDepth -from lighter.models.order_book_detail import OrderBookDetail +from lighter.models.order_book_depth_with_begin_nonce import OrderBookDepthWithBeginNonce from lighter.models.order_book_details import OrderBookDetails from lighter.models.order_book_orders import OrderBookOrders from lighter.models.order_book_stats import OrderBookStats from lighter.models.order_books import OrderBooks from lighter.models.orders import Orders +from lighter.models.perps_market_stats import PerpsMarketStats +from lighter.models.perps_order_book_detail import PerpsOrderBookDetail from lighter.models.pn_l_entry import PnLEntry from lighter.models.position_funding import PositionFunding from lighter.models.position_fundings import PositionFundings from lighter.models.price_level import PriceLevel -from lighter.models.public_pool import PublicPool from lighter.models.public_pool_info import PublicPoolInfo from lighter.models.public_pool_metadata import PublicPoolMetadata from lighter.models.public_pool_share import PublicPoolShare -from lighter.models.public_pools import PublicPools -from lighter.models.referral_point_entry import ReferralPointEntry -from lighter.models.referral_points import ReferralPoints +from lighter.models.req_do_faucet import ReqDoFaucet from lighter.models.req_export_data import ReqExportData from lighter.models.req_get_account import ReqGetAccount from lighter.models.req_get_account_active_orders import ReqGetAccountActiveOrders @@ -115,10 +115,13 @@ from lighter.models.req_get_account_metadata import ReqGetAccountMetadata from lighter.models.req_get_account_pn_l import ReqGetAccountPnL from lighter.models.req_get_account_txs import ReqGetAccountTxs +from lighter.models.req_get_api_tokens import ReqGetApiTokens +from lighter.models.req_get_asset_details import ReqGetAssetDetails from lighter.models.req_get_block import ReqGetBlock from lighter.models.req_get_block_txs import ReqGetBlockTxs +from lighter.models.req_get_bridges_by_l1_addr import ReqGetBridgesByL1Addr from lighter.models.req_get_by_account import ReqGetByAccount -from lighter.models.req_get_candlesticks import ReqGetCandlesticks +from lighter.models.req_get_candles import ReqGetCandles from lighter.models.req_get_deposit_history import ReqGetDepositHistory from lighter.models.req_get_fast_withdraw_info import ReqGetFastWithdrawInfo from lighter.models.req_get_fundings import ReqGetFundings @@ -131,21 +134,25 @@ from lighter.models.req_get_order_book_orders import ReqGetOrderBookOrders from lighter.models.req_get_order_books import ReqGetOrderBooks from lighter.models.req_get_position_funding import ReqGetPositionFunding -from lighter.models.req_get_public_pools import ReqGetPublicPools from lighter.models.req_get_public_pools_metadata import ReqGetPublicPoolsMetadata from lighter.models.req_get_range_with_cursor import ReqGetRangeWithCursor from lighter.models.req_get_range_with_index import ReqGetRangeWithIndex from lighter.models.req_get_range_with_index_sortable import ReqGetRangeWithIndexSortable from lighter.models.req_get_recent_trades import ReqGetRecentTrades -from lighter.models.req_get_referral_points import ReqGetReferralPoints from lighter.models.req_get_trades import ReqGetTrades from lighter.models.req_get_transfer_fee_info import ReqGetTransferFeeInfo from lighter.models.req_get_transfer_history import ReqGetTransferHistory from lighter.models.req_get_tx import ReqGetTx from lighter.models.req_get_withdraw_history import ReqGetWithdrawHistory from lighter.models.resp_change_account_tier import RespChangeAccountTier +from lighter.models.resp_get_api_tokens import RespGetApiTokens +from lighter.models.resp_get_bridges_by_l1_addr import RespGetBridgesByL1Addr from lighter.models.resp_get_fast_bridge_info import RespGetFastBridgeInfo +from lighter.models.resp_get_fastwithdrawal_info import RespGetFastwithdrawalInfo +from lighter.models.resp_get_is_next_bridge_fast import RespGetIsNextBridgeFast +from lighter.models.resp_post_api_token import RespPostApiToken from lighter.models.resp_public_pools_metadata import RespPublicPoolsMetadata +from lighter.models.resp_revoke_api_token import RespRevokeApiToken from lighter.models.resp_send_tx import RespSendTx from lighter.models.resp_send_tx_batch import RespSendTxBatch from lighter.models.resp_withdrawal_delay import RespWithdrawalDelay @@ -154,6 +161,8 @@ from lighter.models.risk_parameters import RiskParameters from lighter.models.share_price import SharePrice from lighter.models.simple_order import SimpleOrder +from lighter.models.spot_market_stats import SpotMarketStats +from lighter.models.spot_order_book_detail import SpotOrderBookDetail from lighter.models.status import Status from lighter.models.sub_accounts import SubAccounts from lighter.models.ticker import Ticker @@ -162,10 +171,8 @@ from lighter.models.transfer_fee_info import TransferFeeInfo from lighter.models.transfer_history import TransferHistory from lighter.models.transfer_history_item import TransferHistoryItem -from lighter.models.tx import Tx from lighter.models.tx_hash import TxHash from lighter.models.tx_hashes import TxHashes -from lighter.models.txs import Txs from lighter.models.validator_info import ValidatorInfo from lighter.models.withdraw_history import WithdrawHistory from lighter.models.withdraw_history_item import WithdrawHistoryItem diff --git a/lighter/api/__init__.py b/lighter/api/__init__.py index a238373..6e2b365 100644 --- a/lighter/api/__init__.py +++ b/lighter/api/__init__.py @@ -3,14 +3,12 @@ # import apis into api package from lighter.api.account_api import AccountApi from lighter.api.announcement_api import AnnouncementApi -from lighter.api.block_api import BlockApi from lighter.api.bridge_api import BridgeApi from lighter.api.candlestick_api import CandlestickApi from lighter.api.funding_api import FundingApi from lighter.api.info_api import InfoApi from lighter.api.notification_api import NotificationApi from lighter.api.order_api import OrderApi -from lighter.api.referral_api import ReferralApi from lighter.api.root_api import RootApi from lighter.api.transaction_api import TransactionApi diff --git a/lighter/api/account_api.py b/lighter/api/account_api.py index c92f6dc..2a689ff 100644 --- a/lighter/api/account_api.py +++ b/lighter/api/account_api.py @@ -27,9 +27,12 @@ from lighter.models.l1_metadata import L1Metadata from lighter.models.liquidation_infos import LiquidationInfos from lighter.models.position_fundings import PositionFundings -from lighter.models.public_pools import PublicPools from lighter.models.resp_change_account_tier import RespChangeAccountTier +from lighter.models.resp_get_api_tokens import RespGetApiTokens +from lighter.models.resp_post_api_token import RespPostApiToken from lighter.models.resp_public_pools_metadata import RespPublicPoolsMetadata +from lighter.models.resp_revoke_api_token import RespRevokeApiToken +from lighter.models.result_code import ResultCode from lighter.models.sub_accounts import SubAccounts from lighter.api_client import ApiClient, RequestSerialized @@ -50,7 +53,6 @@ def __init__(self, api_client=None) -> None: self.api_client = api_client - @validate_call async def account( self, by: StrictStr, @@ -122,7 +124,6 @@ async def account( ).data - @validate_call async def account_with_http_info( self, by: StrictStr, @@ -194,7 +195,6 @@ async def account_with_http_info( ) - @validate_call async def account_without_preload_content( self, by: StrictStr, @@ -330,7 +330,6 @@ def _account_serialize( - @validate_call async def account_limits( self, account_index: StrictInt, @@ -406,7 +405,6 @@ async def account_limits( ).data - @validate_call async def account_limits_with_http_info( self, account_index: StrictInt, @@ -482,7 +480,6 @@ async def account_limits_with_http_info( ) - @validate_call async def account_limits_without_preload_content( self, account_index: StrictInt, @@ -583,13 +580,15 @@ def _account_limits_serialize( _query_params.append(('account_index', account_index)) + if authorization is not None: + + _query_params.append(('authorization', authorization)) + if auth is not None: _query_params.append(('auth', auth)) # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization # process the form parameters # process the body parameter @@ -625,7 +624,6 @@ def _account_limits_serialize( - @validate_call async def account_metadata( self, by: StrictStr, @@ -705,7 +703,6 @@ async def account_metadata( ).data - @validate_call async def account_metadata_with_http_info( self, by: StrictStr, @@ -785,7 +782,6 @@ async def account_metadata_with_http_info( ) - @validate_call async def account_metadata_without_preload_content( self, by: StrictStr, @@ -937,7 +933,6 @@ def _account_metadata_serialize( - @validate_call async def accounts_by_l1_address( self, l1_address: StrictStr, @@ -1005,7 +1000,6 @@ async def accounts_by_l1_address( ).data - @validate_call async def accounts_by_l1_address_with_http_info( self, l1_address: StrictStr, @@ -1073,7 +1067,6 @@ async def accounts_by_l1_address_with_http_info( ) - @validate_call async def accounts_by_l1_address_without_preload_content( self, l1_address: StrictStr, @@ -1200,7 +1193,6 @@ def _accounts_by_l1_address_serialize( - @validate_call async def apikeys( self, account_index: StrictInt, @@ -1272,7 +1264,6 @@ async def apikeys( ).data - @validate_call async def apikeys_with_http_info( self, account_index: StrictInt, @@ -1344,7 +1335,6 @@ async def apikeys_with_http_info( ) - @validate_call async def apikeys_without_preload_content( self, account_index: StrictInt, @@ -1480,7 +1470,6 @@ def _apikeys_serialize( - @validate_call async def change_account_tier( self, account_index: StrictInt, @@ -1560,7 +1549,6 @@ async def change_account_tier( ).data - @validate_call async def change_account_tier_with_http_info( self, account_index: StrictInt, @@ -1640,7 +1628,6 @@ async def change_account_tier_with_http_info( ) - @validate_call async def change_account_tier_without_preload_content( self, account_index: StrictInt, @@ -1799,7 +1786,283 @@ def _change_account_tier_serialize( - @validate_call + async def faucet( + self, + l1_address: StrictStr, + do_l1_transfer: StrictBool, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ResultCode: + """faucet + + Request funds from faucet + + :param l1_address: (required) + :type l1_address: str + :param do_l1_transfer: (required) + :type do_l1_transfer: bool + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._faucet_serialize( + l1_address=l1_address, + do_l1_transfer=do_l1_transfer, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ResultCode", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + async def faucet_with_http_info( + self, + l1_address: StrictStr, + do_l1_transfer: StrictBool, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ResultCode]: + """faucet + + Request funds from faucet + + :param l1_address: (required) + :type l1_address: str + :param do_l1_transfer: (required) + :type do_l1_transfer: bool + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._faucet_serialize( + l1_address=l1_address, + do_l1_transfer=do_l1_transfer, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ResultCode", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + async def faucet_without_preload_content( + self, + l1_address: StrictStr, + do_l1_transfer: StrictBool, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """faucet + + Request funds from faucet + + :param l1_address: (required) + :type l1_address: str + :param do_l1_transfer: (required) + :type do_l1_transfer: bool + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._faucet_serialize( + l1_address=l1_address, + do_l1_transfer=do_l1_transfer, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ResultCode", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _faucet_serialize( + self, + l1_address, + do_l1_transfer, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if l1_address is not None: + + _query_params.append(('l1_address', l1_address)) + + if do_l1_transfer is not None: + + _query_params.append(('do_l1_transfer', do_l1_transfer)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/api/v1/faucet', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + async def l1_metadata( self, l1_address: StrictStr, @@ -1875,7 +2138,6 @@ async def l1_metadata( ).data - @validate_call async def l1_metadata_with_http_info( self, l1_address: StrictStr, @@ -1951,7 +2213,6 @@ async def l1_metadata_with_http_info( ) - @validate_call async def l1_metadata_without_preload_content( self, l1_address: StrictStr, @@ -2094,7 +2355,6 @@ def _l1_metadata_serialize( - @validate_call async def liquidations( self, account_index: StrictInt, @@ -2182,7 +2442,6 @@ async def liquidations( ).data - @validate_call async def liquidations_with_http_info( self, account_index: StrictInt, @@ -2270,7 +2529,6 @@ async def liquidations_with_http_info( ) - @validate_call async def liquidations_without_preload_content( self, account_index: StrictInt, @@ -2382,6 +2640,10 @@ def _liquidations_serialize( # process the path parameters # process the query parameters + if authorization is not None: + + _query_params.append(('authorization', authorization)) + if auth is not None: _query_params.append(('auth', auth)) @@ -2403,8 +2665,6 @@ def _liquidations_serialize( _query_params.append(('limit', limit)) # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization # process the form parameters # process the body parameter @@ -2440,7 +2700,6 @@ def _liquidations_serialize( - @validate_call async def pnl( self, by: StrictStr, @@ -2449,9 +2708,9 @@ async def pnl( start_timestamp: Annotated[int, Field(le=5000000000000, strict=True, ge=0)], end_timestamp: Annotated[int, Field(le=5000000000000, strict=True, ge=0)], count_back: StrictInt, - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, - ignore_transfers: Optional[StrictBool] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, + ignore_transfers: Optional[StrictBool] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -2481,9 +2740,9 @@ async def pnl( :type end_timestamp: int :param count_back: (required) :type count_back: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param ignore_transfers: :type ignore_transfers: bool @@ -2540,7 +2799,6 @@ async def pnl( ).data - @validate_call async def pnl_with_http_info( self, by: StrictStr, @@ -2549,8 +2807,8 @@ async def pnl_with_http_info( start_timestamp: Annotated[int, Field(le=5000000000000, strict=True, ge=0)], end_timestamp: Annotated[int, Field(le=5000000000000, strict=True, ge=0)], count_back: StrictInt, - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, ignore_transfers: Optional[StrictBool] = None, _request_timeout: Union[ None, @@ -2581,9 +2839,9 @@ async def pnl_with_http_info( :type end_timestamp: int :param count_back: (required) :type count_back: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param ignore_transfers: :type ignore_transfers: bool @@ -2640,7 +2898,6 @@ async def pnl_with_http_info( ) - @validate_call async def pnl_without_preload_content( self, by: StrictStr, @@ -2649,8 +2906,8 @@ async def pnl_without_preload_content( start_timestamp: Annotated[int, Field(le=5000000000000, strict=True, ge=0)], end_timestamp: Annotated[int, Field(le=5000000000000, strict=True, ge=0)], count_back: StrictInt, - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, ignore_transfers: Optional[StrictBool] = None, _request_timeout: Union[ None, @@ -2681,9 +2938,9 @@ async def pnl_without_preload_content( :type end_timestamp: int :param count_back: (required) :type count_back: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param ignore_transfers: :type ignore_transfers: bool @@ -2767,6 +3024,10 @@ def _pnl_serialize( # process the path parameters # process the query parameters + if authorization is not None: + + _query_params.append(('authorization', authorization)) + if auth is not None: _query_params.append(('auth', auth)) @@ -2800,8 +3061,6 @@ def _pnl_serialize( _query_params.append(('ignore_transfers', ignore_transfers)) # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization # process the form parameters # process the body parameter @@ -2837,13 +3096,12 @@ def _pnl_serialize( - @validate_call async def position_funding( self, account_index: StrictInt, limit: Annotated[int, Field(le=100, strict=True, ge=1)], - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, market_id: Optional[StrictInt] = None, cursor: Optional[StrictStr] = None, side: Optional[StrictStr] = None, @@ -2868,9 +3126,9 @@ async def position_funding( :type account_index: int :param limit: (required) :type limit: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param market_id: :type market_id: int @@ -2929,13 +3187,12 @@ async def position_funding( ).data - @validate_call async def position_funding_with_http_info( self, account_index: StrictInt, limit: Annotated[int, Field(le=100, strict=True, ge=1)], - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, market_id: Optional[StrictInt] = None, cursor: Optional[StrictStr] = None, side: Optional[StrictStr] = None, @@ -2960,9 +3217,9 @@ async def position_funding_with_http_info( :type account_index: int :param limit: (required) :type limit: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param market_id: :type market_id: int @@ -3021,13 +3278,12 @@ async def position_funding_with_http_info( ) - @validate_call async def position_funding_without_preload_content( self, account_index: StrictInt, limit: Annotated[int, Field(le=100, strict=True, ge=1)], - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, market_id: Optional[StrictInt] = None, cursor: Optional[StrictStr] = None, side: Optional[StrictStr] = None, @@ -3052,9 +3308,9 @@ async def position_funding_without_preload_content( :type account_index: int :param limit: (required) :type limit: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param market_id: :type market_id: int @@ -3138,6 +3394,10 @@ def _position_funding_serialize( # process the path parameters # process the query parameters + if authorization is not None: + + _query_params.append(('authorization', authorization)) + if auth is not None: _query_params.append(('auth', auth)) @@ -3163,8 +3423,6 @@ def _position_funding_serialize( _query_params.append(('side', side)) # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization # process the form parameters # process the body parameter @@ -3200,13 +3458,12 @@ def _position_funding_serialize( - @validate_call - async def public_pools( + async def public_pools_metadata( self, index: StrictInt, limit: Annotated[int, Field(le=100, strict=True, ge=1)], - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, filter: Optional[StrictStr] = None, account_index: Optional[StrictInt] = None, _request_timeout: Union[ @@ -3221,18 +3478,18 @@ async def public_pools( _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> PublicPools: - """publicPools + ) -> RespPublicPoolsMetadata: + """publicPoolsMetadata - Get public pools + Get public pools metadata :param index: (required) :type index: int :param limit: (required) :type limit: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param filter: :type filter: str @@ -3260,7 +3517,7 @@ async def public_pools( :return: Returns the result object. """ # noqa: E501 - _param = self._public_pools_serialize( + _param = self._public_pools_metadata_serialize( index=index, limit=limit, authorization=authorization, @@ -3274,7 +3531,7 @@ async def public_pools( ) _response_types_map: Dict[str, Optional[str]] = { - '200': "PublicPools", + '200': "RespPublicPoolsMetadata", '400': "ResultCode", } response_data = await self.api_client.call_api( @@ -3288,13 +3545,12 @@ async def public_pools( ).data - @validate_call - async def public_pools_with_http_info( + async def public_pools_metadata_with_http_info( self, index: StrictInt, limit: Annotated[int, Field(le=100, strict=True, ge=1)], - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, filter: Optional[StrictStr] = None, account_index: Optional[StrictInt] = None, _request_timeout: Union[ @@ -3309,18 +3565,18 @@ async def public_pools_with_http_info( _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[PublicPools]: - """publicPools + ) -> ApiResponse[RespPublicPoolsMetadata]: + """publicPoolsMetadata - Get public pools + Get public pools metadata :param index: (required) :type index: int :param limit: (required) :type limit: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param filter: :type filter: str @@ -3348,7 +3604,7 @@ async def public_pools_with_http_info( :return: Returns the result object. """ # noqa: E501 - _param = self._public_pools_serialize( + _param = self._public_pools_metadata_serialize( index=index, limit=limit, authorization=authorization, @@ -3362,7 +3618,7 @@ async def public_pools_with_http_info( ) _response_types_map: Dict[str, Optional[str]] = { - '200': "PublicPools", + '200': "RespPublicPoolsMetadata", '400': "ResultCode", } response_data = await self.api_client.call_api( @@ -3376,13 +3632,12 @@ async def public_pools_with_http_info( ) - @validate_call - async def public_pools_without_preload_content( + async def public_pools_metadata_without_preload_content( self, index: StrictInt, limit: Annotated[int, Field(le=100, strict=True, ge=1)], - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, filter: Optional[StrictStr] = None, account_index: Optional[StrictInt] = None, _request_timeout: Union[ @@ -3398,17 +3653,17 @@ async def public_pools_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """publicPools + """publicPoolsMetadata - Get public pools + Get public pools metadata :param index: (required) :type index: int :param limit: (required) :type limit: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param filter: :type filter: str @@ -3436,7 +3691,7 @@ async def public_pools_without_preload_content( :return: Returns the result object. """ # noqa: E501 - _param = self._public_pools_serialize( + _param = self._public_pools_metadata_serialize( index=index, limit=limit, authorization=authorization, @@ -3450,7 +3705,7 @@ async def public_pools_without_preload_content( ) _response_types_map: Dict[str, Optional[str]] = { - '200': "PublicPools", + '200': "RespPublicPoolsMetadata", '400': "ResultCode", } response_data = await self.api_client.call_api( @@ -3460,7 +3715,7 @@ async def public_pools_without_preload_content( return response_data.response - def _public_pools_serialize( + def _public_pools_metadata_serialize( self, index, limit, @@ -3488,6 +3743,10 @@ def _public_pools_serialize( # process the path parameters # process the query parameters + if authorization is not None: + + _query_params.append(('authorization', authorization)) + if auth is not None: _query_params.append(('auth', auth)) @@ -3509,8 +3768,6 @@ def _public_pools_serialize( _query_params.append(('account_index', account_index)) # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization # process the form parameters # process the body parameter @@ -3530,7 +3787,7 @@ def _public_pools_serialize( return self.api_client.param_serialize( method='GET', - resource_path='/api/v1/publicPools', + resource_path='/api/v1/publicPoolsMetadata', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -3546,15 +3803,10 @@ def _public_pools_serialize( - @validate_call - async def public_pools_metadata( + async def tokens( self, - index: StrictInt, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, - filter: Optional[StrictStr] = None, - account_index: Optional[StrictInt] = None, + account_index: StrictInt, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -3567,23 +3819,15 @@ async def public_pools_metadata( _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RespPublicPoolsMetadata: - """publicPoolsMetadata + ) -> RespGetApiTokens: + """tokens - Get public pools metadata + Get api tokens of an account - :param index: (required) - :type index: int - :param limit: (required) - :type limit: int - :param authorization: - :type authorization: str - :param auth: - :type auth: str - :param filter: - :type filter: str - :param account_index: + :param account_index: (required) :type account_index: int + :param authorization: make required after integ is done + :type authorization: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -3606,13 +3850,9 @@ async def public_pools_metadata( :return: Returns the result object. """ # noqa: E501 - _param = self._public_pools_metadata_serialize( - index=index, - limit=limit, - authorization=authorization, - auth=auth, - filter=filter, + _param = self._tokens_serialize( account_index=account_index, + authorization=authorization, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -3620,7 +3860,7 @@ async def public_pools_metadata( ) _response_types_map: Dict[str, Optional[str]] = { - '200': "RespPublicPoolsMetadata", + '200': "RespGetApiTokens", '400': "ResultCode", } response_data = await self.api_client.call_api( @@ -3634,15 +3874,10 @@ async def public_pools_metadata( ).data - @validate_call - async def public_pools_metadata_with_http_info( + async def tokens_with_http_info( self, - index: StrictInt, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, - filter: Optional[StrictStr] = None, - account_index: Optional[StrictInt] = None, + account_index: StrictInt, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -3655,23 +3890,15 @@ async def public_pools_metadata_with_http_info( _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[RespPublicPoolsMetadata]: - """publicPoolsMetadata + ) -> ApiResponse[RespGetApiTokens]: + """tokens - Get public pools metadata + Get api tokens of an account - :param index: (required) - :type index: int - :param limit: (required) - :type limit: int - :param authorization: - :type authorization: str - :param auth: - :type auth: str - :param filter: - :type filter: str - :param account_index: + :param account_index: (required) :type account_index: int + :param authorization: make required after integ is done + :type authorization: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -3694,13 +3921,9 @@ async def public_pools_metadata_with_http_info( :return: Returns the result object. """ # noqa: E501 - _param = self._public_pools_metadata_serialize( - index=index, - limit=limit, - authorization=authorization, - auth=auth, - filter=filter, + _param = self._tokens_serialize( account_index=account_index, + authorization=authorization, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -3708,7 +3931,7 @@ async def public_pools_metadata_with_http_info( ) _response_types_map: Dict[str, Optional[str]] = { - '200': "RespPublicPoolsMetadata", + '200': "RespGetApiTokens", '400': "ResultCode", } response_data = await self.api_client.call_api( @@ -3722,15 +3945,10 @@ async def public_pools_metadata_with_http_info( ) - @validate_call - async def public_pools_metadata_without_preload_content( + async def tokens_without_preload_content( self, - index: StrictInt, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, - filter: Optional[StrictStr] = None, - account_index: Optional[StrictInt] = None, + account_index: StrictInt, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -3744,22 +3962,14 @@ async def public_pools_metadata_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """publicPoolsMetadata + """tokens - Get public pools metadata + Get api tokens of an account - :param index: (required) - :type index: int - :param limit: (required) - :type limit: int - :param authorization: - :type authorization: str - :param auth: - :type auth: str - :param filter: - :type filter: str - :param account_index: + :param account_index: (required) :type account_index: int + :param authorization: make required after integ is done + :type authorization: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -3782,13 +3992,9 @@ async def public_pools_metadata_without_preload_content( :return: Returns the result object. """ # noqa: E501 - _param = self._public_pools_metadata_serialize( - index=index, - limit=limit, - authorization=authorization, - auth=auth, - filter=filter, + _param = self._tokens_serialize( account_index=account_index, + authorization=authorization, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -3796,7 +4002,7 @@ async def public_pools_metadata_without_preload_content( ) _response_types_map: Dict[str, Optional[str]] = { - '200': "RespPublicPoolsMetadata", + '200': "RespGetApiTokens", '400': "ResultCode", } response_data = await self.api_client.call_api( @@ -3806,14 +4012,10 @@ async def public_pools_metadata_without_preload_content( return response_data.response - def _public_pools_metadata_serialize( + def _tokens_serialize( self, - index, - limit, - authorization, - auth, - filter, account_index, + authorization, _request_auth, _content_type, _headers, @@ -3834,22 +4036,6 @@ def _public_pools_metadata_serialize( # process the path parameters # process the query parameters - if auth is not None: - - _query_params.append(('auth', auth)) - - if filter is not None: - - _query_params.append(('filter', filter)) - - if index is not None: - - _query_params.append(('index', index)) - - if limit is not None: - - _query_params.append(('limit', limit)) - if account_index is not None: _query_params.append(('account_index', account_index)) @@ -3876,7 +4062,654 @@ def _public_pools_metadata_serialize( return self.api_client.param_serialize( method='GET', - resource_path='/api/v1/publicPoolsMetadata', + resource_path='/api/v1/tokens', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + async def tokens_create( + self, + name: StrictStr, + account_index: StrictInt, + expiry: StrictInt, + sub_account_access: StrictBool, + authorization: Optional[StrictStr] = None, + scopes: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RespPostApiToken: + """tokens_create + + Create api token + + :param name: (required) + :type name: str + :param account_index: (required) + :type account_index: int + :param expiry: (required) + :type expiry: int + :param sub_account_access: (required) + :type sub_account_access: bool + :param authorization: + :type authorization: str + :param scopes: + :type scopes: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._tokens_create_serialize( + name=name, + account_index=account_index, + expiry=expiry, + sub_account_access=sub_account_access, + authorization=authorization, + scopes=scopes, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespPostApiToken", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + async def tokens_create_with_http_info( + self, + name: StrictStr, + account_index: StrictInt, + expiry: StrictInt, + sub_account_access: StrictBool, + authorization: Optional[StrictStr] = None, + scopes: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[RespPostApiToken]: + """tokens_create + + Create api token + + :param name: (required) + :type name: str + :param account_index: (required) + :type account_index: int + :param expiry: (required) + :type expiry: int + :param sub_account_access: (required) + :type sub_account_access: bool + :param authorization: + :type authorization: str + :param scopes: + :type scopes: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._tokens_create_serialize( + name=name, + account_index=account_index, + expiry=expiry, + sub_account_access=sub_account_access, + authorization=authorization, + scopes=scopes, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespPostApiToken", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + async def tokens_create_without_preload_content( + self, + name: StrictStr, + account_index: StrictInt, + expiry: StrictInt, + sub_account_access: StrictBool, + authorization: Optional[StrictStr] = None, + scopes: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """tokens_create + + Create api token + + :param name: (required) + :type name: str + :param account_index: (required) + :type account_index: int + :param expiry: (required) + :type expiry: int + :param sub_account_access: (required) + :type sub_account_access: bool + :param authorization: + :type authorization: str + :param scopes: + :type scopes: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._tokens_create_serialize( + name=name, + account_index=account_index, + expiry=expiry, + sub_account_access=sub_account_access, + authorization=authorization, + scopes=scopes, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespPostApiToken", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _tokens_create_serialize( + self, + name, + account_index, + expiry, + sub_account_access, + authorization, + scopes, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + if authorization is not None: + _header_params['authorization'] = authorization + # process the form parameters + if name is not None: + _form_params.append(('name', name)) + if account_index is not None: + _form_params.append(('account_index', account_index)) + if expiry is not None: + _form_params.append(('expiry', expiry)) + if sub_account_access is not None: + _form_params.append(('sub_account_access', sub_account_access)) + if scopes is not None: + _form_params.append(('scopes', scopes)) + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'multipart/form-data' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/api/v1/tokens/create', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + async def tokens_revoke( + self, + token_id: StrictInt, + account_index: StrictInt, + authorization: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RespRevokeApiToken: + """tokens_revoke + + Revoke api token + + :param token_id: (required) + :type token_id: int + :param account_index: (required) + :type account_index: int + :param authorization: + :type authorization: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._tokens_revoke_serialize( + token_id=token_id, + account_index=account_index, + authorization=authorization, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespRevokeApiToken", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + async def tokens_revoke_with_http_info( + self, + token_id: StrictInt, + account_index: StrictInt, + authorization: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[RespRevokeApiToken]: + """tokens_revoke + + Revoke api token + + :param token_id: (required) + :type token_id: int + :param account_index: (required) + :type account_index: int + :param authorization: + :type authorization: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._tokens_revoke_serialize( + token_id=token_id, + account_index=account_index, + authorization=authorization, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespRevokeApiToken", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + async def tokens_revoke_without_preload_content( + self, + token_id: StrictInt, + account_index: StrictInt, + authorization: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """tokens_revoke + + Revoke api token + + :param token_id: (required) + :type token_id: int + :param account_index: (required) + :type account_index: int + :param authorization: + :type authorization: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._tokens_revoke_serialize( + token_id=token_id, + account_index=account_index, + authorization=authorization, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespRevokeApiToken", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _tokens_revoke_serialize( + self, + token_id, + account_index, + authorization, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + if authorization is not None: + _header_params['authorization'] = authorization + # process the form parameters + if token_id is not None: + _form_params.append(('token_id', token_id)) + if account_index is not None: + _form_params.append(('account_index', account_index)) + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'multipart/form-data' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/api/v1/tokens/revoke', path_params=_path_params, query_params=_query_params, header_params=_header_params, diff --git a/lighter/api/announcement_api.py b/lighter/api/announcement_api.py index 7eaa982..2f62113 100644 --- a/lighter/api/announcement_api.py +++ b/lighter/api/announcement_api.py @@ -36,7 +36,6 @@ def __init__(self, api_client=None) -> None: self.api_client = api_client - @validate_call async def announcement( self, _request_timeout: Union[ @@ -100,7 +99,6 @@ async def announcement( ).data - @validate_call async def announcement_with_http_info( self, _request_timeout: Union[ @@ -164,7 +162,6 @@ async def announcement_with_http_info( ) - @validate_call async def announcement_without_preload_content( self, _request_timeout: Union[ diff --git a/lighter/api/block_api.py b/lighter/api/block_api.py deleted file mode 100644 index e09888a..0000000 --- a/lighter/api/block_api.py +++ /dev/null @@ -1,863 +0,0 @@ -# coding: utf-8 - -""" - - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - -import warnings -from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt -from typing import Any, Dict, List, Optional, Tuple, Union -from typing_extensions import Annotated - -from pydantic import Field, StrictInt, StrictStr, field_validator -from typing import Optional -from typing_extensions import Annotated -from lighter.models.blocks import Blocks -from lighter.models.current_height import CurrentHeight - -from lighter.api_client import ApiClient, RequestSerialized -from lighter.api_response import ApiResponse -from lighter.rest import RESTResponseType - - -class BlockApi: - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None) -> None: - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - - @validate_call - async def block( - self, - by: StrictStr, - value: StrictStr, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> Blocks: - """block - - Get block by its height or commitment - - :param by: (required) - :type by: str - :param value: (required) - :type value: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._block_serialize( - by=by, - value=value, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Blocks", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - await response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - async def block_with_http_info( - self, - by: StrictStr, - value: StrictStr, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[Blocks]: - """block - - Get block by its height or commitment - - :param by: (required) - :type by: str - :param value: (required) - :type value: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._block_serialize( - by=by, - value=value, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Blocks", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - await response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - async def block_without_preload_content( - self, - by: StrictStr, - value: StrictStr, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """block - - Get block by its height or commitment - - :param by: (required) - :type by: str - :param value: (required) - :type value: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._block_serialize( - by=by, - value=value, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Blocks", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _block_serialize( - self, - by, - value, - _request_auth, - _content_type, - _headers, - _host_index, - ) -> RequestSerialized: - - _host = None - - _collection_formats: Dict[str, str] = { - } - - _path_params: Dict[str, str] = {} - _query_params: List[Tuple[str, str]] = [] - _header_params: Dict[str, Optional[str]] = _headers or {} - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - # process the query parameters - if by is not None: - - _query_params.append(('by', by)) - - if value is not None: - - _query_params.append(('value', value)) - - # process the header parameters - # process the form parameters - # process the body parameter - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - - # authentication setting - _auth_settings: List[str] = [ - ] - - return self.api_client.param_serialize( - method='GET', - resource_path='/api/v1/block', - path_params=_path_params, - query_params=_query_params, - header_params=_header_params, - body=_body_params, - post_params=_form_params, - files=_files, - auth_settings=_auth_settings, - collection_formats=_collection_formats, - _host=_host, - _request_auth=_request_auth - ) - - - - - @validate_call - async def blocks( - self, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], - index: Optional[StrictInt] = None, - sort: Optional[StrictStr] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> Blocks: - """blocks - - Get blocks - - :param limit: (required) - :type limit: int - :param index: - :type index: int - :param sort: - :type sort: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._blocks_serialize( - limit=limit, - index=index, - sort=sort, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Blocks", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - await response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - async def blocks_with_http_info( - self, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], - index: Optional[StrictInt] = None, - sort: Optional[StrictStr] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[Blocks]: - """blocks - - Get blocks - - :param limit: (required) - :type limit: int - :param index: - :type index: int - :param sort: - :type sort: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._blocks_serialize( - limit=limit, - index=index, - sort=sort, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Blocks", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - await response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - async def blocks_without_preload_content( - self, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], - index: Optional[StrictInt] = None, - sort: Optional[StrictStr] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """blocks - - Get blocks - - :param limit: (required) - :type limit: int - :param index: - :type index: int - :param sort: - :type sort: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._blocks_serialize( - limit=limit, - index=index, - sort=sort, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Blocks", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _blocks_serialize( - self, - limit, - index, - sort, - _request_auth, - _content_type, - _headers, - _host_index, - ) -> RequestSerialized: - - _host = None - - _collection_formats: Dict[str, str] = { - } - - _path_params: Dict[str, str] = {} - _query_params: List[Tuple[str, str]] = [] - _header_params: Dict[str, Optional[str]] = _headers or {} - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - # process the query parameters - if index is not None: - - _query_params.append(('index', index)) - - if limit is not None: - - _query_params.append(('limit', limit)) - - if sort is not None: - - _query_params.append(('sort', sort)) - - # process the header parameters - # process the form parameters - # process the body parameter - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - - # authentication setting - _auth_settings: List[str] = [ - ] - - return self.api_client.param_serialize( - method='GET', - resource_path='/api/v1/blocks', - path_params=_path_params, - query_params=_query_params, - header_params=_header_params, - body=_body_params, - post_params=_form_params, - files=_files, - auth_settings=_auth_settings, - collection_formats=_collection_formats, - _host=_host, - _request_auth=_request_auth - ) - - - - - @validate_call - async def current_height( - self, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> CurrentHeight: - """currentHeight - - Get current height - - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._current_height_serialize( - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "CurrentHeight", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - await response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - async def current_height_with_http_info( - self, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[CurrentHeight]: - """currentHeight - - Get current height - - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._current_height_serialize( - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "CurrentHeight", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - await response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - async def current_height_without_preload_content( - self, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """currentHeight - - Get current height - - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._current_height_serialize( - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "CurrentHeight", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _current_height_serialize( - self, - _request_auth, - _content_type, - _headers, - _host_index, - ) -> RequestSerialized: - - _host = None - - _collection_formats: Dict[str, str] = { - } - - _path_params: Dict[str, str] = {} - _query_params: List[Tuple[str, str]] = [] - _header_params: Dict[str, Optional[str]] = _headers or {} - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - # process the query parameters - # process the header parameters - # process the form parameters - # process the body parameter - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - - # authentication setting - _auth_settings: List[str] = [ - ] - - return self.api_client.param_serialize( - method='GET', - resource_path='/api/v1/currentHeight', - path_params=_path_params, - query_params=_query_params, - header_params=_header_params, - body=_body_params, - post_params=_form_params, - files=_files, - auth_settings=_auth_settings, - collection_formats=_collection_formats, - _host=_host, - _request_auth=_request_auth - ) - - diff --git a/lighter/api/bridge_api.py b/lighter/api/bridge_api.py index f9d7851..6f1fb9b 100644 --- a/lighter/api/bridge_api.py +++ b/lighter/api/bridge_api.py @@ -16,7 +16,14 @@ from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated +from lighter.models.resp_get_bridges_by_l1_addr import RespGetBridgesByL1Addr from lighter.models.resp_get_fast_bridge_info import RespGetFastBridgeInfo +from lighter.models.resp_get_fastwithdrawal_info import RespGetFastwithdrawalInfo +from lighter.models.resp_get_is_next_bridge_fast import RespGetIsNextBridgeFast +from lighter.models.result_code import ResultCode from lighter.api_client import ApiClient, RequestSerialized from lighter.api_response import ApiResponse @@ -36,9 +43,9 @@ def __init__(self, api_client=None) -> None: self.api_client = api_client - @validate_call - async def fastbridge_info( + async def bridges( self, + l1_address: StrictStr, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -51,11 +58,13 @@ async def fastbridge_info( _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RespGetFastBridgeInfo: - """fastbridge_info + ) -> RespGetBridgesByL1Addr: + """bridges - Get fast bridge info + Get bridges for given l1 address + :param l1_address: (required) + :type l1_address: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -78,7 +87,8 @@ async def fastbridge_info( :return: Returns the result object. """ # noqa: E501 - _param = self._fastbridge_info_serialize( + _param = self._bridges_serialize( + l1_address=l1_address, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -86,7 +96,7 @@ async def fastbridge_info( ) _response_types_map: Dict[str, Optional[str]] = { - '200': "RespGetFastBridgeInfo", + '200': "RespGetBridgesByL1Addr", '400': "ResultCode", } response_data = await self.api_client.call_api( @@ -100,9 +110,9 @@ async def fastbridge_info( ).data - @validate_call - async def fastbridge_info_with_http_info( + async def bridges_with_http_info( self, + l1_address: StrictStr, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -115,11 +125,13 @@ async def fastbridge_info_with_http_info( _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[RespGetFastBridgeInfo]: - """fastbridge_info + ) -> ApiResponse[RespGetBridgesByL1Addr]: + """bridges - Get fast bridge info + Get bridges for given l1 address + :param l1_address: (required) + :type l1_address: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -142,7 +154,8 @@ async def fastbridge_info_with_http_info( :return: Returns the result object. """ # noqa: E501 - _param = self._fastbridge_info_serialize( + _param = self._bridges_serialize( + l1_address=l1_address, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -150,7 +163,7 @@ async def fastbridge_info_with_http_info( ) _response_types_map: Dict[str, Optional[str]] = { - '200': "RespGetFastBridgeInfo", + '200': "RespGetBridgesByL1Addr", '400': "ResultCode", } response_data = await self.api_client.call_api( @@ -164,9 +177,9 @@ async def fastbridge_info_with_http_info( ) - @validate_call - async def fastbridge_info_without_preload_content( + async def bridges_without_preload_content( self, + l1_address: StrictStr, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -180,10 +193,12 @@ async def fastbridge_info_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """fastbridge_info + """bridges - Get fast bridge info + Get bridges for given l1 address + :param l1_address: (required) + :type l1_address: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -206,7 +221,8 @@ async def fastbridge_info_without_preload_content( :return: Returns the result object. """ # noqa: E501 - _param = self._fastbridge_info_serialize( + _param = self._bridges_serialize( + l1_address=l1_address, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -214,7 +230,7 @@ async def fastbridge_info_without_preload_content( ) _response_types_map: Dict[str, Optional[str]] = { - '200': "RespGetFastBridgeInfo", + '200': "RespGetBridgesByL1Addr", '400': "ResultCode", } response_data = await self.api_client.call_api( @@ -224,8 +240,9 @@ async def fastbridge_info_without_preload_content( return response_data.response - def _fastbridge_info_serialize( + def _bridges_serialize( self, + l1_address, _request_auth, _content_type, _headers, @@ -246,6 +263,10 @@ def _fastbridge_info_serialize( # process the path parameters # process the query parameters + if l1_address is not None: + + _query_params.append(('l1_address', l1_address)) + # process the header parameters # process the form parameters # process the body parameter @@ -266,7 +287,1120 @@ def _fastbridge_info_serialize( return self.api_client.param_serialize( method='GET', - resource_path='/api/v1/fastbridge/info', + resource_path='/api/v1/bridges', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + async def bridges_is_next_bridge_fast( + self, + l1_address: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RespGetIsNextBridgeFast: + """bridges_isNextBridgeFast + + Get if next bridge is fast + + :param l1_address: (required) + :type l1_address: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._bridges_is_next_bridge_fast_serialize( + l1_address=l1_address, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespGetIsNextBridgeFast", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + async def bridges_is_next_bridge_fast_with_http_info( + self, + l1_address: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[RespGetIsNextBridgeFast]: + """bridges_isNextBridgeFast + + Get if next bridge is fast + + :param l1_address: (required) + :type l1_address: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._bridges_is_next_bridge_fast_serialize( + l1_address=l1_address, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespGetIsNextBridgeFast", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + async def bridges_is_next_bridge_fast_without_preload_content( + self, + l1_address: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """bridges_isNextBridgeFast + + Get if next bridge is fast + + :param l1_address: (required) + :type l1_address: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._bridges_is_next_bridge_fast_serialize( + l1_address=l1_address, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespGetIsNextBridgeFast", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _bridges_is_next_bridge_fast_serialize( + self, + l1_address, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if l1_address is not None: + + _query_params.append(('l1_address', l1_address)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/api/v1/bridges/isNextBridgeFast', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + async def fastbridge_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RespGetFastBridgeInfo: + """fastbridge_info + + Get fast bridge info + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fastbridge_info_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespGetFastBridgeInfo", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + async def fastbridge_info_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[RespGetFastBridgeInfo]: + """fastbridge_info + + Get fast bridge info + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fastbridge_info_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespGetFastBridgeInfo", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + async def fastbridge_info_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """fastbridge_info + + Get fast bridge info + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fastbridge_info_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespGetFastBridgeInfo", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fastbridge_info_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/api/v1/fastbridge/info', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + async def fastwithdraw( + self, + tx_info: StrictStr, + to_address: StrictStr, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ResultCode: + """fastwithdraw + + Fast withdraw + + :param tx_info: (required) + :type tx_info: str + :param to_address: (required) + :type to_address: str + :param authorization: make required after integ is done + :type authorization: str + :param auth: made optional to support header auth clients + :type auth: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fastwithdraw_serialize( + tx_info=tx_info, + to_address=to_address, + authorization=authorization, + auth=auth, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ResultCode", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + async def fastwithdraw_with_http_info( + self, + tx_info: StrictStr, + to_address: StrictStr, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ResultCode]: + """fastwithdraw + + Fast withdraw + + :param tx_info: (required) + :type tx_info: str + :param to_address: (required) + :type to_address: str + :param authorization: make required after integ is done + :type authorization: str + :param auth: made optional to support header auth clients + :type auth: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fastwithdraw_serialize( + tx_info=tx_info, + to_address=to_address, + authorization=authorization, + auth=auth, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ResultCode", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + async def fastwithdraw_without_preload_content( + self, + tx_info: StrictStr, + to_address: StrictStr, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """fastwithdraw + + Fast withdraw + + :param tx_info: (required) + :type tx_info: str + :param to_address: (required) + :type to_address: str + :param authorization: make required after integ is done + :type authorization: str + :param auth: made optional to support header auth clients + :type auth: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fastwithdraw_serialize( + tx_info=tx_info, + to_address=to_address, + authorization=authorization, + auth=auth, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ResultCode", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fastwithdraw_serialize( + self, + tx_info, + to_address, + authorization, + auth, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + if authorization is not None: + _header_params['authorization'] = authorization + # process the form parameters + if tx_info is not None: + _form_params.append(('tx_info', tx_info)) + if to_address is not None: + _form_params.append(('to_address', to_address)) + if auth is not None: + _form_params.append(('auth', auth)) + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'multipart/form-data' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/api/v1/fastwithdraw', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + async def fastwithdraw_info( + self, + account_index: StrictInt, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RespGetFastwithdrawalInfo: + """fastwithdraw_info + + Get fast withdraw info + + :param account_index: (required) + :type account_index: int + :param authorization: make required after integ is done + :type authorization: str + :param auth: made optional to support header auth clients + :type auth: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fastwithdraw_info_serialize( + account_index=account_index, + authorization=authorization, + auth=auth, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespGetFastwithdrawalInfo", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + async def fastwithdraw_info_with_http_info( + self, + account_index: StrictInt, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[RespGetFastwithdrawalInfo]: + """fastwithdraw_info + + Get fast withdraw info + + :param account_index: (required) + :type account_index: int + :param authorization: make required after integ is done + :type authorization: str + :param auth: made optional to support header auth clients + :type auth: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fastwithdraw_info_serialize( + account_index=account_index, + authorization=authorization, + auth=auth, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespGetFastwithdrawalInfo", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + async def fastwithdraw_info_without_preload_content( + self, + account_index: StrictInt, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """fastwithdraw_info + + Get fast withdraw info + + :param account_index: (required) + :type account_index: int + :param authorization: make required after integ is done + :type authorization: str + :param auth: made optional to support header auth clients + :type auth: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fastwithdraw_info_serialize( + account_index=account_index, + authorization=authorization, + auth=auth, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "RespGetFastwithdrawalInfo", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fastwithdraw_info_serialize( + self, + account_index, + authorization, + auth, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if authorization is not None: + + _query_params.append(('authorization', authorization)) + + if auth is not None: + + _query_params.append(('auth', auth)) + + if account_index is not None: + + _query_params.append(('account_index', account_index)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/api/v1/fastwithdraw/info', path_params=_path_params, query_params=_query_params, header_params=_header_params, diff --git a/lighter/api/candlestick_api.py b/lighter/api/candlestick_api.py index c964c30..2486ab1 100644 --- a/lighter/api/candlestick_api.py +++ b/lighter/api/candlestick_api.py @@ -19,7 +19,7 @@ from pydantic import Field, StrictBool, StrictInt, StrictStr, field_validator from typing import Optional from typing_extensions import Annotated -from lighter.models.candlesticks import Candlesticks +from lighter.models.candles import Candles from lighter.models.fundings import Fundings from lighter.api_client import ApiClient, RequestSerialized @@ -40,8 +40,7 @@ def __init__(self, api_client=None) -> None: self.api_client = api_client - @validate_call - async def candlesticks( + async def candles( self, market_id: StrictInt, resolution: StrictStr, @@ -61,10 +60,10 @@ async def candlesticks( _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> Candlesticks: - """candlesticks + ) -> Candles: + """candles - Get candlesticks + Get candles (optimized with shortened fields and smaller response size) :param market_id: (required) :type market_id: int @@ -100,7 +99,7 @@ async def candlesticks( :return: Returns the result object. """ # noqa: E501 - _param = self._candlesticks_serialize( + _param = self._candles_serialize( market_id=market_id, resolution=resolution, start_timestamp=start_timestamp, @@ -114,7 +113,7 @@ async def candlesticks( ) _response_types_map: Dict[str, Optional[str]] = { - '200': "Candlesticks", + '200': "Candles", '400': "ResultCode", } response_data = await self.api_client.call_api( @@ -128,8 +127,7 @@ async def candlesticks( ).data - @validate_call - async def candlesticks_with_http_info( + async def candles_with_http_info( self, market_id: StrictInt, resolution: StrictStr, @@ -149,10 +147,10 @@ async def candlesticks_with_http_info( _content_type: Optional[StrictStr] = None, _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[Candlesticks]: - """candlesticks + ) -> ApiResponse[Candles]: + """candles - Get candlesticks + Get candles (optimized with shortened fields and smaller response size) :param market_id: (required) :type market_id: int @@ -188,7 +186,7 @@ async def candlesticks_with_http_info( :return: Returns the result object. """ # noqa: E501 - _param = self._candlesticks_serialize( + _param = self._candles_serialize( market_id=market_id, resolution=resolution, start_timestamp=start_timestamp, @@ -202,7 +200,7 @@ async def candlesticks_with_http_info( ) _response_types_map: Dict[str, Optional[str]] = { - '200': "Candlesticks", + '200': "Candles", '400': "ResultCode", } response_data = await self.api_client.call_api( @@ -216,8 +214,7 @@ async def candlesticks_with_http_info( ) - @validate_call - async def candlesticks_without_preload_content( + async def candles_without_preload_content( self, market_id: StrictInt, resolution: StrictStr, @@ -238,9 +235,9 @@ async def candlesticks_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """candlesticks + """candles - Get candlesticks + Get candles (optimized with shortened fields and smaller response size) :param market_id: (required) :type market_id: int @@ -276,7 +273,7 @@ async def candlesticks_without_preload_content( :return: Returns the result object. """ # noqa: E501 - _param = self._candlesticks_serialize( + _param = self._candles_serialize( market_id=market_id, resolution=resolution, start_timestamp=start_timestamp, @@ -290,7 +287,7 @@ async def candlesticks_without_preload_content( ) _response_types_map: Dict[str, Optional[str]] = { - '200': "Candlesticks", + '200': "Candles", '400': "ResultCode", } response_data = await self.api_client.call_api( @@ -300,7 +297,7 @@ async def candlesticks_without_preload_content( return response_data.response - def _candlesticks_serialize( + def _candles_serialize( self, market_id, resolution, @@ -372,7 +369,7 @@ def _candlesticks_serialize( return self.api_client.param_serialize( method='GET', - resource_path='/api/v1/candlesticks', + resource_path='/api/v1/candles', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -388,7 +385,6 @@ def _candlesticks_serialize( - @validate_call async def fundings( self, market_id: StrictInt, @@ -472,7 +468,6 @@ async def fundings( ).data - @validate_call async def fundings_with_http_info( self, market_id: StrictInt, @@ -556,7 +551,6 @@ async def fundings_with_http_info( ) - @validate_call async def fundings_without_preload_content( self, market_id: StrictInt, diff --git a/lighter/api/funding_api.py b/lighter/api/funding_api.py index 5bcc028..9095e82 100644 --- a/lighter/api/funding_api.py +++ b/lighter/api/funding_api.py @@ -36,7 +36,6 @@ def __init__(self, api_client=None) -> None: self.api_client = api_client - @validate_call async def funding_rates( self, _request_timeout: Union[ @@ -100,7 +99,6 @@ async def funding_rates( ).data - @validate_call async def funding_rates_with_http_info( self, _request_timeout: Union[ @@ -164,7 +162,6 @@ async def funding_rates_with_http_info( ) - @validate_call async def funding_rates_without_preload_content( self, _request_timeout: Union[ diff --git a/lighter/api/info_api.py b/lighter/api/info_api.py index 9e2591a..0c30f3c 100644 --- a/lighter/api/info_api.py +++ b/lighter/api/info_api.py @@ -16,8 +16,9 @@ from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated -from pydantic import StrictInt, StrictStr +from pydantic import Field, StrictInt, StrictStr from typing import Optional +from typing_extensions import Annotated from lighter.models.resp_withdrawal_delay import RespWithdrawalDelay from lighter.models.transfer_fee_info import TransferFeeInfo @@ -39,12 +40,11 @@ def __init__(self, api_client=None) -> None: self.api_client = api_client - @validate_call async def transfer_fee_info( self, account_index: StrictInt, - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, to_account_index: Optional[StrictInt] = None, _request_timeout: Union[ None, @@ -65,9 +65,9 @@ async def transfer_fee_info( :param account_index: (required) :type account_index: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param to_account_index: :type to_account_index: int @@ -119,12 +119,11 @@ async def transfer_fee_info( ).data - @validate_call async def transfer_fee_info_with_http_info( self, account_index: StrictInt, - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, to_account_index: Optional[StrictInt] = None, _request_timeout: Union[ None, @@ -145,9 +144,9 @@ async def transfer_fee_info_with_http_info( :param account_index: (required) :type account_index: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param to_account_index: :type to_account_index: int @@ -199,12 +198,11 @@ async def transfer_fee_info_with_http_info( ) - @validate_call async def transfer_fee_info_without_preload_content( self, account_index: StrictInt, - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, to_account_index: Optional[StrictInt] = None, _request_timeout: Union[ None, @@ -225,9 +223,9 @@ async def transfer_fee_info_without_preload_content( :param account_index: (required) :type account_index: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param to_account_index: :type to_account_index: int @@ -301,6 +299,10 @@ def _transfer_fee_info_serialize( # process the path parameters # process the query parameters + if authorization is not None: + + _query_params.append(('authorization', authorization)) + if auth is not None: _query_params.append(('auth', auth)) @@ -314,8 +316,6 @@ def _transfer_fee_info_serialize( _query_params.append(('to_account_index', to_account_index)) # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization # process the form parameters # process the body parameter @@ -351,7 +351,6 @@ def _transfer_fee_info_serialize( - @validate_call async def withdrawal_delay( self, _request_timeout: Union[ @@ -415,7 +414,6 @@ async def withdrawal_delay( ).data - @validate_call async def withdrawal_delay_with_http_info( self, _request_timeout: Union[ @@ -479,7 +477,6 @@ async def withdrawal_delay_with_http_info( ) - @validate_call async def withdrawal_delay_without_preload_content( self, _request_timeout: Union[ diff --git a/lighter/api/notification_api.py b/lighter/api/notification_api.py index a3c2477..f514353 100644 --- a/lighter/api/notification_api.py +++ b/lighter/api/notification_api.py @@ -39,7 +39,6 @@ def __init__(self, api_client=None) -> None: self.api_client = api_client - @validate_call async def notification_ack( self, notif_id: StrictStr, @@ -119,7 +118,6 @@ async def notification_ack( ).data - @validate_call async def notification_ack_with_http_info( self, notif_id: StrictStr, @@ -199,7 +197,6 @@ async def notification_ack_with_http_info( ) - @validate_call async def notification_ack_without_preload_content( self, notif_id: StrictStr, diff --git a/lighter/api/order_api.py b/lighter/api/order_api.py index 6b89d83..5ad21b2 100644 --- a/lighter/api/order_api.py +++ b/lighter/api/order_api.py @@ -16,9 +16,10 @@ from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated -from pydantic import Field, StrictInt, StrictStr, field_validator +from pydantic import Field, StrictBool, StrictInt, StrictStr, field_validator from typing import Optional from typing_extensions import Annotated +from lighter.models.asset_details import AssetDetails from lighter.models.exchange_stats import ExchangeStats from lighter.models.export_data import ExportData from lighter.models.order_book_details import OrderBookDetails @@ -45,7 +46,6 @@ def __init__(self, api_client=None) -> None: self.api_client = api_client - @validate_call async def account_active_orders( self, account_index: StrictInt, @@ -125,7 +125,6 @@ async def account_active_orders( ).data - @validate_call async def account_active_orders_with_http_info( self, account_index: StrictInt, @@ -205,7 +204,6 @@ async def account_active_orders_with_http_info( ) - @validate_call async def account_active_orders_without_preload_content( self, account_index: StrictInt, @@ -307,6 +305,14 @@ def _account_active_orders_serialize( # process the path parameters # process the query parameters + if authorization is not None: + + _query_params.append(('authorization', authorization)) + + if auth is not None: + + _query_params.append(('auth', auth)) + if account_index is not None: _query_params.append(('account_index', account_index)) @@ -315,13 +321,7 @@ def _account_active_orders_serialize( _query_params.append(('market_id', market_id)) - if auth is not None: - - _query_params.append(('auth', auth)) - # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization # process the form parameters # process the body parameter @@ -357,7 +357,6 @@ def _account_active_orders_serialize( - @validate_call async def account_inactive_orders( self, account_index: StrictInt, @@ -453,7 +452,6 @@ async def account_inactive_orders( ).data - @validate_call async def account_inactive_orders_with_http_info( self, account_index: StrictInt, @@ -549,7 +547,6 @@ async def account_inactive_orders_with_http_info( ) - @validate_call async def account_inactive_orders_without_preload_content( self, account_index: StrictInt, @@ -671,6 +668,10 @@ def _account_inactive_orders_serialize( # process the path parameters # process the query parameters + if authorization is not None: + + _query_params.append(('authorization', authorization)) + if auth is not None: _query_params.append(('auth', auth)) @@ -700,8 +701,6 @@ def _account_inactive_orders_serialize( _query_params.append(('limit', limit)) # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization # process the form parameters # process the body parameter @@ -737,7 +736,266 @@ def _account_inactive_orders_serialize( - @validate_call + async def asset_details( + self, + asset_id: Optional[StrictInt] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> AssetDetails: + """assetDetails + + Get asset details + + :param asset_id: + :type asset_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._asset_details_serialize( + asset_id=asset_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AssetDetails", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + async def asset_details_with_http_info( + self, + asset_id: Optional[StrictInt] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[AssetDetails]: + """assetDetails + + Get asset details + + :param asset_id: + :type asset_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._asset_details_serialize( + asset_id=asset_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AssetDetails", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + async def asset_details_without_preload_content( + self, + asset_id: Optional[StrictInt] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """assetDetails + + Get asset details + + :param asset_id: + :type asset_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._asset_details_serialize( + asset_id=asset_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AssetDetails", + '400': "ResultCode", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _asset_details_serialize( + self, + asset_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if asset_id is not None: + + _query_params.append(('asset_id', asset_id)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/api/v1/assetDetails', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + async def exchange_stats( self, _request_timeout: Union[ @@ -801,7 +1059,6 @@ async def exchange_stats( ).data - @validate_call async def exchange_stats_with_http_info( self, _request_timeout: Union[ @@ -865,7 +1122,6 @@ async def exchange_stats_with_http_info( ) - @validate_call async def exchange_stats_without_preload_content( self, _request_timeout: Union[ @@ -983,12 +1239,11 @@ def _exchange_stats_serialize( - @validate_call async def export( self, type: StrictStr, - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, account_index: Optional[StrictInt] = None, market_id: Optional[StrictInt] = None, _request_timeout: Union[ @@ -1010,9 +1265,9 @@ async def export( :param type: (required) :type type: str - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param account_index: :type account_index: int @@ -1067,12 +1322,11 @@ async def export( ).data - @validate_call async def export_with_http_info( self, type: StrictStr, - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, account_index: Optional[StrictInt] = None, market_id: Optional[StrictInt] = None, _request_timeout: Union[ @@ -1094,9 +1348,9 @@ async def export_with_http_info( :param type: (required) :type type: str - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param account_index: :type account_index: int @@ -1151,12 +1405,11 @@ async def export_with_http_info( ) - @validate_call async def export_without_preload_content( self, type: StrictStr, - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, account_index: Optional[StrictInt] = None, market_id: Optional[StrictInt] = None, _request_timeout: Union[ @@ -1178,9 +1431,9 @@ async def export_without_preload_content( :param type: (required) :type type: str - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param account_index: :type account_index: int @@ -1258,6 +1511,10 @@ def _export_serialize( # process the path parameters # process the query parameters + if authorization is not None: + + _query_params.append(('authorization', authorization)) + if auth is not None: _query_params.append(('auth', auth)) @@ -1275,8 +1532,6 @@ def _export_serialize( _query_params.append(('type', type)) # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization # process the form parameters # process the body parameter @@ -1312,10 +1567,10 @@ def _export_serialize( - @validate_call async def order_book_details( self, market_id: Optional[StrictInt] = None, + filter: Optional[StrictStr] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -1335,6 +1590,8 @@ async def order_book_details( :param market_id: :type market_id: int + :param filter: + :type filter: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -1359,6 +1616,7 @@ async def order_book_details( _param = self._order_book_details_serialize( market_id=market_id, + filter=filter, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -1380,10 +1638,10 @@ async def order_book_details( ).data - @validate_call async def order_book_details_with_http_info( self, market_id: Optional[StrictInt] = None, + filter: Optional[StrictStr] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -1403,6 +1661,8 @@ async def order_book_details_with_http_info( :param market_id: :type market_id: int + :param filter: + :type filter: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -1427,6 +1687,7 @@ async def order_book_details_with_http_info( _param = self._order_book_details_serialize( market_id=market_id, + filter=filter, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -1448,10 +1709,10 @@ async def order_book_details_with_http_info( ) - @validate_call async def order_book_details_without_preload_content( self, market_id: Optional[StrictInt] = None, + filter: Optional[StrictStr] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -1471,6 +1732,8 @@ async def order_book_details_without_preload_content( :param market_id: :type market_id: int + :param filter: + :type filter: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -1495,6 +1758,7 @@ async def order_book_details_without_preload_content( _param = self._order_book_details_serialize( market_id=market_id, + filter=filter, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -1515,6 +1779,7 @@ async def order_book_details_without_preload_content( def _order_book_details_serialize( self, market_id, + filter, _request_auth, _content_type, _headers, @@ -1539,6 +1804,10 @@ def _order_book_details_serialize( _query_params.append(('market_id', market_id)) + if filter is not None: + + _query_params.append(('filter', filter)) + # process the header parameters # process the form parameters # process the body parameter @@ -1575,11 +1844,10 @@ def _order_book_details_serialize( - @validate_call async def order_book_orders( self, market_id: StrictInt, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], + limit: Annotated[int, Field(le=250, strict=True, ge=1)], _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -1647,11 +1915,10 @@ async def order_book_orders( ).data - @validate_call async def order_book_orders_with_http_info( self, market_id: StrictInt, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], + limit: Annotated[int, Field(le=250, strict=True, ge=1)], _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -1719,11 +1986,10 @@ async def order_book_orders_with_http_info( ) - @validate_call async def order_book_orders_without_preload_content( self, market_id: StrictInt, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], + limit: Annotated[int, Field(le=250, strict=True, ge=1)], _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -1855,10 +2121,10 @@ def _order_book_orders_serialize( - @validate_call async def order_books( self, market_id: Optional[StrictInt] = None, + filter: Optional[StrictStr] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -1878,6 +2144,8 @@ async def order_books( :param market_id: :type market_id: int + :param filter: + :type filter: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -1902,6 +2170,7 @@ async def order_books( _param = self._order_books_serialize( market_id=market_id, + filter=filter, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -1923,10 +2192,10 @@ async def order_books( ).data - @validate_call async def order_books_with_http_info( self, market_id: Optional[StrictInt] = None, + filter: Optional[StrictStr] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -1946,6 +2215,8 @@ async def order_books_with_http_info( :param market_id: :type market_id: int + :param filter: + :type filter: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -1970,6 +2241,7 @@ async def order_books_with_http_info( _param = self._order_books_serialize( market_id=market_id, + filter=filter, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -1991,10 +2263,10 @@ async def order_books_with_http_info( ) - @validate_call async def order_books_without_preload_content( self, market_id: Optional[StrictInt] = None, + filter: Optional[StrictStr] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -2014,6 +2286,8 @@ async def order_books_without_preload_content( :param market_id: :type market_id: int + :param filter: + :type filter: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -2038,6 +2312,7 @@ async def order_books_without_preload_content( _param = self._order_books_serialize( market_id=market_id, + filter=filter, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -2058,6 +2333,7 @@ async def order_books_without_preload_content( def _order_books_serialize( self, market_id, + filter, _request_auth, _content_type, _headers, @@ -2082,6 +2358,10 @@ def _order_books_serialize( _query_params.append(('market_id', market_id)) + if filter is not None: + + _query_params.append(('filter', filter)) + # process the header parameters # process the form parameters # process the body parameter @@ -2118,7 +2398,6 @@ def _order_books_serialize( - @validate_call async def recent_trades( self, market_id: StrictInt, @@ -2190,7 +2469,6 @@ async def recent_trades( ).data - @validate_call async def recent_trades_with_http_info( self, market_id: StrictInt, @@ -2262,7 +2540,6 @@ async def recent_trades_with_http_info( ) - @validate_call async def recent_trades_without_preload_content( self, market_id: StrictInt, @@ -2398,13 +2675,12 @@ def _recent_trades_serialize( - @validate_call async def trades( self, sort_by: StrictStr, limit: Annotated[int, Field(le=100, strict=True, ge=1)], - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, market_id: Optional[StrictInt] = None, account_index: Optional[StrictInt] = None, order_index: Optional[StrictInt] = None, @@ -2412,6 +2688,9 @@ async def trades( cursor: Optional[StrictStr] = None, var_from: Optional[StrictInt] = None, ask_filter: Optional[StrictInt] = None, + role: Optional[StrictStr] = None, + type: Optional[StrictStr] = None, + aggregate: Optional[StrictBool] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -2433,9 +2712,9 @@ async def trades( :type sort_by: str :param limit: (required) :type limit: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param market_id: :type market_id: int @@ -2451,6 +2730,12 @@ async def trades( :type var_from: int :param ask_filter: :type ask_filter: int + :param role: + :type role: str + :param type: + :type type: str + :param aggregate: + :type aggregate: bool :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -2485,6 +2770,9 @@ async def trades( cursor=cursor, var_from=var_from, ask_filter=ask_filter, + role=role, + type=type, + aggregate=aggregate, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -2506,13 +2794,12 @@ async def trades( ).data - @validate_call async def trades_with_http_info( self, sort_by: StrictStr, limit: Annotated[int, Field(le=100, strict=True, ge=1)], - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, market_id: Optional[StrictInt] = None, account_index: Optional[StrictInt] = None, order_index: Optional[StrictInt] = None, @@ -2520,6 +2807,9 @@ async def trades_with_http_info( cursor: Optional[StrictStr] = None, var_from: Optional[StrictInt] = None, ask_filter: Optional[StrictInt] = None, + role: Optional[StrictStr] = None, + type: Optional[StrictStr] = None, + aggregate: Optional[StrictBool] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -2541,9 +2831,9 @@ async def trades_with_http_info( :type sort_by: str :param limit: (required) :type limit: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param market_id: :type market_id: int @@ -2559,6 +2849,12 @@ async def trades_with_http_info( :type var_from: int :param ask_filter: :type ask_filter: int + :param role: + :type role: str + :param type: + :type type: str + :param aggregate: + :type aggregate: bool :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -2593,6 +2889,9 @@ async def trades_with_http_info( cursor=cursor, var_from=var_from, ask_filter=ask_filter, + role=role, + type=type, + aggregate=aggregate, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -2614,13 +2913,12 @@ async def trades_with_http_info( ) - @validate_call async def trades_without_preload_content( self, sort_by: StrictStr, limit: Annotated[int, Field(le=100, strict=True, ge=1)], - authorization: Optional[StrictStr] = None, - auth: Optional[StrictStr] = None, + authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, + auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, market_id: Optional[StrictInt] = None, account_index: Optional[StrictInt] = None, order_index: Optional[StrictInt] = None, @@ -2628,6 +2926,9 @@ async def trades_without_preload_content( cursor: Optional[StrictStr] = None, var_from: Optional[StrictInt] = None, ask_filter: Optional[StrictInt] = None, + role: Optional[StrictStr] = None, + type: Optional[StrictStr] = None, + aggregate: Optional[StrictBool] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -2649,9 +2950,9 @@ async def trades_without_preload_content( :type sort_by: str :param limit: (required) :type limit: int - :param authorization: + :param authorization: make required after integ is done :type authorization: str - :param auth: + :param auth: made optional to support header auth clients :type auth: str :param market_id: :type market_id: int @@ -2667,6 +2968,12 @@ async def trades_without_preload_content( :type var_from: int :param ask_filter: :type ask_filter: int + :param role: + :type role: str + :param type: + :type type: str + :param aggregate: + :type aggregate: bool :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of @@ -2701,6 +3008,9 @@ async def trades_without_preload_content( cursor=cursor, var_from=var_from, ask_filter=ask_filter, + role=role, + type=type, + aggregate=aggregate, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -2731,6 +3041,9 @@ def _trades_serialize( cursor, var_from, ask_filter, + role, + type, + aggregate, _request_auth, _content_type, _headers, @@ -2751,6 +3064,10 @@ def _trades_serialize( # process the path parameters # process the query parameters + if authorization is not None: + + _query_params.append(('authorization', authorization)) + if auth is not None: _query_params.append(('auth', auth)) @@ -2787,13 +3104,23 @@ def _trades_serialize( _query_params.append(('ask_filter', ask_filter)) + if role is not None: + + _query_params.append(('role', role)) + + if type is not None: + + _query_params.append(('type', type)) + if limit is not None: _query_params.append(('limit', limit)) + if aggregate is not None: + + _query_params.append(('aggregate', aggregate)) + # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization # process the form parameters # process the body parameter diff --git a/lighter/api/referral_api.py b/lighter/api/referral_api.py deleted file mode 100644 index 733ac60..0000000 --- a/lighter/api/referral_api.py +++ /dev/null @@ -1,334 +0,0 @@ -# coding: utf-8 - -""" - - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - -import warnings -from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt -from typing import Any, Dict, List, Optional, Tuple, Union -from typing_extensions import Annotated - -from pydantic import Field, StrictInt, StrictStr -from typing import Optional -from typing_extensions import Annotated -from lighter.models.referral_points import ReferralPoints - -from lighter.api_client import ApiClient, RequestSerialized -from lighter.api_response import ApiResponse -from lighter.rest import RESTResponseType - - -class ReferralApi: - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None) -> None: - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client - - - @validate_call - async def referral_points( - self, - account_index: StrictInt, - authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, - auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ReferralPoints: - """referral_points - - Get referral points - - :param account_index: (required) - :type account_index: int - :param authorization: make required after integ is done - :type authorization: str - :param auth: made optional to support header auth clients - :type auth: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._referral_points_serialize( - account_index=account_index, - authorization=authorization, - auth=auth, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "ReferralPoints", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - await response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - async def referral_points_with_http_info( - self, - account_index: StrictInt, - authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, - auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[ReferralPoints]: - """referral_points - - Get referral points - - :param account_index: (required) - :type account_index: int - :param authorization: make required after integ is done - :type authorization: str - :param auth: made optional to support header auth clients - :type auth: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._referral_points_serialize( - account_index=account_index, - authorization=authorization, - auth=auth, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "ReferralPoints", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - await response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - async def referral_points_without_preload_content( - self, - account_index: StrictInt, - authorization: Annotated[Optional[StrictStr], Field(description=" make required after integ is done")] = None, - auth: Annotated[Optional[StrictStr], Field(description=" made optional to support header auth clients")] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """referral_points - - Get referral points - - :param account_index: (required) - :type account_index: int - :param authorization: make required after integ is done - :type authorization: str - :param auth: made optional to support header auth clients - :type auth: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._referral_points_serialize( - account_index=account_index, - authorization=authorization, - auth=auth, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "ReferralPoints", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _referral_points_serialize( - self, - account_index, - authorization, - auth, - _request_auth, - _content_type, - _headers, - _host_index, - ) -> RequestSerialized: - - _host = None - - _collection_formats: Dict[str, str] = { - } - - _path_params: Dict[str, str] = {} - _query_params: List[Tuple[str, str]] = [] - _header_params: Dict[str, Optional[str]] = _headers or {} - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - # process the query parameters - if auth is not None: - - _query_params.append(('auth', auth)) - - if account_index is not None: - - _query_params.append(('account_index', account_index)) - - # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization - # process the form parameters - # process the body parameter - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - - # authentication setting - _auth_settings: List[str] = [ - ] - - return self.api_client.param_serialize( - method='GET', - resource_path='/api/v1/referral/points', - path_params=_path_params, - query_params=_query_params, - header_params=_header_params, - body=_body_params, - post_params=_form_params, - files=_files, - auth_settings=_auth_settings, - collection_formats=_collection_formats, - _host=_host, - _request_auth=_request_auth - ) - - diff --git a/lighter/api/root_api.py b/lighter/api/root_api.py index f009fdc..82d9cb0 100644 --- a/lighter/api/root_api.py +++ b/lighter/api/root_api.py @@ -37,7 +37,6 @@ def __init__(self, api_client=None) -> None: self.api_client = api_client - @validate_call async def info( self, _request_timeout: Union[ @@ -101,7 +100,6 @@ async def info( ).data - @validate_call async def info_with_http_info( self, _request_timeout: Union[ @@ -165,7 +163,6 @@ async def info_with_http_info( ) - @validate_call async def info_without_preload_content( self, _request_timeout: Union[ @@ -283,7 +280,6 @@ def _info_serialize( - @validate_call async def status( self, _request_timeout: Union[ @@ -347,7 +343,6 @@ async def status( ).data - @validate_call async def status_with_http_info( self, _request_timeout: Union[ @@ -411,7 +406,6 @@ async def status_with_http_info( ) - @validate_call async def status_without_preload_content( self, _request_timeout: Union[ diff --git a/lighter/api/transaction_api.py b/lighter/api/transaction_api.py index 5129ab0..240f3c8 100644 --- a/lighter/api/transaction_api.py +++ b/lighter/api/transaction_api.py @@ -17,7 +17,7 @@ from typing_extensions import Annotated from pydantic import Field, StrictBool, StrictInt, StrictStr, field_validator -from typing import List, Optional +from typing import Optional from typing_extensions import Annotated from lighter.models.deposit_history import DepositHistory from lighter.models.enriched_tx import EnrichedTx @@ -25,7 +25,6 @@ from lighter.models.resp_send_tx import RespSendTx from lighter.models.resp_send_tx_batch import RespSendTxBatch from lighter.models.transfer_history import TransferHistory -from lighter.models.txs import Txs from lighter.models.withdraw_history import WithdrawHistory from lighter.api_client import ApiClient, RequestSerialized @@ -46,651 +45,6 @@ def __init__(self, api_client=None) -> None: self.api_client = api_client - @validate_call - async def account_txs( - self, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], - by: StrictStr, - value: StrictStr, - authorization: Optional[StrictStr] = None, - index: Optional[StrictInt] = None, - types: Optional[List[StrictInt]] = None, - auth: Optional[StrictStr] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> Txs: - """accountTxs - - Get transactions of a specific account - - :param limit: (required) - :type limit: int - :param by: (required) - :type by: str - :param value: (required) - :type value: str - :param authorization: - :type authorization: str - :param index: - :type index: int - :param types: - :type types: List[int] - :param auth: - :type auth: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._account_txs_serialize( - limit=limit, - by=by, - value=value, - authorization=authorization, - index=index, - types=types, - auth=auth, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Txs", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - await response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - async def account_txs_with_http_info( - self, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], - by: StrictStr, - value: StrictStr, - authorization: Optional[StrictStr] = None, - index: Optional[StrictInt] = None, - types: Optional[List[StrictInt]] = None, - auth: Optional[StrictStr] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[Txs]: - """accountTxs - - Get transactions of a specific account - - :param limit: (required) - :type limit: int - :param by: (required) - :type by: str - :param value: (required) - :type value: str - :param authorization: - :type authorization: str - :param index: - :type index: int - :param types: - :type types: List[int] - :param auth: - :type auth: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._account_txs_serialize( - limit=limit, - by=by, - value=value, - authorization=authorization, - index=index, - types=types, - auth=auth, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Txs", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - await response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - async def account_txs_without_preload_content( - self, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], - by: StrictStr, - value: StrictStr, - authorization: Optional[StrictStr] = None, - index: Optional[StrictInt] = None, - types: Optional[List[StrictInt]] = None, - auth: Optional[StrictStr] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """accountTxs - - Get transactions of a specific account - - :param limit: (required) - :type limit: int - :param by: (required) - :type by: str - :param value: (required) - :type value: str - :param authorization: - :type authorization: str - :param index: - :type index: int - :param types: - :type types: List[int] - :param auth: - :type auth: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._account_txs_serialize( - limit=limit, - by=by, - value=value, - authorization=authorization, - index=index, - types=types, - auth=auth, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Txs", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _account_txs_serialize( - self, - limit, - by, - value, - authorization, - index, - types, - auth, - _request_auth, - _content_type, - _headers, - _host_index, - ) -> RequestSerialized: - - _host = None - - _collection_formats: Dict[str, str] = { - 'types': 'csv', - } - - _path_params: Dict[str, str] = {} - _query_params: List[Tuple[str, str]] = [] - _header_params: Dict[str, Optional[str]] = _headers or {} - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - # process the query parameters - if index is not None: - - _query_params.append(('index', index)) - - if limit is not None: - - _query_params.append(('limit', limit)) - - if by is not None: - - _query_params.append(('by', by)) - - if value is not None: - - _query_params.append(('value', value)) - - if types is not None: - - _query_params.append(('types', types)) - - if auth is not None: - - _query_params.append(('auth', auth)) - - # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization - # process the form parameters - # process the body parameter - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - - # authentication setting - _auth_settings: List[str] = [ - ] - - return self.api_client.param_serialize( - method='GET', - resource_path='/api/v1/accountTxs', - path_params=_path_params, - query_params=_query_params, - header_params=_header_params, - body=_body_params, - post_params=_form_params, - files=_files, - auth_settings=_auth_settings, - collection_formats=_collection_formats, - _host=_host, - _request_auth=_request_auth - ) - - - - - @validate_call - async def block_txs( - self, - by: StrictStr, - value: StrictStr, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> Txs: - """blockTxs - - Get transactions in a block - - :param by: (required) - :type by: str - :param value: (required) - :type value: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._block_txs_serialize( - by=by, - value=value, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Txs", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - await response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - async def block_txs_with_http_info( - self, - by: StrictStr, - value: StrictStr, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[Txs]: - """blockTxs - - Get transactions in a block - - :param by: (required) - :type by: str - :param value: (required) - :type value: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._block_txs_serialize( - by=by, - value=value, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Txs", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - await response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - async def block_txs_without_preload_content( - self, - by: StrictStr, - value: StrictStr, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """blockTxs - - Get transactions in a block - - :param by: (required) - :type by: str - :param value: (required) - :type value: str - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._block_txs_serialize( - by=by, - value=value, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Txs", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _block_txs_serialize( - self, - by, - value, - _request_auth, - _content_type, - _headers, - _host_index, - ) -> RequestSerialized: - - _host = None - - _collection_formats: Dict[str, str] = { - } - - _path_params: Dict[str, str] = {} - _query_params: List[Tuple[str, str]] = [] - _header_params: Dict[str, Optional[str]] = _headers or {} - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - # process the query parameters - if by is not None: - - _query_params.append(('by', by)) - - if value is not None: - - _query_params.append(('value', value)) - - # process the header parameters - # process the form parameters - # process the body parameter - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - - # authentication setting - _auth_settings: List[str] = [ - ] - - return self.api_client.param_serialize( - method='GET', - resource_path='/api/v1/blockTxs', - path_params=_path_params, - query_params=_query_params, - header_params=_header_params, - body=_body_params, - post_params=_form_params, - files=_files, - auth_settings=_auth_settings, - collection_formats=_collection_formats, - _host=_host, - _request_auth=_request_auth - ) - - - - - @validate_call async def deposit_history( self, account_index: StrictInt, @@ -778,7 +132,6 @@ async def deposit_history( ).data - @validate_call async def deposit_history_with_http_info( self, account_index: StrictInt, @@ -866,7 +219,6 @@ async def deposit_history_with_http_info( ) - @validate_call async def deposit_history_without_preload_content( self, account_index: StrictInt, @@ -978,14 +330,18 @@ def _deposit_history_serialize( # process the path parameters # process the query parameters - if account_index is not None: + if authorization is not None: - _query_params.append(('account_index', account_index)) + _query_params.append(('authorization', authorization)) if auth is not None: _query_params.append(('auth', auth)) + if account_index is not None: + + _query_params.append(('account_index', account_index)) + if l1_address is not None: _query_params.append(('l1_address', l1_address)) @@ -999,8 +355,6 @@ def _deposit_history_serialize( _query_params.append(('filter', filter)) # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization # process the form parameters # process the body parameter @@ -1036,7 +390,6 @@ def _deposit_history_serialize( - @validate_call async def next_nonce( self, account_index: StrictInt, @@ -1108,7 +461,6 @@ async def next_nonce( ).data - @validate_call async def next_nonce_with_http_info( self, account_index: StrictInt, @@ -1180,7 +532,6 @@ async def next_nonce_with_http_info( ) - @validate_call async def next_nonce_without_preload_content( self, account_index: StrictInt, @@ -1316,7 +667,6 @@ def _next_nonce_serialize( - @validate_call async def send_tx( self, tx_type: StrictInt, @@ -1392,7 +742,6 @@ async def send_tx( ).data - @validate_call async def send_tx_with_http_info( self, tx_type: StrictInt, @@ -1468,7 +817,6 @@ async def send_tx_with_http_info( ) - @validate_call async def send_tx_without_preload_content( self, tx_type: StrictInt, @@ -1620,7 +968,6 @@ def _send_tx_serialize( - @validate_call async def send_tx_batch( self, tx_types: StrictStr, @@ -1692,7 +1039,6 @@ async def send_tx_batch( ).data - @validate_call async def send_tx_batch_with_http_info( self, tx_types: StrictStr, @@ -1764,7 +1110,6 @@ async def send_tx_batch_with_http_info( ) - @validate_call async def send_tx_batch_without_preload_content( self, tx_types: StrictStr, @@ -1909,7 +1254,6 @@ def _send_tx_batch_serialize( - @validate_call async def transfer_history( self, account_index: StrictInt, @@ -1989,7 +1333,6 @@ async def transfer_history( ).data - @validate_call async def transfer_history_with_http_info( self, account_index: StrictInt, @@ -2069,7 +1412,6 @@ async def transfer_history_with_http_info( ) - @validate_call async def transfer_history_without_preload_content( self, account_index: StrictInt, @@ -2171,21 +1513,23 @@ def _transfer_history_serialize( # process the path parameters # process the query parameters - if account_index is not None: + if authorization is not None: - _query_params.append(('account_index', account_index)) + _query_params.append(('authorization', authorization)) if auth is not None: _query_params.append(('auth', auth)) + if account_index is not None: + + _query_params.append(('account_index', account_index)) + if cursor is not None: _query_params.append(('cursor', cursor)) # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization # process the form parameters # process the body parameter @@ -2221,7 +1565,6 @@ def _transfer_history_serialize( - @validate_call async def tx( self, by: StrictStr, @@ -2293,7 +1636,6 @@ async def tx( ).data - @validate_call async def tx_with_http_info( self, by: StrictStr, @@ -2365,7 +1707,6 @@ async def tx_with_http_info( ) - @validate_call async def tx_without_preload_content( self, by: StrictStr, @@ -2501,7 +1842,6 @@ def _tx_serialize( - @validate_call async def tx_from_l1_tx_hash( self, hash: StrictStr, @@ -2569,7 +1909,6 @@ async def tx_from_l1_tx_hash( ).data - @validate_call async def tx_from_l1_tx_hash_with_http_info( self, hash: StrictStr, @@ -2637,7 +1976,6 @@ async def tx_from_l1_tx_hash_with_http_info( ) - @validate_call async def tx_from_l1_tx_hash_without_preload_content( self, hash: StrictStr, @@ -2764,287 +2102,6 @@ def _tx_from_l1_tx_hash_serialize( - @validate_call - async def txs( - self, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], - index: Optional[StrictInt] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> Txs: - """txs - - Get transactions which are already packed into blocks - - :param limit: (required) - :type limit: int - :param index: - :type index: int - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._txs_serialize( - limit=limit, - index=index, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Txs", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - await response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - - @validate_call - async def txs_with_http_info( - self, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], - index: Optional[StrictInt] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[Txs]: - """txs - - Get transactions which are already packed into blocks - - :param limit: (required) - :type limit: int - :param index: - :type index: int - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._txs_serialize( - limit=limit, - index=index, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Txs", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - await response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - - @validate_call - async def txs_without_preload_content( - self, - limit: Annotated[int, Field(le=100, strict=True, ge=1)], - index: Optional[StrictInt] = None, - _request_timeout: Union[ - None, - Annotated[StrictFloat, Field(gt=0)], - Tuple[ - Annotated[StrictFloat, Field(gt=0)], - Annotated[StrictFloat, Field(gt=0)] - ] - ] = None, - _request_auth: Optional[Dict[StrictStr, Any]] = None, - _content_type: Optional[StrictStr] = None, - _headers: Optional[Dict[StrictStr, Any]] = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """txs - - Get transactions which are already packed into blocks - - :param limit: (required) - :type limit: int - :param index: - :type index: int - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ # noqa: E501 - - _param = self._txs_serialize( - limit=limit, - index=index, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index - ) - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Txs", - '400': "ResultCode", - } - response_data = await self.api_client.call_api( - *_param, - _request_timeout=_request_timeout - ) - return response_data.response - - - def _txs_serialize( - self, - limit, - index, - _request_auth, - _content_type, - _headers, - _host_index, - ) -> RequestSerialized: - - _host = None - - _collection_formats: Dict[str, str] = { - } - - _path_params: Dict[str, str] = {} - _query_params: List[Tuple[str, str]] = [] - _header_params: Dict[str, Optional[str]] = _headers or {} - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} - _body_params: Optional[bytes] = None - - # process the path parameters - # process the query parameters - if index is not None: - - _query_params.append(('index', index)) - - if limit is not None: - - _query_params.append(('limit', limit)) - - # process the header parameters - # process the form parameters - # process the body parameter - - - # set the HTTP header `Accept` - if 'Accept' not in _header_params: - _header_params['Accept'] = self.api_client.select_header_accept( - [ - 'application/json' - ] - ) - - - # authentication setting - _auth_settings: List[str] = [ - ] - - return self.api_client.param_serialize( - method='GET', - resource_path='/api/v1/txs', - path_params=_path_params, - query_params=_query_params, - header_params=_header_params, - body=_body_params, - post_params=_form_params, - files=_files, - auth_settings=_auth_settings, - collection_formats=_collection_formats, - _host=_host, - _request_auth=_request_auth - ) - - - - - @validate_call async def withdraw_history( self, account_index: StrictInt, @@ -3128,7 +2185,6 @@ async def withdraw_history( ).data - @validate_call async def withdraw_history_with_http_info( self, account_index: StrictInt, @@ -3212,7 +2268,6 @@ async def withdraw_history_with_http_info( ) - @validate_call async def withdraw_history_without_preload_content( self, account_index: StrictInt, @@ -3319,14 +2374,18 @@ def _withdraw_history_serialize( # process the path parameters # process the query parameters - if account_index is not None: + if authorization is not None: - _query_params.append(('account_index', account_index)) + _query_params.append(('authorization', authorization)) if auth is not None: _query_params.append(('auth', auth)) + if account_index is not None: + + _query_params.append(('account_index', account_index)) + if cursor is not None: _query_params.append(('cursor', cursor)) @@ -3336,8 +2395,6 @@ def _withdraw_history_serialize( _query_params.append(('filter', filter)) # process the header parameters - if authorization is not None: - _header_params['authorization'] = authorization # process the form parameters # process the body parameter diff --git a/lighter/models/__init__.py b/lighter/models/__init__.py index f5abd92..f54774b 100644 --- a/lighter/models/__init__.py +++ b/lighter/models/__init__.py @@ -16,6 +16,7 @@ # import models into model package from lighter.models.account import Account from lighter.models.account_api_keys import AccountApiKeys +from lighter.models.account_asset import AccountAsset from lighter.models.account_limits import AccountLimits from lighter.models.account_margin_stats import AccountMarginStats from lighter.models.account_market_stats import AccountMarketStats @@ -28,13 +29,15 @@ from lighter.models.announcement import Announcement from lighter.models.announcements import Announcements from lighter.models.api_key import ApiKey -from lighter.models.block import Block -from lighter.models.blocks import Blocks +from lighter.models.api_token import ApiToken +from lighter.models.asset import Asset +from lighter.models.asset_details import AssetDetails +from lighter.models.auth import Auth +from lighter.models.bridge import Bridge from lighter.models.bridge_supported_network import BridgeSupportedNetwork -from lighter.models.candlestick import Candlestick -from lighter.models.candlesticks import Candlesticks +from lighter.models.candle import Candle +from lighter.models.candles import Candles from lighter.models.contract_address import ContractAddress -from lighter.models.current_height import CurrentHeight from lighter.models.cursor import Cursor from lighter.models.daily_return import DailyReturn from lighter.models.deposit_history import DepositHistory @@ -55,28 +58,27 @@ from lighter.models.liquidation import Liquidation from lighter.models.liquidation_info import LiquidationInfo from lighter.models.liquidation_infos import LiquidationInfos -from lighter.models.market_info import MarketInfo +from lighter.models.market_config import MarketConfig from lighter.models.next_nonce import NextNonce from lighter.models.order import Order from lighter.models.order_book import OrderBook from lighter.models.order_book_depth import OrderBookDepth -from lighter.models.order_book_detail import OrderBookDetail +from lighter.models.order_book_depth_with_begin_nonce import OrderBookDepthWithBeginNonce from lighter.models.order_book_details import OrderBookDetails from lighter.models.order_book_orders import OrderBookOrders from lighter.models.order_book_stats import OrderBookStats from lighter.models.order_books import OrderBooks from lighter.models.orders import Orders +from lighter.models.perps_market_stats import PerpsMarketStats +from lighter.models.perps_order_book_detail import PerpsOrderBookDetail from lighter.models.pn_l_entry import PnLEntry from lighter.models.position_funding import PositionFunding from lighter.models.position_fundings import PositionFundings from lighter.models.price_level import PriceLevel -from lighter.models.public_pool import PublicPool from lighter.models.public_pool_info import PublicPoolInfo from lighter.models.public_pool_metadata import PublicPoolMetadata from lighter.models.public_pool_share import PublicPoolShare -from lighter.models.public_pools import PublicPools -from lighter.models.referral_point_entry import ReferralPointEntry -from lighter.models.referral_points import ReferralPoints +from lighter.models.req_do_faucet import ReqDoFaucet from lighter.models.req_export_data import ReqExportData from lighter.models.req_get_account import ReqGetAccount from lighter.models.req_get_account_active_orders import ReqGetAccountActiveOrders @@ -87,10 +89,13 @@ from lighter.models.req_get_account_metadata import ReqGetAccountMetadata from lighter.models.req_get_account_pn_l import ReqGetAccountPnL from lighter.models.req_get_account_txs import ReqGetAccountTxs +from lighter.models.req_get_api_tokens import ReqGetApiTokens +from lighter.models.req_get_asset_details import ReqGetAssetDetails from lighter.models.req_get_block import ReqGetBlock from lighter.models.req_get_block_txs import ReqGetBlockTxs +from lighter.models.req_get_bridges_by_l1_addr import ReqGetBridgesByL1Addr from lighter.models.req_get_by_account import ReqGetByAccount -from lighter.models.req_get_candlesticks import ReqGetCandlesticks +from lighter.models.req_get_candles import ReqGetCandles from lighter.models.req_get_deposit_history import ReqGetDepositHistory from lighter.models.req_get_fast_withdraw_info import ReqGetFastWithdrawInfo from lighter.models.req_get_fundings import ReqGetFundings @@ -103,21 +108,25 @@ from lighter.models.req_get_order_book_orders import ReqGetOrderBookOrders from lighter.models.req_get_order_books import ReqGetOrderBooks from lighter.models.req_get_position_funding import ReqGetPositionFunding -from lighter.models.req_get_public_pools import ReqGetPublicPools from lighter.models.req_get_public_pools_metadata import ReqGetPublicPoolsMetadata from lighter.models.req_get_range_with_cursor import ReqGetRangeWithCursor from lighter.models.req_get_range_with_index import ReqGetRangeWithIndex from lighter.models.req_get_range_with_index_sortable import ReqGetRangeWithIndexSortable from lighter.models.req_get_recent_trades import ReqGetRecentTrades -from lighter.models.req_get_referral_points import ReqGetReferralPoints from lighter.models.req_get_trades import ReqGetTrades from lighter.models.req_get_transfer_fee_info import ReqGetTransferFeeInfo from lighter.models.req_get_transfer_history import ReqGetTransferHistory from lighter.models.req_get_tx import ReqGetTx from lighter.models.req_get_withdraw_history import ReqGetWithdrawHistory from lighter.models.resp_change_account_tier import RespChangeAccountTier +from lighter.models.resp_get_api_tokens import RespGetApiTokens +from lighter.models.resp_get_bridges_by_l1_addr import RespGetBridgesByL1Addr from lighter.models.resp_get_fast_bridge_info import RespGetFastBridgeInfo +from lighter.models.resp_get_fastwithdrawal_info import RespGetFastwithdrawalInfo +from lighter.models.resp_get_is_next_bridge_fast import RespGetIsNextBridgeFast +from lighter.models.resp_post_api_token import RespPostApiToken from lighter.models.resp_public_pools_metadata import RespPublicPoolsMetadata +from lighter.models.resp_revoke_api_token import RespRevokeApiToken from lighter.models.resp_send_tx import RespSendTx from lighter.models.resp_send_tx_batch import RespSendTxBatch from lighter.models.resp_withdrawal_delay import RespWithdrawalDelay @@ -126,6 +135,8 @@ from lighter.models.risk_parameters import RiskParameters from lighter.models.share_price import SharePrice from lighter.models.simple_order import SimpleOrder +from lighter.models.spot_market_stats import SpotMarketStats +from lighter.models.spot_order_book_detail import SpotOrderBookDetail from lighter.models.status import Status from lighter.models.sub_accounts import SubAccounts from lighter.models.ticker import Ticker @@ -134,11 +145,11 @@ from lighter.models.transfer_fee_info import TransferFeeInfo from lighter.models.transfer_history import TransferHistory from lighter.models.transfer_history_item import TransferHistoryItem -from lighter.models.tx import Tx from lighter.models.tx_hash import TxHash from lighter.models.tx_hashes import TxHashes -from lighter.models.txs import Txs from lighter.models.validator_info import ValidatorInfo from lighter.models.withdraw_history import WithdrawHistory from lighter.models.withdraw_history_item import WithdrawHistoryItem from lighter.models.zk_lighter_info import ZkLighterInfo + +from lighter.models.ws_account_assets import WSAccountAssets diff --git a/lighter/models/account.py b/lighter/models/account.py index c14398c..d349e6f 100644 --- a/lighter/models/account.py +++ b/lighter/models/account.py @@ -35,11 +35,12 @@ class Account(BaseModel): total_order_count: StrictInt total_isolated_order_count: StrictInt pending_order_count: StrictInt - available_balance: Optional[StrictStr] + available_balance: StrictStr status: StrictInt collateral: StrictStr + transaction_time: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "account_type", "index", "l1_address", "cancel_all_time", "total_order_count", "total_isolated_order_count", "pending_order_count", "available_balance", "status", "collateral"] + __properties: ClassVar[List[str]] = ["code", "message", "account_type", "index", "l1_address", "cancel_all_time", "total_order_count", "total_isolated_order_count", "pending_order_count", "available_balance", "status", "collateral", "transaction_time"] model_config = ConfigDict( populate_by_name=True, @@ -98,7 +99,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "account_type": obj.get("account_type"), @@ -110,7 +111,8 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: "pending_order_count": obj.get("pending_order_count"), "available_balance": obj.get("available_balance"), "status": obj.get("status"), - "collateral": obj.get("collateral") + "collateral": obj.get("collateral"), + "transaction_time": obj.get("transaction_time") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/account_api_keys.py b/lighter/models/account_api_keys.py index da1e42c..78d7dbd 100644 --- a/lighter/models/account_api_keys.py +++ b/lighter/models/account_api_keys.py @@ -97,7 +97,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "api_keys": [ApiKey.from_dict(_item) for _item in obj["api_keys"]] if obj.get("api_keys") is not None else None diff --git a/lighter/models/account_asset.py b/lighter/models/account_asset.py new file mode 100644 index 0000000..c6ca30a --- /dev/null +++ b/lighter/models/account_asset.py @@ -0,0 +1,106 @@ +# coding: utf-8 + +""" + + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class AccountAsset(BaseModel): + """ + AccountAsset + """ # noqa: E501 + symbol: StrictStr + asset_id: StrictInt + balance: StrictStr + locked_balance: StrictStr + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["symbol", "asset_id", "balance", "locked_balance"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AccountAsset from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AccountAsset from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_construct(**{ + "symbol": obj.get("symbol"), + "asset_id": obj.get("asset_id"), + "balance": obj.get("balance"), + "locked_balance": obj.get("locked_balance") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/lighter/models/account_limits.py b/lighter/models/account_limits.py index 81eff07..47598f5 100644 --- a/lighter/models/account_limits.py +++ b/lighter/models/account_limits.py @@ -17,7 +17,7 @@ import re # noqa: F401 import json -from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr +from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set from typing_extensions import Self @@ -29,9 +29,11 @@ class AccountLimits(BaseModel): code: StrictInt message: Optional[StrictStr] = None max_llp_percentage: StrictInt + max_llp_amount: StrictStr user_tier: StrictStr + can_create_public_pool: StrictBool additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "max_llp_percentage", "user_tier"] + __properties: ClassVar[List[str]] = ["code", "message", "max_llp_percentage", "max_llp_amount", "user_tier", "can_create_public_pool"] model_config = ConfigDict( populate_by_name=True, @@ -90,11 +92,13 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "max_llp_percentage": obj.get("max_llp_percentage"), - "user_tier": obj.get("user_tier") + "max_llp_amount": obj.get("max_llp_amount"), + "user_tier": obj.get("user_tier"), + "can_create_public_pool": obj.get("can_create_public_pool") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/account_margin_stats.py b/lighter/models/account_margin_stats.py index bad64a8..03e5dea 100644 --- a/lighter/models/account_margin_stats.py +++ b/lighter/models/account_margin_stats.py @@ -92,7 +92,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "collateral": obj.get("collateral"), "portfolio_value": obj.get("portfolio_value"), "leverage": obj.get("leverage"), diff --git a/lighter/models/account_market_stats.py b/lighter/models/account_market_stats.py index efa1731..7065b2d 100644 --- a/lighter/models/account_market_stats.py +++ b/lighter/models/account_market_stats.py @@ -99,7 +99,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "market_id": obj.get("market_id"), "daily_trades_count": obj.get("daily_trades_count"), "daily_base_token_volume": obj.get("daily_base_token_volume"), diff --git a/lighter/models/account_metadata.py b/lighter/models/account_metadata.py index ddd09e6..ee08b50 100644 --- a/lighter/models/account_metadata.py +++ b/lighter/models/account_metadata.py @@ -91,7 +91,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "account_index": obj.get("account_index"), "name": obj.get("name"), "description": obj.get("description"), diff --git a/lighter/models/account_metadatas.py b/lighter/models/account_metadatas.py index 3d41085..b77d80a 100644 --- a/lighter/models/account_metadatas.py +++ b/lighter/models/account_metadatas.py @@ -97,7 +97,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "account_metadatas": [AccountMetadata.from_dict(_item) for _item in obj["account_metadatas"]] if obj.get("account_metadatas") is not None else None diff --git a/lighter/models/account_pn_l.py b/lighter/models/account_pn_l.py index 9196cf0..55ec511 100644 --- a/lighter/models/account_pn_l.py +++ b/lighter/models/account_pn_l.py @@ -98,7 +98,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "resolution": obj.get("resolution"), diff --git a/lighter/models/account_position.py b/lighter/models/account_position.py index 9942715..50021b6 100644 --- a/lighter/models/account_position.py +++ b/lighter/models/account_position.py @@ -102,7 +102,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "market_id": obj.get("market_id"), "symbol": obj.get("symbol"), "initial_margin_fraction": obj.get("initial_margin_fraction"), diff --git a/lighter/models/account_stats.py b/lighter/models/account_stats.py index 9fac368..6587f78 100644 --- a/lighter/models/account_stats.py +++ b/lighter/models/account_stats.py @@ -30,7 +30,7 @@ class AccountStats(BaseModel): collateral: StrictStr portfolio_value: StrictStr leverage: StrictStr - available_balance: Optional[StrictStr] + available_balance: StrictStr margin_usage: StrictStr buying_power: StrictStr cross_stats: AccountMarginStats @@ -101,7 +101,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "collateral": obj.get("collateral"), "portfolio_value": obj.get("portfolio_value"), "leverage": obj.get("leverage"), diff --git a/lighter/models/account_trade_stats.py b/lighter/models/account_trade_stats.py index a266610..2a783fc 100644 --- a/lighter/models/account_trade_stats.py +++ b/lighter/models/account_trade_stats.py @@ -94,7 +94,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "daily_trades_count": obj.get("daily_trades_count"), "daily_volume": obj.get("daily_volume"), "weekly_trades_count": obj.get("weekly_trades_count"), diff --git a/lighter/models/announcement.py b/lighter/models/announcement.py index cbccae5..a721cf3 100644 --- a/lighter/models/announcement.py +++ b/lighter/models/announcement.py @@ -29,8 +29,9 @@ class Announcement(BaseModel): title: StrictStr content: StrictStr created_at: StrictInt + expired_at: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["title", "content", "created_at"] + __properties: ClassVar[List[str]] = ["title", "content", "created_at", "expired_at"] model_config = ConfigDict( populate_by_name=True, @@ -89,10 +90,11 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "title": obj.get("title"), "content": obj.get("content"), - "created_at": obj.get("created_at") + "created_at": obj.get("created_at"), + "expired_at": obj.get("expired_at") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/announcements.py b/lighter/models/announcements.py index d89894f..4eb8081 100644 --- a/lighter/models/announcements.py +++ b/lighter/models/announcements.py @@ -97,7 +97,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "announcements": [Announcement.from_dict(_item) for _item in obj["announcements"]] if obj.get("announcements") is not None else None diff --git a/lighter/models/api_key.py b/lighter/models/api_key.py index f02af99..96e9d91 100644 --- a/lighter/models/api_key.py +++ b/lighter/models/api_key.py @@ -30,8 +30,9 @@ class ApiKey(BaseModel): api_key_index: StrictInt nonce: StrictInt public_key: StrictStr + transaction_time: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["account_index", "api_key_index", "nonce", "public_key"] + __properties: ClassVar[List[str]] = ["account_index", "api_key_index", "nonce", "public_key", "transaction_time"] model_config = ConfigDict( populate_by_name=True, @@ -90,11 +91,12 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "account_index": obj.get("account_index"), "api_key_index": obj.get("api_key_index"), "nonce": obj.get("nonce"), - "public_key": obj.get("public_key") + "public_key": obj.get("public_key"), + "transaction_time": obj.get("transaction_time") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/api_token.py b/lighter/models/api_token.py new file mode 100644 index 0000000..c61cff1 --- /dev/null +++ b/lighter/models/api_token.py @@ -0,0 +1,114 @@ +# coding: utf-8 + +""" + + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class ApiToken(BaseModel): + """ + ApiToken + """ # noqa: E501 + token_id: StrictInt + api_token: StrictStr + name: StrictStr + account_index: StrictInt + expiry: StrictInt + sub_account_access: StrictBool + revoked: StrictBool + scopes: StrictStr + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["token_id", "api_token", "name", "account_index", "expiry", "sub_account_access", "revoked", "scopes"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ApiToken from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ApiToken from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_construct(**{ + "token_id": obj.get("token_id"), + "api_token": obj.get("api_token"), + "name": obj.get("name"), + "account_index": obj.get("account_index"), + "expiry": obj.get("expiry"), + "sub_account_access": obj.get("sub_account_access"), + "revoked": obj.get("revoked"), + "scopes": obj.get("scopes") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/lighter/models/asset.py b/lighter/models/asset.py new file mode 100644 index 0000000..462bac2 --- /dev/null +++ b/lighter/models/asset.py @@ -0,0 +1,123 @@ +# coding: utf-8 + +""" + + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class Asset(BaseModel): + """ + Asset + """ # noqa: E501 + asset_id: StrictInt + symbol: StrictStr + l1_decimals: StrictInt + decimals: StrictInt + min_transfer_amount: StrictStr + min_withdrawal_amount: StrictStr + margin_mode: StrictStr + index_price: StrictStr + l1_address: StrictStr + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["asset_id", "symbol", "l1_decimals", "decimals", "min_transfer_amount", "min_withdrawal_amount", "margin_mode", "index_price", "l1_address"] + + @field_validator('margin_mode') + def margin_mode_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['enabled', 'disabled']): + raise ValueError("must be one of enum values ('enabled', 'disabled')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Asset from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Asset from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_construct(**{ + "asset_id": obj.get("asset_id"), + "symbol": obj.get("symbol"), + "l1_decimals": obj.get("l1_decimals"), + "decimals": obj.get("decimals"), + "min_transfer_amount": obj.get("min_transfer_amount"), + "min_withdrawal_amount": obj.get("min_withdrawal_amount"), + "margin_mode": obj.get("margin_mode"), + "index_price": obj.get("index_price"), + "l1_address": obj.get("l1_address") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/lighter/models/txs.py b/lighter/models/asset_details.py similarity index 82% rename from lighter/models/txs.py rename to lighter/models/asset_details.py index 8beafb5..7935030 100644 --- a/lighter/models/txs.py +++ b/lighter/models/asset_details.py @@ -19,19 +19,19 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from lighter.models.tx import Tx +from lighter.models.asset import Asset from typing import Optional, Set from typing_extensions import Self -class Txs(BaseModel): +class AssetDetails(BaseModel): """ - Txs + AssetDetails """ # noqa: E501 code: StrictInt message: Optional[StrictStr] = None - txs: List[Tx] + asset_details: List[Asset] additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "txs"] + __properties: ClassVar[List[str]] = ["code", "message", "asset_details"] model_config = ConfigDict( populate_by_name=True, @@ -51,7 +51,7 @@ def to_json(self) -> str: @classmethod def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Txs from a JSON string""" + """Create an instance of AssetDetails from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -74,13 +74,13 @@ def to_dict(self) -> Dict[str, Any]: exclude=excluded_fields, exclude_none=True, ) - # override the default output from pydantic by calling `to_dict()` of each item in txs (list) + # override the default output from pydantic by calling `to_dict()` of each item in asset_details (list) _items = [] - if self.txs: - for _item in self.txs: + if self.asset_details: + for _item in self.asset_details: if _item: _items.append(_item.to_dict()) - _dict['txs'] = _items + _dict['asset_details'] = _items # puts key-value pairs in additional_properties in the top level if self.additional_properties is not None: for _key, _value in self.additional_properties.items(): @@ -90,17 +90,17 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Txs from a dict""" + """Create an instance of AssetDetails from a dict""" if obj is None: return None if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), - "txs": [Tx.from_dict(_item) for _item in obj["txs"]] if obj.get("txs") is not None else None + "asset_details": [Asset.from_dict(_item) for _item in obj["asset_details"]] if obj.get("asset_details") is not None else None }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/auth.py b/lighter/models/auth.py new file mode 100644 index 0000000..7f590f7 --- /dev/null +++ b/lighter/models/auth.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class Auth(BaseModel): + """ + Auth + """ # noqa: E501 + auth: StrictStr = Field(description=" made optional to support header auth clients") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["auth"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Auth from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Auth from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_construct(**{ + "auth": obj.get("auth") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/lighter/models/block.py b/lighter/models/bridge.py similarity index 55% rename from lighter/models/block.py rename to lighter/models/bridge.py index 7e550d7..2b4f5f6 100644 --- a/lighter/models/block.py +++ b/lighter/models/bridge.py @@ -17,31 +17,46 @@ import re # noqa: F401 import json -from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr +from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List -from lighter.models.tx import Tx from typing import Optional, Set from typing_extensions import Self -class Block(BaseModel): +class Bridge(BaseModel): """ - Block + Bridge """ # noqa: E501 - commitment: StrictStr - height: StrictInt - state_root: StrictStr - priority_operations: StrictInt - on_chain_l2_operations: StrictInt - pending_on_chain_operations_pub_data: StrictStr - committed_tx_hash: StrictStr - committed_at: StrictInt - verified_tx_hash: StrictStr - verified_at: StrictInt - txs: List[Tx] - status: StrictInt - size: StrictInt + id: StrictInt + version: StrictInt + source: StrictStr + source_chain_id: StrictStr + fast_bridge_tx_hash: StrictStr + batch_claim_tx_hash: StrictStr + cctp_burn_tx_hash: StrictStr + amount: StrictStr + intent_address: StrictStr + status: StrictStr + step: StrictStr + description: StrictStr + created_at: StrictInt + updated_at: StrictInt + is_external_deposit: StrictBool additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["commitment", "height", "state_root", "priority_operations", "on_chain_l2_operations", "pending_on_chain_operations_pub_data", "committed_tx_hash", "committed_at", "verified_tx_hash", "verified_at", "txs", "status", "size"] + __properties: ClassVar[List[str]] = ["id", "version", "source", "source_chain_id", "fast_bridge_tx_hash", "batch_claim_tx_hash", "cctp_burn_tx_hash", "amount", "intent_address", "status", "step", "description", "created_at", "updated_at", "is_external_deposit"] + + @field_validator('version') + def version_validate_enum(cls, value): + """Validates the enum""" + if value not in set([1, 2]): + raise ValueError("must be one of enum values (1, 2)") + return value + + @field_validator('status') + def status_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['pending', 'bridging', 'completed']): + raise ValueError("must be one of enum values ('pending', 'bridging', 'completed')") + return value model_config = ConfigDict( populate_by_name=True, @@ -61,7 +76,7 @@ def to_json(self) -> str: @classmethod def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Block from a JSON string""" + """Create an instance of Bridge from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -84,13 +99,6 @@ def to_dict(self) -> Dict[str, Any]: exclude=excluded_fields, exclude_none=True, ) - # override the default output from pydantic by calling `to_dict()` of each item in txs (list) - _items = [] - if self.txs: - for _item in self.txs: - if _item: - _items.append(_item.to_dict()) - _dict['txs'] = _items # puts key-value pairs in additional_properties in the top level if self.additional_properties is not None: for _key, _value in self.additional_properties.items(): @@ -100,27 +108,29 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Block from a dict""" + """Create an instance of Bridge from a dict""" if obj is None: return None if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ - "commitment": obj.get("commitment"), - "height": obj.get("height"), - "state_root": obj.get("state_root"), - "priority_operations": obj.get("priority_operations"), - "on_chain_l2_operations": obj.get("on_chain_l2_operations"), - "pending_on_chain_operations_pub_data": obj.get("pending_on_chain_operations_pub_data"), - "committed_tx_hash": obj.get("committed_tx_hash"), - "committed_at": obj.get("committed_at"), - "verified_tx_hash": obj.get("verified_tx_hash"), - "verified_at": obj.get("verified_at"), - "txs": [Tx.from_dict(_item) for _item in obj["txs"]] if obj.get("txs") is not None else None, + _obj = cls.model_construct(**{ + "id": obj.get("id"), + "version": obj.get("version"), + "source": obj.get("source"), + "source_chain_id": obj.get("source_chain_id"), + "fast_bridge_tx_hash": obj.get("fast_bridge_tx_hash"), + "batch_claim_tx_hash": obj.get("batch_claim_tx_hash"), + "cctp_burn_tx_hash": obj.get("cctp_burn_tx_hash"), + "amount": obj.get("amount"), + "intent_address": obj.get("intent_address"), "status": obj.get("status"), - "size": obj.get("size") + "step": obj.get("step"), + "description": obj.get("description"), + "created_at": obj.get("created_at"), + "updated_at": obj.get("updated_at"), + "is_external_deposit": obj.get("is_external_deposit") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/bridge_supported_network.py b/lighter/models/bridge_supported_network.py index 4e3533a..158afc6 100644 --- a/lighter/models/bridge_supported_network.py +++ b/lighter/models/bridge_supported_network.py @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "name": obj.get("name"), "chain_id": obj.get("chain_id"), "explorer": obj.get("explorer") diff --git a/lighter/models/candle.py b/lighter/models/candle.py new file mode 100644 index 0000000..f1f0d13 --- /dev/null +++ b/lighter/models/candle.py @@ -0,0 +1,122 @@ +# coding: utf-8 + +""" + + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt +from typing import Any, ClassVar, Dict, List, Union +from typing import Optional, Set +from typing_extensions import Self + +class Candle(BaseModel): + """ + Candle + """ # noqa: E501 + t: StrictInt = Field(description=" timestamp") + o: Union[StrictFloat, StrictInt] = Field(description=" open") + h: Union[StrictFloat, StrictInt] = Field(description=" high") + l: Union[StrictFloat, StrictInt] = Field(description=" low") + c: Union[StrictFloat, StrictInt] = Field(description=" close") + o: Union[StrictFloat, StrictInt] = Field(description=" open_raw", alias="O") + h: Union[StrictFloat, StrictInt] = Field(description=" high_raw", alias="H") + l: Union[StrictFloat, StrictInt] = Field(description=" low_raw", alias="L") + c: Union[StrictFloat, StrictInt] = Field(description=" close_raw", alias="C") + v: Union[StrictFloat, StrictInt] = Field(description=" volume0") + v: Union[StrictFloat, StrictInt] = Field(description=" volume1", alias="V") + i: StrictInt = Field(description=" last_trade_id") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["t", "o", "h", "l", "c", "O", "H", "L", "C", "v", "V", "i"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Candle from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Candle from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_construct(**{ + "t": obj.get("t"), + "o": obj.get("o"), + "h": obj.get("h"), + "l": obj.get("l"), + "c": obj.get("c"), + "O": obj.get("O"), + "H": obj.get("H"), + "L": obj.get("L"), + "C": obj.get("C"), + "v": obj.get("v"), + "V": obj.get("V"), + "i": obj.get("i") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/lighter/models/candlesticks.py b/lighter/models/candles.py similarity index 78% rename from lighter/models/candlesticks.py rename to lighter/models/candles.py index a8184f9..53a41de 100644 --- a/lighter/models/candlesticks.py +++ b/lighter/models/candles.py @@ -17,22 +17,22 @@ import re # noqa: F401 import json -from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from lighter.models.candlestick import Candlestick +from lighter.models.candle import Candle from typing import Optional, Set from typing_extensions import Self -class Candlesticks(BaseModel): +class Candles(BaseModel): """ - Candlesticks + Candles """ # noqa: E501 code: StrictInt message: Optional[StrictStr] = None - resolution: StrictStr - candlesticks: List[Candlestick] + r: StrictStr = Field(description=" resolution") + c: List[Candle] = Field(description=" candles") additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "resolution", "candlesticks"] + __properties: ClassVar[List[str]] = ["code", "message", "r", "c"] model_config = ConfigDict( populate_by_name=True, @@ -52,7 +52,7 @@ def to_json(self) -> str: @classmethod def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Candlesticks from a JSON string""" + """Create an instance of Candles from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -75,13 +75,13 @@ def to_dict(self) -> Dict[str, Any]: exclude=excluded_fields, exclude_none=True, ) - # override the default output from pydantic by calling `to_dict()` of each item in candlesticks (list) + # override the default output from pydantic by calling `to_dict()` of each item in c (list) _items = [] - if self.candlesticks: - for _item in self.candlesticks: + if self.c: + for _item in self.c: if _item: _items.append(_item.to_dict()) - _dict['candlesticks'] = _items + _dict['c'] = _items # puts key-value pairs in additional_properties in the top level if self.additional_properties is not None: for _key, _value in self.additional_properties.items(): @@ -91,18 +91,18 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Candlesticks from a dict""" + """Create an instance of Candles from a dict""" if obj is None: return None if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), - "resolution": obj.get("resolution"), - "candlesticks": [Candlestick.from_dict(_item) for _item in obj["candlesticks"]] if obj.get("candlesticks") is not None else None + "r": obj.get("r"), + "c": [Candle.from_dict(_item) for _item in obj["c"]] if obj.get("c") is not None else None }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/contract_address.py b/lighter/models/contract_address.py index 768652e..662540a 100644 --- a/lighter/models/contract_address.py +++ b/lighter/models/contract_address.py @@ -88,7 +88,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "name": obj.get("name"), "address": obj.get("address") }) diff --git a/lighter/models/cursor.py b/lighter/models/cursor.py index a1ca1ef..4468d46 100644 --- a/lighter/models/cursor.py +++ b/lighter/models/cursor.py @@ -87,7 +87,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "next_cursor": obj.get("next_cursor") }) # store additional fields in additional_properties diff --git a/lighter/models/daily_return.py b/lighter/models/daily_return.py index 0453381..af99736 100644 --- a/lighter/models/daily_return.py +++ b/lighter/models/daily_return.py @@ -88,7 +88,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "timestamp": obj.get("timestamp"), "daily_return": obj.get("daily_return") }) diff --git a/lighter/models/deposit_history.py b/lighter/models/deposit_history.py index 2b2e238..b0a68ab 100644 --- a/lighter/models/deposit_history.py +++ b/lighter/models/deposit_history.py @@ -98,7 +98,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "deposits": [DepositHistoryItem.from_dict(_item) for _item in obj["deposits"]] if obj.get("deposits") is not None else None, diff --git a/lighter/models/deposit_history_item.py b/lighter/models/deposit_history_item.py index c7a1894..49f6186 100644 --- a/lighter/models/deposit_history_item.py +++ b/lighter/models/deposit_history_item.py @@ -27,12 +27,13 @@ class DepositHistoryItem(BaseModel): DepositHistoryItem """ # noqa: E501 id: StrictStr + asset_id: StrictInt amount: StrictStr timestamp: StrictInt status: StrictStr l1_tx_hash: StrictStr additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["id", "amount", "timestamp", "status", "l1_tx_hash"] + __properties: ClassVar[List[str]] = ["id", "asset_id", "amount", "timestamp", "status", "l1_tx_hash"] @field_validator('status') def status_validate_enum(cls, value): @@ -98,8 +99,9 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "id": obj.get("id"), + "asset_id": obj.get("asset_id"), "amount": obj.get("amount"), "timestamp": obj.get("timestamp"), "status": obj.get("status"), diff --git a/lighter/models/detailed_account.py b/lighter/models/detailed_account.py index eb8a0b0..cbeff8a 100644 --- a/lighter/models/detailed_account.py +++ b/lighter/models/detailed_account.py @@ -19,6 +19,7 @@ from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional +from lighter.models.account_asset import AccountAsset from lighter.models.account_position import AccountPosition from lighter.models.public_pool_info import PublicPoolInfo from lighter.models.public_pool_share import PublicPoolShare @@ -38,21 +39,23 @@ class DetailedAccount(BaseModel): total_order_count: StrictInt total_isolated_order_count: StrictInt pending_order_count: StrictInt - available_balance: Optional[StrictStr] + available_balance: StrictStr status: StrictInt collateral: StrictStr + transaction_time: StrictInt account_index: StrictInt name: StrictStr description: StrictStr can_invite: StrictBool = Field(description=" Remove After FE uses L1 meta endpoint") referral_points_percentage: StrictStr = Field(description=" Remove After FE uses L1 meta endpoint") positions: List[AccountPosition] + assets: List[AccountAsset] total_asset_value: StrictStr cross_asset_value: StrictStr - pool_info: Optional[PublicPoolInfo] + pool_info: PublicPoolInfo shares: List[PublicPoolShare] additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "account_type", "index", "l1_address", "cancel_all_time", "total_order_count", "total_isolated_order_count", "pending_order_count", "available_balance", "status", "collateral", "account_index", "name", "description", "can_invite", "referral_points_percentage", "positions", "total_asset_value", "cross_asset_value", "pool_info", "shares"] + __properties: ClassVar[List[str]] = ["code", "message", "account_type", "index", "l1_address", "cancel_all_time", "total_order_count", "total_isolated_order_count", "pending_order_count", "available_balance", "status", "collateral", "transaction_time", "account_index", "name", "description", "can_invite", "referral_points_percentage", "positions", "assets", "total_asset_value", "cross_asset_value", "pool_info", "shares"] model_config = ConfigDict( populate_by_name=True, @@ -102,6 +105,13 @@ def to_dict(self) -> Dict[str, Any]: if _item: _items.append(_item.to_dict()) _dict['positions'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in assets (list) + _items = [] + if self.assets: + for _item in self.assets: + if _item: + _items.append(_item.to_dict()) + _dict['assets'] = _items # override the default output from pydantic by calling `to_dict()` of pool_info if self.pool_info: _dict['pool_info'] = self.pool_info.to_dict() @@ -128,7 +138,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "account_type": obj.get("account_type"), @@ -141,12 +151,14 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: "available_balance": obj.get("available_balance"), "status": obj.get("status"), "collateral": obj.get("collateral"), + "transaction_time": obj.get("transaction_time"), "account_index": obj.get("account_index"), "name": obj.get("name"), "description": obj.get("description"), "can_invite": obj.get("can_invite"), "referral_points_percentage": obj.get("referral_points_percentage"), "positions": [AccountPosition.from_dict(_item) for _item in obj["positions"]] if obj.get("positions") is not None else None, + "assets": [AccountAsset.from_dict(_item) for _item in obj["assets"]] if obj.get("assets") is not None else None, "total_asset_value": obj.get("total_asset_value"), "cross_asset_value": obj.get("cross_asset_value"), "pool_info": PublicPoolInfo.from_dict(obj["pool_info"]) if obj.get("pool_info") is not None else None, diff --git a/lighter/models/detailed_accounts.py b/lighter/models/detailed_accounts.py index 50f61e1..5fde717 100644 --- a/lighter/models/detailed_accounts.py +++ b/lighter/models/detailed_accounts.py @@ -98,7 +98,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "total": obj.get("total"), diff --git a/lighter/models/detailed_candlestick.py b/lighter/models/detailed_candlestick.py index 36a84ca..4ff5987 100644 --- a/lighter/models/detailed_candlestick.py +++ b/lighter/models/detailed_candlestick.py @@ -31,12 +31,16 @@ class DetailedCandlestick(BaseModel): high: Union[StrictFloat, StrictInt] low: Union[StrictFloat, StrictInt] close: Union[StrictFloat, StrictInt] + open_raw: Union[StrictFloat, StrictInt] + high_raw: Union[StrictFloat, StrictInt] + low_raw: Union[StrictFloat, StrictInt] + close_raw: Union[StrictFloat, StrictInt] volume0: Union[StrictFloat, StrictInt] volume1: Union[StrictFloat, StrictInt] last_trade_id: StrictInt trade_count: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["timestamp", "open", "high", "low", "close", "volume0", "volume1", "last_trade_id", "trade_count"] + __properties: ClassVar[List[str]] = ["timestamp", "open", "high", "low", "close", "open_raw", "high_raw", "low_raw", "close_raw", "volume0", "volume1", "last_trade_id", "trade_count"] model_config = ConfigDict( populate_by_name=True, @@ -95,12 +99,16 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "timestamp": obj.get("timestamp"), "open": obj.get("open"), "high": obj.get("high"), "low": obj.get("low"), "close": obj.get("close"), + "open_raw": obj.get("open_raw"), + "high_raw": obj.get("high_raw"), + "low_raw": obj.get("low_raw"), + "close_raw": obj.get("close_raw"), "volume0": obj.get("volume0"), "volume1": obj.get("volume1"), "last_trade_id": obj.get("last_trade_id"), diff --git a/lighter/models/enriched_tx.py b/lighter/models/enriched_tx.py index 08567b2..7956354 100644 --- a/lighter/models/enriched_tx.py +++ b/lighter/models/enriched_tx.py @@ -44,10 +44,12 @@ class EnrichedTx(BaseModel): executed_at: StrictInt sequence_index: StrictInt parent_hash: StrictStr + api_key_index: StrictInt + transaction_time: StrictInt committed_at: StrictInt verified_at: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "hash", "type", "info", "event_info", "status", "transaction_index", "l1_address", "account_index", "nonce", "expire_at", "block_height", "queued_at", "executed_at", "sequence_index", "parent_hash", "committed_at", "verified_at"] + __properties: ClassVar[List[str]] = ["code", "message", "hash", "type", "info", "event_info", "status", "transaction_index", "l1_address", "account_index", "nonce", "expire_at", "block_height", "queued_at", "executed_at", "sequence_index", "parent_hash", "api_key_index", "transaction_time", "committed_at", "verified_at"] model_config = ConfigDict( populate_by_name=True, @@ -106,7 +108,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "hash": obj.get("hash"), @@ -124,6 +126,8 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: "executed_at": obj.get("executed_at"), "sequence_index": obj.get("sequence_index"), "parent_hash": obj.get("parent_hash"), + "api_key_index": obj.get("api_key_index"), + "transaction_time": obj.get("transaction_time"), "committed_at": obj.get("committed_at"), "verified_at": obj.get("verified_at") }) diff --git a/lighter/models/exchange_stats.py b/lighter/models/exchange_stats.py index fa276ce..f3e6fc5 100644 --- a/lighter/models/exchange_stats.py +++ b/lighter/models/exchange_stats.py @@ -100,7 +100,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "total": obj.get("total"), diff --git a/lighter/models/export_data.py b/lighter/models/export_data.py index 4e712d8..f16b03e 100644 --- a/lighter/models/export_data.py +++ b/lighter/models/export_data.py @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "data_url": obj.get("data_url") diff --git a/lighter/models/funding.py b/lighter/models/funding.py index 727be7d..99e0204 100644 --- a/lighter/models/funding.py +++ b/lighter/models/funding.py @@ -90,7 +90,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "timestamp": obj.get("timestamp"), "value": obj.get("value"), "rate": obj.get("rate"), diff --git a/lighter/models/funding_rate.py b/lighter/models/funding_rate.py index ff591b1..7b8129a 100644 --- a/lighter/models/funding_rate.py +++ b/lighter/models/funding_rate.py @@ -97,7 +97,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "market_id": obj.get("market_id"), "exchange": obj.get("exchange"), "symbol": obj.get("symbol"), diff --git a/lighter/models/funding_rates.py b/lighter/models/funding_rates.py index 90e062b..73d4e95 100644 --- a/lighter/models/funding_rates.py +++ b/lighter/models/funding_rates.py @@ -97,7 +97,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "funding_rates": [FundingRate.from_dict(_item) for _item in obj["funding_rates"]] if obj.get("funding_rates") is not None else None diff --git a/lighter/models/fundings.py b/lighter/models/fundings.py index 0ace19a..3aaa32c 100644 --- a/lighter/models/fundings.py +++ b/lighter/models/fundings.py @@ -98,7 +98,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "resolution": obj.get("resolution"), diff --git a/lighter/models/l1_metadata.py b/lighter/models/l1_metadata.py index 19f653b..736c0c2 100644 --- a/lighter/models/l1_metadata.py +++ b/lighter/models/l1_metadata.py @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "l1_address": obj.get("l1_address"), "can_invite": obj.get("can_invite"), "referral_points_percentage": obj.get("referral_points_percentage") diff --git a/lighter/models/l1_provider_info.py b/lighter/models/l1_provider_info.py index 41e5a3b..55d9ee5 100644 --- a/lighter/models/l1_provider_info.py +++ b/lighter/models/l1_provider_info.py @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "chainId": obj.get("chainId"), "networkId": obj.get("networkId"), "latestBlockNumber": obj.get("latestBlockNumber") diff --git a/lighter/models/liq_trade.py b/lighter/models/liq_trade.py index 276042e..5d00ace 100644 --- a/lighter/models/liq_trade.py +++ b/lighter/models/liq_trade.py @@ -17,7 +17,7 @@ import re # noqa: F401 import json -from pydantic import BaseModel, ConfigDict, StrictStr +from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List from typing import Optional, Set from typing_extensions import Self @@ -30,8 +30,9 @@ class LiqTrade(BaseModel): size: StrictStr taker_fee: StrictStr maker_fee: StrictStr + transaction_time: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["price", "size", "taker_fee", "maker_fee"] + __properties: ClassVar[List[str]] = ["price", "size", "taker_fee", "maker_fee", "transaction_time"] model_config = ConfigDict( populate_by_name=True, @@ -90,11 +91,12 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "price": obj.get("price"), "size": obj.get("size"), "taker_fee": obj.get("taker_fee"), - "maker_fee": obj.get("maker_fee") + "maker_fee": obj.get("maker_fee"), + "transaction_time": obj.get("transaction_time") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/liquidation.py b/lighter/models/liquidation.py index aa012a4..e8fc2a2 100644 --- a/lighter/models/liquidation.py +++ b/lighter/models/liquidation.py @@ -107,7 +107,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "id": obj.get("id"), "market_id": obj.get("market_id"), "type": obj.get("type"), diff --git a/lighter/models/liquidation_info.py b/lighter/models/liquidation_info.py index 91519d1..ad0a781 100644 --- a/lighter/models/liquidation_info.py +++ b/lighter/models/liquidation_info.py @@ -105,7 +105,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "positions": [AccountPosition.from_dict(_item) for _item in obj["positions"]] if obj.get("positions") is not None else None, "risk_info_before": RiskInfo.from_dict(obj["risk_info_before"]) if obj.get("risk_info_before") is not None else None, "risk_info_after": RiskInfo.from_dict(obj["risk_info_after"]) if obj.get("risk_info_after") is not None else None, diff --git a/lighter/models/liquidation_infos.py b/lighter/models/liquidation_infos.py index 9d633d7..9e5b6b2 100644 --- a/lighter/models/liquidation_infos.py +++ b/lighter/models/liquidation_infos.py @@ -98,7 +98,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "liquidations": [Liquidation.from_dict(_item) for _item in obj["liquidations"]] if obj.get("liquidations") is not None else None, diff --git a/lighter/models/market_config.py b/lighter/models/market_config.py new file mode 100644 index 0000000..d898dde --- /dev/null +++ b/lighter/models/market_config.py @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class MarketConfig(BaseModel): + """ + MarketConfig + """ # noqa: E501 + market_margin_mode: StrictInt + insurance_fund_account_index: StrictInt + liquidation_mode: StrictInt + force_reduce_only: StrictBool + trading_hours: StrictStr + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["market_margin_mode", "insurance_fund_account_index", "liquidation_mode", "force_reduce_only", "trading_hours"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of MarketConfig from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of MarketConfig from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_construct(**{ + "market_margin_mode": obj.get("market_margin_mode"), + "insurance_fund_account_index": obj.get("insurance_fund_account_index"), + "liquidation_mode": obj.get("liquidation_mode"), + "force_reduce_only": obj.get("force_reduce_only"), + "trading_hours": obj.get("trading_hours") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/lighter/models/next_nonce.py b/lighter/models/next_nonce.py index 94ab734..5d698f1 100644 --- a/lighter/models/next_nonce.py +++ b/lighter/models/next_nonce.py @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "nonce": obj.get("nonce") diff --git a/lighter/models/order.py b/lighter/models/order.py index 47d6543..42c370a 100644 --- a/lighter/models/order.py +++ b/lighter/models/order.py @@ -57,8 +57,11 @@ class Order(BaseModel): to_cancel_order_id_0: StrictStr block_height: StrictInt timestamp: StrictInt + created_at: StrictInt + updated_at: StrictInt + transaction_time: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["order_index", "client_order_index", "order_id", "client_order_id", "market_index", "owner_account_index", "initial_base_amount", "price", "nonce", "remaining_base_amount", "is_ask", "base_size", "base_price", "filled_base_amount", "filled_quote_amount", "side", "type", "time_in_force", "reduce_only", "trigger_price", "order_expiry", "status", "trigger_status", "trigger_time", "parent_order_index", "parent_order_id", "to_trigger_order_id_0", "to_trigger_order_id_1", "to_cancel_order_id_0", "block_height", "timestamp"] + __properties: ClassVar[List[str]] = ["order_index", "client_order_index", "order_id", "client_order_id", "market_index", "owner_account_index", "initial_base_amount", "price", "nonce", "remaining_base_amount", "is_ask", "base_size", "base_price", "filled_base_amount", "filled_quote_amount", "side", "type", "time_in_force", "reduce_only", "trigger_price", "order_expiry", "status", "trigger_status", "trigger_time", "parent_order_index", "parent_order_id", "to_trigger_order_id_0", "to_trigger_order_id_1", "to_cancel_order_id_0", "block_height", "timestamp", "created_at", "updated_at", "transaction_time"] @field_validator('type') def type_validate_enum(cls, value): @@ -77,8 +80,8 @@ def time_in_force_validate_enum(cls, value): @field_validator('status') def status_validate_enum(cls, value): """Validates the enum""" - if value not in set(['in-progress', 'pending', 'open', 'filled', 'canceled', 'canceled-post-only', 'canceled-reduce-only', 'canceled-position-not-allowed', 'canceled-margin-not-allowed', 'canceled-too-much-slippage', 'canceled-not-enough-liquidity', 'canceled-self-trade', 'canceled-expired', 'canceled-oco', 'canceled-child', 'canceled-liquidation']): - raise ValueError("must be one of enum values ('in-progress', 'pending', 'open', 'filled', 'canceled', 'canceled-post-only', 'canceled-reduce-only', 'canceled-position-not-allowed', 'canceled-margin-not-allowed', 'canceled-too-much-slippage', 'canceled-not-enough-liquidity', 'canceled-self-trade', 'canceled-expired', 'canceled-oco', 'canceled-child', 'canceled-liquidation')") + if value not in set(['in-progress', 'pending', 'open', 'filled', 'canceled', 'canceled-post-only', 'canceled-reduce-only', 'canceled-position-not-allowed', 'canceled-margin-not-allowed', 'canceled-too-much-slippage', 'canceled-not-enough-liquidity', 'canceled-self-trade', 'canceled-expired', 'canceled-oco', 'canceled-child', 'canceled-liquidation', 'canceled-invalid-balance']): + raise ValueError("must be one of enum values ('in-progress', 'pending', 'open', 'filled', 'canceled', 'canceled-post-only', 'canceled-reduce-only', 'canceled-position-not-allowed', 'canceled-margin-not-allowed', 'canceled-too-much-slippage', 'canceled-not-enough-liquidity', 'canceled-self-trade', 'canceled-expired', 'canceled-oco', 'canceled-child', 'canceled-liquidation', 'canceled-invalid-balance')") return value @field_validator('trigger_status') @@ -145,7 +148,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "order_index": obj.get("order_index"), "client_order_index": obj.get("client_order_index"), "order_id": obj.get("order_id"), @@ -176,7 +179,10 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: "to_trigger_order_id_1": obj.get("to_trigger_order_id_1"), "to_cancel_order_id_0": obj.get("to_cancel_order_id_0"), "block_height": obj.get("block_height"), - "timestamp": obj.get("timestamp") + "timestamp": obj.get("timestamp"), + "created_at": obj.get("created_at"), + "updated_at": obj.get("updated_at"), + "transaction_time": obj.get("transaction_time") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/order_book.py b/lighter/models/order_book.py index 4cbdb56..c269137 100644 --- a/lighter/models/order_book.py +++ b/lighter/models/order_book.py @@ -28,23 +28,34 @@ class OrderBook(BaseModel): """ # noqa: E501 symbol: StrictStr market_id: StrictInt + market_type: StrictStr + base_asset_id: StrictInt + quote_asset_id: StrictInt status: StrictStr taker_fee: StrictStr maker_fee: StrictStr liquidation_fee: StrictStr min_base_amount: StrictStr min_quote_amount: StrictStr + order_quote_limit: StrictStr supported_size_decimals: StrictInt supported_price_decimals: StrictInt supported_quote_decimals: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["symbol", "market_id", "status", "taker_fee", "maker_fee", "liquidation_fee", "min_base_amount", "min_quote_amount", "supported_size_decimals", "supported_price_decimals", "supported_quote_decimals"] + __properties: ClassVar[List[str]] = ["symbol", "market_id", "market_type", "base_asset_id", "quote_asset_id", "status", "taker_fee", "maker_fee", "liquidation_fee", "min_base_amount", "min_quote_amount", "order_quote_limit", "supported_size_decimals", "supported_price_decimals", "supported_quote_decimals"] + + @field_validator('market_type') + def market_type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['perp', 'spot']): + raise ValueError("must be one of enum values ('perp', 'spot')") + return value @field_validator('status') def status_validate_enum(cls, value): """Validates the enum""" - if value not in set(['inactive', 'frozen', 'active']): - raise ValueError("must be one of enum values ('inactive', 'frozen', 'active')") + if value not in set(['inactive', 'active']): + raise ValueError("must be one of enum values ('inactive', 'active')") return value model_config = ConfigDict( @@ -104,15 +115,19 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "symbol": obj.get("symbol"), "market_id": obj.get("market_id"), + "market_type": obj.get("market_type"), + "base_asset_id": obj.get("base_asset_id"), + "quote_asset_id": obj.get("quote_asset_id"), "status": obj.get("status"), "taker_fee": obj.get("taker_fee"), "maker_fee": obj.get("maker_fee"), "liquidation_fee": obj.get("liquidation_fee"), "min_base_amount": obj.get("min_base_amount"), "min_quote_amount": obj.get("min_quote_amount"), + "order_quote_limit": obj.get("order_quote_limit"), "supported_size_decimals": obj.get("supported_size_decimals"), "supported_price_decimals": obj.get("supported_price_decimals"), "supported_quote_decimals": obj.get("supported_quote_decimals") diff --git a/lighter/models/order_book_depth.py b/lighter/models/order_book_depth.py index 214d798..485558a 100644 --- a/lighter/models/order_book_depth.py +++ b/lighter/models/order_book_depth.py @@ -32,8 +32,9 @@ class OrderBookDepth(BaseModel): asks: List[PriceLevel] bids: List[PriceLevel] offset: StrictInt + nonce: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "asks", "bids", "offset"] + __properties: ClassVar[List[str]] = ["code", "message", "asks", "bids", "offset", "nonce"] model_config = ConfigDict( populate_by_name=True, @@ -106,12 +107,13 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "asks": [PriceLevel.from_dict(_item) for _item in obj["asks"]] if obj.get("asks") is not None else None, "bids": [PriceLevel.from_dict(_item) for _item in obj["bids"]] if obj.get("bids") is not None else None, - "offset": obj.get("offset") + "offset": obj.get("offset"), + "nonce": obj.get("nonce") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/order_book_depth_with_begin_nonce.py b/lighter/models/order_book_depth_with_begin_nonce.py new file mode 100644 index 0000000..641ab10 --- /dev/null +++ b/lighter/models/order_book_depth_with_begin_nonce.py @@ -0,0 +1,123 @@ +# coding: utf-8 + +""" + + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictInt +from typing import Any, ClassVar, Dict, List +from lighter.models.price_level import PriceLevel +from typing import Optional, Set +from typing_extensions import Self + +class OrderBookDepthWithBeginNonce(BaseModel): + """ + OrderBookDepthWithBeginNonce + """ # noqa: E501 + asks: List[PriceLevel] + bids: List[PriceLevel] + offset: StrictInt + nonce: StrictInt + begin_nonce: StrictInt + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["asks", "bids", "offset", "nonce", "begin_nonce"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of OrderBookDepthWithBeginNonce from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in asks (list) + _items = [] + if self.asks: + for _item in self.asks: + if _item: + _items.append(_item.to_dict()) + _dict['asks'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in bids (list) + _items = [] + if self.bids: + for _item in self.bids: + if _item: + _items.append(_item.to_dict()) + _dict['bids'] = _items + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of OrderBookDepthWithBeginNonce from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_construct(**{ + "asks": [PriceLevel.from_dict(_item) for _item in obj["asks"]] if obj.get("asks") is not None else None, + "bids": [PriceLevel.from_dict(_item) for _item in obj["bids"]] if obj.get("bids") is not None else None, + "offset": obj.get("offset"), + "nonce": obj.get("nonce"), + "begin_nonce": obj.get("begin_nonce") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/lighter/models/order_book_details.py b/lighter/models/order_book_details.py index a67276f..6daf960 100644 --- a/lighter/models/order_book_details.py +++ b/lighter/models/order_book_details.py @@ -19,7 +19,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from lighter.models.order_book_detail import OrderBookDetail +from lighter.models.perps_order_book_detail import PerpsOrderBookDetail +from lighter.models.spot_order_book_detail import SpotOrderBookDetail from typing import Optional, Set from typing_extensions import Self @@ -29,9 +30,10 @@ class OrderBookDetails(BaseModel): """ # noqa: E501 code: StrictInt message: Optional[StrictStr] = None - order_book_details: List[OrderBookDetail] + order_book_details: List[PerpsOrderBookDetail] + spot_order_book_details: List[SpotOrderBookDetail] additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "order_book_details"] + __properties: ClassVar[List[str]] = ["code", "message", "order_book_details", "spot_order_book_details"] model_config = ConfigDict( populate_by_name=True, @@ -81,6 +83,13 @@ def to_dict(self) -> Dict[str, Any]: if _item: _items.append(_item.to_dict()) _dict['order_book_details'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in spot_order_book_details (list) + _items = [] + if self.spot_order_book_details: + for _item in self.spot_order_book_details: + if _item: + _items.append(_item.to_dict()) + _dict['spot_order_book_details'] = _items # puts key-value pairs in additional_properties in the top level if self.additional_properties is not None: for _key, _value in self.additional_properties.items(): @@ -97,10 +106,11 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), - "order_book_details": [OrderBookDetail.from_dict(_item) for _item in obj["order_book_details"]] if obj.get("order_book_details") is not None else None + "order_book_details": [PerpsOrderBookDetail.from_dict(_item) for _item in obj["order_book_details"]] if obj.get("order_book_details") is not None else None, + "spot_order_book_details": [SpotOrderBookDetail.from_dict(_item) for _item in obj["spot_order_book_details"]] if obj.get("spot_order_book_details") is not None else None }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/order_book_orders.py b/lighter/models/order_book_orders.py index 549d79c..1e69164 100644 --- a/lighter/models/order_book_orders.py +++ b/lighter/models/order_book_orders.py @@ -107,7 +107,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "total_asks": obj.get("total_asks"), diff --git a/lighter/models/order_book_stats.py b/lighter/models/order_book_stats.py index 5f09676..8719552 100644 --- a/lighter/models/order_book_stats.py +++ b/lighter/models/order_book_stats.py @@ -92,7 +92,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "symbol": obj.get("symbol"), "last_trade_price": obj.get("last_trade_price"), "daily_trades_count": obj.get("daily_trades_count"), diff --git a/lighter/models/order_books.py b/lighter/models/order_books.py index f7cc8e8..f94a315 100644 --- a/lighter/models/order_books.py +++ b/lighter/models/order_books.py @@ -97,7 +97,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "order_books": [OrderBook.from_dict(_item) for _item in obj["order_books"]] if obj.get("order_books") is not None else None diff --git a/lighter/models/orders.py b/lighter/models/orders.py index b494259..788b2c5 100644 --- a/lighter/models/orders.py +++ b/lighter/models/orders.py @@ -98,7 +98,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "next_cursor": obj.get("next_cursor"), diff --git a/lighter/models/market_info.py b/lighter/models/perps_market_stats.py similarity index 80% rename from lighter/models/market_info.py rename to lighter/models/perps_market_stats.py index c836971..d28434f 100644 --- a/lighter/models/market_info.py +++ b/lighter/models/perps_market_stats.py @@ -22,14 +22,18 @@ from typing import Optional, Set from typing_extensions import Self -class MarketInfo(BaseModel): +class PerpsMarketStats(BaseModel): """ - MarketInfo + PerpsMarketStats """ # noqa: E501 + symbol: StrictStr market_id: StrictInt index_price: StrictStr mark_price: StrictStr open_interest: StrictStr + open_interest_limit: StrictStr + funding_clamp_small: StrictStr + funding_clamp_big: StrictStr last_trade_price: StrictStr current_funding_rate: StrictStr funding_rate: StrictStr @@ -40,7 +44,7 @@ class MarketInfo(BaseModel): daily_price_high: Union[StrictFloat, StrictInt] daily_price_change: Union[StrictFloat, StrictInt] additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["market_id", "index_price", "mark_price", "open_interest", "last_trade_price", "current_funding_rate", "funding_rate", "funding_timestamp", "daily_base_token_volume", "daily_quote_token_volume", "daily_price_low", "daily_price_high", "daily_price_change"] + __properties: ClassVar[List[str]] = ["symbol", "market_id", "index_price", "mark_price", "open_interest", "open_interest_limit", "funding_clamp_small", "funding_clamp_big", "last_trade_price", "current_funding_rate", "funding_rate", "funding_timestamp", "daily_base_token_volume", "daily_quote_token_volume", "daily_price_low", "daily_price_high", "daily_price_change"] model_config = ConfigDict( populate_by_name=True, @@ -60,7 +64,7 @@ def to_json(self) -> str: @classmethod def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MarketInfo from a JSON string""" + """Create an instance of PerpsMarketStats from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -92,18 +96,22 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MarketInfo from a dict""" + """Create an instance of PerpsMarketStats from a dict""" if obj is None: return None if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ + "symbol": obj.get("symbol"), "market_id": obj.get("market_id"), "index_price": obj.get("index_price"), "mark_price": obj.get("mark_price"), "open_interest": obj.get("open_interest"), + "open_interest_limit": obj.get("open_interest_limit"), + "funding_clamp_small": obj.get("funding_clamp_small"), + "funding_clamp_big": obj.get("funding_clamp_big"), "last_trade_price": obj.get("last_trade_price"), "current_funding_rate": obj.get("current_funding_rate"), "funding_rate": obj.get("funding_rate"), diff --git a/lighter/models/perps_order_book_detail.py b/lighter/models/perps_order_book_detail.py new file mode 100644 index 0000000..46f1c77 --- /dev/null +++ b/lighter/models/perps_order_book_detail.py @@ -0,0 +1,180 @@ +# coding: utf-8 + +""" + + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictFloat, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Union +from lighter.models.market_config import MarketConfig +from typing import Optional, Set +from typing_extensions import Self + +class PerpsOrderBookDetail(BaseModel): + """ + PerpsOrderBookDetail + """ # noqa: E501 + symbol: StrictStr + market_id: StrictInt + market_type: StrictStr + base_asset_id: StrictInt + quote_asset_id: StrictInt + status: StrictStr + taker_fee: StrictStr + maker_fee: StrictStr + liquidation_fee: StrictStr + min_base_amount: StrictStr + min_quote_amount: StrictStr + order_quote_limit: StrictStr + supported_size_decimals: StrictInt + supported_price_decimals: StrictInt + supported_quote_decimals: StrictInt + size_decimals: StrictInt + price_decimals: StrictInt + quote_multiplier: StrictInt + default_initial_margin_fraction: StrictInt + min_initial_margin_fraction: StrictInt + maintenance_margin_fraction: StrictInt + closeout_margin_fraction: StrictInt + last_trade_price: Union[StrictFloat, StrictInt] + daily_trades_count: StrictInt + daily_base_token_volume: Union[StrictFloat, StrictInt] + daily_quote_token_volume: Union[StrictFloat, StrictInt] + daily_price_low: Union[StrictFloat, StrictInt] + daily_price_high: Union[StrictFloat, StrictInt] + daily_price_change: Union[StrictFloat, StrictInt] + open_interest: Union[StrictFloat, StrictInt] + daily_chart: Dict[str, Union[StrictFloat, StrictInt]] + market_config: MarketConfig + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["symbol", "market_id", "market_type", "base_asset_id", "quote_asset_id", "status", "taker_fee", "maker_fee", "liquidation_fee", "min_base_amount", "min_quote_amount", "order_quote_limit", "supported_size_decimals", "supported_price_decimals", "supported_quote_decimals", "size_decimals", "price_decimals", "quote_multiplier", "default_initial_margin_fraction", "min_initial_margin_fraction", "maintenance_margin_fraction", "closeout_margin_fraction", "last_trade_price", "daily_trades_count", "daily_base_token_volume", "daily_quote_token_volume", "daily_price_low", "daily_price_high", "daily_price_change", "open_interest", "daily_chart", "market_config"] + + @field_validator('market_type') + def market_type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['perp', 'spot']): + raise ValueError("must be one of enum values ('perp', 'spot')") + return value + + @field_validator('status') + def status_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['inactive', 'active']): + raise ValueError("must be one of enum values ('inactive', 'active')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PerpsOrderBookDetail from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of market_config + if self.market_config: + _dict['market_config'] = self.market_config.to_dict() + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PerpsOrderBookDetail from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_construct(**{ + "symbol": obj.get("symbol"), + "market_id": obj.get("market_id"), + "market_type": obj.get("market_type"), + "base_asset_id": obj.get("base_asset_id"), + "quote_asset_id": obj.get("quote_asset_id"), + "status": obj.get("status"), + "taker_fee": obj.get("taker_fee"), + "maker_fee": obj.get("maker_fee"), + "liquidation_fee": obj.get("liquidation_fee"), + "min_base_amount": obj.get("min_base_amount"), + "min_quote_amount": obj.get("min_quote_amount"), + "order_quote_limit": obj.get("order_quote_limit"), + "supported_size_decimals": obj.get("supported_size_decimals"), + "supported_price_decimals": obj.get("supported_price_decimals"), + "supported_quote_decimals": obj.get("supported_quote_decimals"), + "size_decimals": obj.get("size_decimals"), + "price_decimals": obj.get("price_decimals"), + "quote_multiplier": obj.get("quote_multiplier"), + "default_initial_margin_fraction": obj.get("default_initial_margin_fraction"), + "min_initial_margin_fraction": obj.get("min_initial_margin_fraction"), + "maintenance_margin_fraction": obj.get("maintenance_margin_fraction"), + "closeout_margin_fraction": obj.get("closeout_margin_fraction"), + "last_trade_price": obj.get("last_trade_price"), + "daily_trades_count": obj.get("daily_trades_count"), + "daily_base_token_volume": obj.get("daily_base_token_volume"), + "daily_quote_token_volume": obj.get("daily_quote_token_volume"), + "daily_price_low": obj.get("daily_price_low"), + "daily_price_high": obj.get("daily_price_high"), + "daily_price_change": obj.get("daily_price_change"), + "open_interest": obj.get("open_interest"), + "daily_chart": obj.get("daily_chart"), + "market_config": MarketConfig.from_dict(obj["market_config"]) if obj.get("market_config") is not None else None + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/lighter/models/pn_l_entry.py b/lighter/models/pn_l_entry.py index 5bedea7..1b09378 100644 --- a/lighter/models/pn_l_entry.py +++ b/lighter/models/pn_l_entry.py @@ -28,14 +28,17 @@ class PnLEntry(BaseModel): """ # noqa: E501 timestamp: StrictInt trade_pnl: Union[StrictFloat, StrictInt] + trade_spot_pnl: Union[StrictFloat, StrictInt] inflow: Union[StrictFloat, StrictInt] outflow: Union[StrictFloat, StrictInt] + spot_outflow: Union[StrictFloat, StrictInt] + spot_inflow: Union[StrictFloat, StrictInt] pool_pnl: Union[StrictFloat, StrictInt] pool_inflow: Union[StrictFloat, StrictInt] pool_outflow: Union[StrictFloat, StrictInt] pool_total_shares: Union[StrictFloat, StrictInt] additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["timestamp", "trade_pnl", "inflow", "outflow", "pool_pnl", "pool_inflow", "pool_outflow", "pool_total_shares"] + __properties: ClassVar[List[str]] = ["timestamp", "trade_pnl", "trade_spot_pnl", "inflow", "outflow", "spot_outflow", "spot_inflow", "pool_pnl", "pool_inflow", "pool_outflow", "pool_total_shares"] model_config = ConfigDict( populate_by_name=True, @@ -94,11 +97,14 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "timestamp": obj.get("timestamp"), "trade_pnl": obj.get("trade_pnl"), + "trade_spot_pnl": obj.get("trade_spot_pnl"), "inflow": obj.get("inflow"), "outflow": obj.get("outflow"), + "spot_outflow": obj.get("spot_outflow"), + "spot_inflow": obj.get("spot_inflow"), "pool_pnl": obj.get("pool_pnl"), "pool_inflow": obj.get("pool_inflow"), "pool_outflow": obj.get("pool_outflow"), diff --git a/lighter/models/position_funding.py b/lighter/models/position_funding.py index 1fee27f..7fe8093 100644 --- a/lighter/models/position_funding.py +++ b/lighter/models/position_funding.py @@ -100,7 +100,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "timestamp": obj.get("timestamp"), "market_id": obj.get("market_id"), "funding_id": obj.get("funding_id"), diff --git a/lighter/models/position_fundings.py b/lighter/models/position_fundings.py index fcd8677..c5b603e 100644 --- a/lighter/models/position_fundings.py +++ b/lighter/models/position_fundings.py @@ -98,7 +98,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "position_fundings": [PositionFunding.from_dict(_item) for _item in obj["position_fundings"]] if obj.get("position_fundings") is not None else None, diff --git a/lighter/models/price_level.py b/lighter/models/price_level.py index dc5b081..188551a 100644 --- a/lighter/models/price_level.py +++ b/lighter/models/price_level.py @@ -88,7 +88,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "price": obj.get("price"), "size": obj.get("size") }) diff --git a/lighter/models/public_pool.py b/lighter/models/public_pool.py deleted file mode 100644 index 5d9b61a..0000000 --- a/lighter/models/public_pool.py +++ /dev/null @@ -1,148 +0,0 @@ -# coding: utf-8 - -""" - - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - -from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr -from typing import Any, ClassVar, Dict, List, Optional -from lighter.models.public_pool_info import PublicPoolInfo -from lighter.models.public_pool_share import PublicPoolShare -from typing import Optional, Set -from typing_extensions import Self - -class PublicPool(BaseModel): - """ - PublicPool - """ # noqa: E501 - code: StrictInt - message: Optional[StrictStr] = None - account_type: StrictInt - index: StrictInt - l1_address: StrictStr - cancel_all_time: StrictInt - total_order_count: StrictInt - total_isolated_order_count: StrictInt - pending_order_count: StrictInt - available_balance: StrictStr - status: StrictInt - collateral: StrictStr - account_index: StrictInt - name: StrictStr - description: StrictStr - can_invite: StrictBool = Field(description=" Remove After FE uses L1 meta endpoint") - referral_points_percentage: StrictStr = Field(description=" Remove After FE uses L1 meta endpoint") - total_asset_value: StrictStr - cross_asset_value: StrictStr - pool_info: PublicPoolInfo - account_share: Optional[PublicPoolShare] = None - additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "account_type", "index", "l1_address", "cancel_all_time", "total_order_count", "total_isolated_order_count", "pending_order_count", "available_balance", "status", "collateral", "account_index", "name", "description", "can_invite", "referral_points_percentage", "total_asset_value", "cross_asset_value", "pool_info", "account_share"] - - model_config = ConfigDict( - populate_by_name=True, - validate_assignment=True, - protected_namespaces=(), - ) - - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PublicPool from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of pool_info - if self.pool_info: - _dict['pool_info'] = self.pool_info.to_dict() - # override the default output from pydantic by calling `to_dict()` of account_share - if self.account_share: - _dict['account_share'] = self.account_share.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PublicPool from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "code": obj.get("code"), - "message": obj.get("message"), - "account_type": obj.get("account_type"), - "index": obj.get("index"), - "l1_address": obj.get("l1_address"), - "cancel_all_time": obj.get("cancel_all_time"), - "total_order_count": obj.get("total_order_count"), - "total_isolated_order_count": obj.get("total_isolated_order_count"), - "pending_order_count": obj.get("pending_order_count"), - "available_balance": obj.get("available_balance"), - "status": obj.get("status"), - "collateral": obj.get("collateral"), - "account_index": obj.get("account_index"), - "name": obj.get("name"), - "description": obj.get("description"), - "can_invite": obj.get("can_invite"), - "referral_points_percentage": obj.get("referral_points_percentage"), - "total_asset_value": obj.get("total_asset_value"), - "cross_asset_value": obj.get("cross_asset_value"), - "pool_info": PublicPoolInfo.from_dict(obj["pool_info"]) if obj.get("pool_info") is not None else None, - "account_share": PublicPoolShare.from_dict(obj["account_share"]) if obj.get("account_share") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj - - diff --git a/lighter/models/public_pool_info.py b/lighter/models/public_pool_info.py index 7ee99d5..d0c1a0b 100644 --- a/lighter/models/public_pool_info.py +++ b/lighter/models/public_pool_info.py @@ -34,10 +34,11 @@ class PublicPoolInfo(BaseModel): total_shares: StrictInt operator_shares: StrictInt annual_percentage_yield: Union[StrictFloat, StrictInt] + sharpe_ratio: Union[StrictFloat, StrictInt] daily_returns: List[DailyReturn] share_prices: List[SharePrice] additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["status", "operator_fee", "min_operator_share_rate", "total_shares", "operator_shares", "annual_percentage_yield", "daily_returns", "share_prices"] + __properties: ClassVar[List[str]] = ["status", "operator_fee", "min_operator_share_rate", "total_shares", "operator_shares", "annual_percentage_yield", "sharpe_ratio", "daily_returns", "share_prices"] model_config = ConfigDict( populate_by_name=True, @@ -110,13 +111,14 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "status": obj.get("status"), "operator_fee": obj.get("operator_fee"), "min_operator_share_rate": obj.get("min_operator_share_rate"), "total_shares": obj.get("total_shares"), "operator_shares": obj.get("operator_shares"), "annual_percentage_yield": obj.get("annual_percentage_yield"), + "sharpe_ratio": obj.get("sharpe_ratio"), "daily_returns": [DailyReturn.from_dict(_item) for _item in obj["daily_returns"]] if obj.get("daily_returns") is not None else None, "share_prices": [SharePrice.from_dict(_item) for _item in obj["share_prices"]] if obj.get("share_prices") is not None else None }) diff --git a/lighter/models/public_pool_metadata.py b/lighter/models/public_pool_metadata.py index a0c5359..a489118 100644 --- a/lighter/models/public_pool_metadata.py +++ b/lighter/models/public_pool_metadata.py @@ -30,17 +30,20 @@ class PublicPoolMetadata(BaseModel): code: StrictInt message: Optional[StrictStr] = None account_index: StrictInt + created_at: StrictInt + master_account_index: StrictInt account_type: StrictInt name: StrictStr l1_address: StrictStr annual_percentage_yield: Union[StrictFloat, StrictInt] + sharpe_ratio: Union[StrictFloat, StrictInt] status: StrictInt operator_fee: StrictStr total_asset_value: StrictStr total_shares: StrictInt account_share: Optional[PublicPoolShare] = None additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "account_index", "account_type", "name", "l1_address", "annual_percentage_yield", "status", "operator_fee", "total_asset_value", "total_shares", "account_share"] + __properties: ClassVar[List[str]] = ["code", "message", "account_index", "created_at", "master_account_index", "account_type", "name", "l1_address", "annual_percentage_yield", "sharpe_ratio", "status", "operator_fee", "total_asset_value", "total_shares", "account_share"] model_config = ConfigDict( populate_by_name=True, @@ -102,14 +105,17 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "account_index": obj.get("account_index"), + "created_at": obj.get("created_at"), + "master_account_index": obj.get("master_account_index"), "account_type": obj.get("account_type"), "name": obj.get("name"), "l1_address": obj.get("l1_address"), "annual_percentage_yield": obj.get("annual_percentage_yield"), + "sharpe_ratio": obj.get("sharpe_ratio"), "status": obj.get("status"), "operator_fee": obj.get("operator_fee"), "total_asset_value": obj.get("total_asset_value"), diff --git a/lighter/models/public_pool_share.py b/lighter/models/public_pool_share.py index 0261075..6e9b6b4 100644 --- a/lighter/models/public_pool_share.py +++ b/lighter/models/public_pool_share.py @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "public_pool_index": obj.get("public_pool_index"), "shares_amount": obj.get("shares_amount"), "entry_usdc": obj.get("entry_usdc") diff --git a/lighter/models/referral_points.py b/lighter/models/referral_points.py deleted file mode 100644 index ffabae7..0000000 --- a/lighter/models/referral_points.py +++ /dev/null @@ -1,118 +0,0 @@ -# coding: utf-8 - -""" - - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - -from pydantic import BaseModel, ConfigDict, StrictFloat, StrictStr -from typing import Any, ClassVar, Dict, List -from lighter.models.referral_point_entry import ReferralPointEntry -from typing import Optional, Set -from typing_extensions import Self - -class ReferralPoints(BaseModel): - """ - ReferralPoints - """ # noqa: E501 - referrals: List[ReferralPointEntry] - user_total_points: StrictFloat - user_last_week_points: StrictFloat - user_total_referral_reward_points: StrictFloat - user_last_week_referral_reward_points: StrictFloat - reward_point_multiplier: StrictStr - additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["referrals", "user_total_points", "user_last_week_points", "user_total_referral_reward_points", "user_last_week_referral_reward_points", "reward_point_multiplier"] - - model_config = ConfigDict( - populate_by_name=True, - validate_assignment=True, - protected_namespaces=(), - ) - - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ReferralPoints from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in referrals (list) - _items = [] - if self.referrals: - for _item in self.referrals: - if _item: - _items.append(_item.to_dict()) - _dict['referrals'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ReferralPoints from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "referrals": [ReferralPointEntry.from_dict(_item) for _item in obj["referrals"]] if obj.get("referrals") is not None else None, - "user_total_points": obj.get("user_total_points"), - "user_last_week_points": obj.get("user_last_week_points"), - "user_total_referral_reward_points": obj.get("user_total_referral_reward_points"), - "user_last_week_referral_reward_points": obj.get("user_last_week_referral_reward_points"), - "reward_point_multiplier": obj.get("reward_point_multiplier") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj - - diff --git a/lighter/models/referral_point_entry.py b/lighter/models/req_do_faucet.py similarity index 74% rename from lighter/models/referral_point_entry.py rename to lighter/models/req_do_faucet.py index fdce287..16281b1 100644 --- a/lighter/models/referral_point_entry.py +++ b/lighter/models/req_do_faucet.py @@ -17,23 +17,19 @@ import re # noqa: F401 import json -from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr +from pydantic import BaseModel, ConfigDict, StrictBool, StrictStr from typing import Any, ClassVar, Dict, List from typing import Optional, Set from typing_extensions import Self -class ReferralPointEntry(BaseModel): +class ReqDoFaucet(BaseModel): """ - ReferralPointEntry + ReqDoFaucet """ # noqa: E501 l1_address: StrictStr - total_points: StrictInt - week_points: StrictInt - total_reward_points: StrictInt - week_reward_points: StrictInt - reward_point_multiplier: StrictStr + do_l1_transfer: StrictBool additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["l1_address", "total_points", "week_points", "total_reward_points", "week_reward_points", "reward_point_multiplier"] + __properties: ClassVar[List[str]] = ["l1_address", "do_l1_transfer"] model_config = ConfigDict( populate_by_name=True, @@ -53,7 +49,7 @@ def to_json(self) -> str: @classmethod def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ReferralPointEntry from a JSON string""" + """Create an instance of ReqDoFaucet from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -85,20 +81,16 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ReferralPointEntry from a dict""" + """Create an instance of ReqDoFaucet from a dict""" if obj is None: return None if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "l1_address": obj.get("l1_address"), - "total_points": obj.get("total_points"), - "week_points": obj.get("week_points"), - "total_reward_points": obj.get("total_reward_points"), - "week_reward_points": obj.get("week_reward_points"), - "reward_point_multiplier": obj.get("reward_point_multiplier") + "do_l1_transfer": obj.get("do_l1_transfer") if obj.get("do_l1_transfer") is not None else False }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/req_export_data.py b/lighter/models/req_export_data.py index d82b64e..96233de 100644 --- a/lighter/models/req_export_data.py +++ b/lighter/models/req_export_data.py @@ -17,7 +17,7 @@ import re # noqa: F401 import json -from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr, field_validator +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set from typing_extensions import Self @@ -26,7 +26,7 @@ class ReqExportData(BaseModel): """ ReqExportData """ # noqa: E501 - auth: Optional[StrictStr] = None + auth: Optional[StrictStr] = Field(default=None, description=" made optional to support header auth clients") account_index: Optional[StrictInt] = -1 market_id: Optional[StrictInt] = None type: StrictStr @@ -97,7 +97,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "auth": obj.get("auth"), "account_index": obj.get("account_index") if obj.get("account_index") is not None else -1, "market_id": obj.get("market_id"), diff --git a/lighter/models/req_get_account.py b/lighter/models/req_get_account.py index c6108e6..bc688c1 100644 --- a/lighter/models/req_get_account.py +++ b/lighter/models/req_get_account.py @@ -95,7 +95,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "by": obj.get("by"), "value": obj.get("value") }) diff --git a/lighter/models/req_get_account_active_orders.py b/lighter/models/req_get_account_active_orders.py index bf3daff..7e976cd 100644 --- a/lighter/models/req_get_account_active_orders.py +++ b/lighter/models/req_get_account_active_orders.py @@ -26,11 +26,11 @@ class ReqGetAccountActiveOrders(BaseModel): """ ReqGetAccountActiveOrders """ # noqa: E501 + auth: Optional[StrictStr] = Field(default=None, description=" made optional to support header auth clients") account_index: StrictInt market_id: StrictInt - auth: Optional[StrictStr] = Field(default=None, description=" made optional to support header auth clients") additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["account_index", "market_id", "auth"] + __properties: ClassVar[List[str]] = ["auth", "account_index", "market_id"] model_config = ConfigDict( populate_by_name=True, @@ -89,10 +89,10 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ + "auth": obj.get("auth"), "account_index": obj.get("account_index"), - "market_id": obj.get("market_id"), - "auth": obj.get("auth") + "market_id": obj.get("market_id") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/req_get_account_api_keys.py b/lighter/models/req_get_account_api_keys.py index 2a395ad..ce423e3 100644 --- a/lighter/models/req_get_account_api_keys.py +++ b/lighter/models/req_get_account_api_keys.py @@ -88,7 +88,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "account_index": obj.get("account_index"), "api_key_index": obj.get("api_key_index") }) diff --git a/lighter/models/req_get_account_by_l1_address.py b/lighter/models/req_get_account_by_l1_address.py index a0b86eb..d5bda53 100644 --- a/lighter/models/req_get_account_by_l1_address.py +++ b/lighter/models/req_get_account_by_l1_address.py @@ -87,7 +87,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "l1_address": obj.get("l1_address") }) # store additional fields in additional_properties diff --git a/lighter/models/req_get_account_inactive_orders.py b/lighter/models/req_get_account_inactive_orders.py index 9ea9b18..6ab3288 100644 --- a/lighter/models/req_get_account_inactive_orders.py +++ b/lighter/models/req_get_account_inactive_orders.py @@ -94,7 +94,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "auth": obj.get("auth"), "account_index": obj.get("account_index"), "market_id": obj.get("market_id"), diff --git a/lighter/models/req_get_account_limits.py b/lighter/models/req_get_account_limits.py index 206f876..eb483ac 100644 --- a/lighter/models/req_get_account_limits.py +++ b/lighter/models/req_get_account_limits.py @@ -88,7 +88,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "account_index": obj.get("account_index"), "auth": obj.get("auth") }) diff --git a/lighter/models/req_get_account_metadata.py b/lighter/models/req_get_account_metadata.py index 4403e9d..b20a60d 100644 --- a/lighter/models/req_get_account_metadata.py +++ b/lighter/models/req_get_account_metadata.py @@ -96,7 +96,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "by": obj.get("by"), "value": obj.get("value"), "auth": obj.get("auth") diff --git a/lighter/models/req_get_account_pn_l.py b/lighter/models/req_get_account_pn_l.py index 034022c..ed47aa4 100644 --- a/lighter/models/req_get_account_pn_l.py +++ b/lighter/models/req_get_account_pn_l.py @@ -27,7 +27,7 @@ class ReqGetAccountPnL(BaseModel): """ ReqGetAccountPnL """ # noqa: E501 - auth: Optional[StrictStr] = None + auth: Optional[StrictStr] = Field(default=None, description=" made optional to support header auth clients") by: StrictStr value: StrictStr resolution: StrictStr @@ -109,7 +109,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "auth": obj.get("auth"), "by": obj.get("by"), "value": obj.get("value"), diff --git a/lighter/models/req_get_account_txs.py b/lighter/models/req_get_account_txs.py index 6c785f6..e9fa53f 100644 --- a/lighter/models/req_get_account_txs.py +++ b/lighter/models/req_get_account_txs.py @@ -31,10 +31,10 @@ class ReqGetAccountTxs(BaseModel): limit: Optional[Annotated[int, Field(le=100, strict=True, ge=1)]] = None by: Optional[StrictStr] = None value: Optional[StrictStr] = None + auth: Optional[StrictStr] = Field(default=None, description=" made optional to support header auth clients") types: Optional[List[StrictInt]] = None - auth: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["index", "limit", "by", "value", "types", "auth"] + __properties: ClassVar[List[str]] = ["index", "limit", "by", "value", "auth", "types"] @field_validator('by') def by_validate_enum(cls, value): @@ -103,13 +103,13 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "index": obj.get("index"), "limit": obj.get("limit"), "by": obj.get("by"), "value": obj.get("value"), - "types": obj.get("types"), - "auth": obj.get("auth") + "auth": obj.get("auth"), + "types": obj.get("types") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/req_get_referral_points.py b/lighter/models/req_get_api_tokens.py similarity index 82% rename from lighter/models/req_get_referral_points.py rename to lighter/models/req_get_api_tokens.py index 19192ec..e0de034 100644 --- a/lighter/models/req_get_referral_points.py +++ b/lighter/models/req_get_api_tokens.py @@ -17,19 +17,18 @@ import re # noqa: F401 import json -from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr -from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, ConfigDict, StrictInt +from typing import Any, ClassVar, Dict, List from typing import Optional, Set from typing_extensions import Self -class ReqGetReferralPoints(BaseModel): +class ReqGetApiTokens(BaseModel): """ - ReqGetReferralPoints + ReqGetApiTokens """ # noqa: E501 - auth: Optional[StrictStr] = Field(default=None, description=" made optional to support header auth clients") account_index: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["auth", "account_index"] + __properties: ClassVar[List[str]] = ["account_index"] model_config = ConfigDict( populate_by_name=True, @@ -49,7 +48,7 @@ def to_json(self) -> str: @classmethod def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ReqGetReferralPoints from a JSON string""" + """Create an instance of ReqGetApiTokens from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -81,15 +80,14 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ReqGetReferralPoints from a dict""" + """Create an instance of ReqGetApiTokens from a dict""" if obj is None: return None if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ - "auth": obj.get("auth"), + _obj = cls.model_construct(**{ "account_index": obj.get("account_index") }) # store additional fields in additional_properties diff --git a/lighter/models/req_get_asset_details.py b/lighter/models/req_get_asset_details.py new file mode 100644 index 0000000..93dae58 --- /dev/null +++ b/lighter/models/req_get_asset_details.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class ReqGetAssetDetails(BaseModel): + """ + ReqGetAssetDetails + """ # noqa: E501 + asset_id: Optional[StrictInt] = None + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["asset_id"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ReqGetAssetDetails from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ReqGetAssetDetails from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_construct(**{ + "asset_id": obj.get("asset_id") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/lighter/models/req_get_block.py b/lighter/models/req_get_block.py index 574e2c7..d0fe811 100644 --- a/lighter/models/req_get_block.py +++ b/lighter/models/req_get_block.py @@ -95,7 +95,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "by": obj.get("by"), "value": obj.get("value") }) diff --git a/lighter/models/req_get_block_txs.py b/lighter/models/req_get_block_txs.py index b040c5e..6a3aa66 100644 --- a/lighter/models/req_get_block_txs.py +++ b/lighter/models/req_get_block_txs.py @@ -95,7 +95,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "by": obj.get("by"), "value": obj.get("value") }) diff --git a/lighter/models/req_get_bridges_by_l1_addr.py b/lighter/models/req_get_bridges_by_l1_addr.py new file mode 100644 index 0000000..6ba63fe --- /dev/null +++ b/lighter/models/req_get_bridges_by_l1_addr.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class ReqGetBridgesByL1Addr(BaseModel): + """ + ReqGetBridgesByL1Addr + """ # noqa: E501 + l1_address: StrictStr + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["l1_address"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ReqGetBridgesByL1Addr from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ReqGetBridgesByL1Addr from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_construct(**{ + "l1_address": obj.get("l1_address") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/lighter/models/req_get_by_account.py b/lighter/models/req_get_by_account.py index 9e52c14..85557cf 100644 --- a/lighter/models/req_get_by_account.py +++ b/lighter/models/req_get_by_account.py @@ -95,7 +95,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "by": obj.get("by"), "value": obj.get("value") }) diff --git a/lighter/models/req_get_candlesticks.py b/lighter/models/req_get_candles.py similarity index 91% rename from lighter/models/req_get_candlesticks.py rename to lighter/models/req_get_candles.py index 0fc9642..8814c7e 100644 --- a/lighter/models/req_get_candlesticks.py +++ b/lighter/models/req_get_candles.py @@ -23,9 +23,9 @@ from typing import Optional, Set from typing_extensions import Self -class ReqGetCandlesticks(BaseModel): +class ReqGetCandles(BaseModel): """ - ReqGetCandlesticks + ReqGetCandles """ # noqa: E501 market_id: StrictInt resolution: StrictStr @@ -39,8 +39,8 @@ class ReqGetCandlesticks(BaseModel): @field_validator('resolution') def resolution_validate_enum(cls, value): """Validates the enum""" - if value not in set(['1m', '5m', '15m', '1h', '4h', '1d']): - raise ValueError("must be one of enum values ('1m', '5m', '15m', '1h', '4h', '1d')") + if value not in set(['1m', '5m', '15m', '30m', '1h', '4h', '12h', '1d', '1w']): + raise ValueError("must be one of enum values ('1m', '5m', '15m', '30m', '1h', '4h', '12h', '1d', '1w')") return value model_config = ConfigDict( @@ -61,7 +61,7 @@ def to_json(self) -> str: @classmethod def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ReqGetCandlesticks from a JSON string""" + """Create an instance of ReqGetCandles from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -93,14 +93,14 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ReqGetCandlesticks from a dict""" + """Create an instance of ReqGetCandles from a dict""" if obj is None: return None if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "market_id": obj.get("market_id"), "resolution": obj.get("resolution"), "start_timestamp": obj.get("start_timestamp"), diff --git a/lighter/models/req_get_deposit_history.py b/lighter/models/req_get_deposit_history.py index b51846c..c090e2f 100644 --- a/lighter/models/req_get_deposit_history.py +++ b/lighter/models/req_get_deposit_history.py @@ -26,13 +26,13 @@ class ReqGetDepositHistory(BaseModel): """ ReqGetDepositHistory """ # noqa: E501 - account_index: StrictInt auth: Optional[StrictStr] = Field(default=None, description=" made optional to support header auth clients") + account_index: StrictInt l1_address: StrictStr cursor: Optional[StrictStr] = None filter: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["account_index", "auth", "l1_address", "cursor", "filter"] + __properties: ClassVar[List[str]] = ["auth", "account_index", "l1_address", "cursor", "filter"] @field_validator('filter') def filter_validate_enum(cls, value): @@ -101,9 +101,9 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ - "account_index": obj.get("account_index"), + _obj = cls.model_construct(**{ "auth": obj.get("auth"), + "account_index": obj.get("account_index"), "l1_address": obj.get("l1_address"), "cursor": obj.get("cursor"), "filter": obj.get("filter") diff --git a/lighter/models/req_get_fast_withdraw_info.py b/lighter/models/req_get_fast_withdraw_info.py index bced0a8..401af0a 100644 --- a/lighter/models/req_get_fast_withdraw_info.py +++ b/lighter/models/req_get_fast_withdraw_info.py @@ -26,10 +26,10 @@ class ReqGetFastWithdrawInfo(BaseModel): """ ReqGetFastWithdrawInfo """ # noqa: E501 - account_index: StrictInt auth: Optional[StrictStr] = Field(default=None, description=" made optional to support header auth clients") + account_index: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["account_index", "auth"] + __properties: ClassVar[List[str]] = ["auth", "account_index"] model_config = ConfigDict( populate_by_name=True, @@ -88,9 +88,9 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ - "account_index": obj.get("account_index"), - "auth": obj.get("auth") + _obj = cls.model_construct(**{ + "auth": obj.get("auth"), + "account_index": obj.get("account_index") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/req_get_fundings.py b/lighter/models/req_get_fundings.py index d2fe9a5..d879d47 100644 --- a/lighter/models/req_get_fundings.py +++ b/lighter/models/req_get_fundings.py @@ -99,7 +99,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "market_id": obj.get("market_id"), "resolution": obj.get("resolution"), "start_timestamp": obj.get("start_timestamp"), diff --git a/lighter/models/req_get_l1_metadata.py b/lighter/models/req_get_l1_metadata.py index 0ce494a..5ee9d19 100644 --- a/lighter/models/req_get_l1_metadata.py +++ b/lighter/models/req_get_l1_metadata.py @@ -88,7 +88,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "auth": obj.get("auth"), "l1_address": obj.get("l1_address") }) diff --git a/lighter/models/req_get_l1_tx.py b/lighter/models/req_get_l1_tx.py index dda8501..02f7f87 100644 --- a/lighter/models/req_get_l1_tx.py +++ b/lighter/models/req_get_l1_tx.py @@ -87,7 +87,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "hash": obj.get("hash") }) # store additional fields in additional_properties diff --git a/lighter/models/req_get_latest_deposit.py b/lighter/models/req_get_latest_deposit.py index 6ce2506..7bd652d 100644 --- a/lighter/models/req_get_latest_deposit.py +++ b/lighter/models/req_get_latest_deposit.py @@ -87,7 +87,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "l1_address": obj.get("l1_address") }) # store additional fields in additional_properties diff --git a/lighter/models/req_get_liquidation_infos.py b/lighter/models/req_get_liquidation_infos.py index 16701b7..aa7f818 100644 --- a/lighter/models/req_get_liquidation_infos.py +++ b/lighter/models/req_get_liquidation_infos.py @@ -92,7 +92,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "auth": obj.get("auth"), "account_index": obj.get("account_index"), "market_id": obj.get("market_id"), diff --git a/lighter/models/req_get_next_nonce.py b/lighter/models/req_get_next_nonce.py index 90920a0..1ae8fbc 100644 --- a/lighter/models/req_get_next_nonce.py +++ b/lighter/models/req_get_next_nonce.py @@ -88,7 +88,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "account_index": obj.get("account_index"), "api_key_index": obj.get("api_key_index") }) diff --git a/lighter/models/req_get_order_book_details.py b/lighter/models/req_get_order_book_details.py index e38a012..50dd1d0 100644 --- a/lighter/models/req_get_order_book_details.py +++ b/lighter/models/req_get_order_book_details.py @@ -17,7 +17,7 @@ import re # noqa: F401 import json -from pydantic import BaseModel, ConfigDict, StrictInt +from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set from typing_extensions import Self @@ -27,8 +27,19 @@ class ReqGetOrderBookDetails(BaseModel): ReqGetOrderBookDetails """ # noqa: E501 market_id: Optional[StrictInt] = None + filter: Optional[StrictStr] = 'all' additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["market_id"] + __properties: ClassVar[List[str]] = ["market_id", "filter"] + + @field_validator('filter') + def filter_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['all', 'spot', 'perp']): + raise ValueError("must be one of enum values ('all', 'spot', 'perp')") + return value model_config = ConfigDict( populate_by_name=True, @@ -87,8 +98,9 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ - "market_id": obj.get("market_id") + _obj = cls.model_construct(**{ + "market_id": obj.get("market_id"), + "filter": obj.get("filter") if obj.get("filter") is not None else 'all' }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/req_get_order_book_orders.py b/lighter/models/req_get_order_book_orders.py index 52c008f..4e72111 100644 --- a/lighter/models/req_get_order_book_orders.py +++ b/lighter/models/req_get_order_book_orders.py @@ -28,7 +28,7 @@ class ReqGetOrderBookOrders(BaseModel): ReqGetOrderBookOrders """ # noqa: E501 market_id: StrictInt - limit: Annotated[int, Field(le=100, strict=True, ge=1)] + limit: Annotated[int, Field(le=250, strict=True, ge=1)] additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["market_id", "limit"] @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "market_id": obj.get("market_id"), "limit": obj.get("limit") }) diff --git a/lighter/models/req_get_order_books.py b/lighter/models/req_get_order_books.py index 9608c4b..be80217 100644 --- a/lighter/models/req_get_order_books.py +++ b/lighter/models/req_get_order_books.py @@ -17,7 +17,7 @@ import re # noqa: F401 import json -from pydantic import BaseModel, ConfigDict, StrictInt +from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set from typing_extensions import Self @@ -27,8 +27,19 @@ class ReqGetOrderBooks(BaseModel): ReqGetOrderBooks """ # noqa: E501 market_id: Optional[StrictInt] = None + filter: Optional[StrictStr] = 'all' additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["market_id"] + __properties: ClassVar[List[str]] = ["market_id", "filter"] + + @field_validator('filter') + def filter_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['all', 'spot', 'perp']): + raise ValueError("must be one of enum values ('all', 'spot', 'perp')") + return value model_config = ConfigDict( populate_by_name=True, @@ -87,8 +98,9 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ - "market_id": obj.get("market_id") + _obj = cls.model_construct(**{ + "market_id": obj.get("market_id"), + "filter": obj.get("filter") if obj.get("filter") is not None else 'all' }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/req_get_position_funding.py b/lighter/models/req_get_position_funding.py index 04d07f8..08ab0d9 100644 --- a/lighter/models/req_get_position_funding.py +++ b/lighter/models/req_get_position_funding.py @@ -27,7 +27,7 @@ class ReqGetPositionFunding(BaseModel): """ ReqGetPositionFunding """ # noqa: E501 - auth: Optional[StrictStr] = None + auth: Optional[StrictStr] = Field(default=None, description=" made optional to support header auth clients") account_index: StrictInt market_id: Optional[StrictInt] = None cursor: Optional[StrictStr] = None @@ -103,7 +103,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "auth": obj.get("auth"), "account_index": obj.get("account_index"), "market_id": obj.get("market_id"), diff --git a/lighter/models/req_get_public_pools.py b/lighter/models/req_get_public_pools.py deleted file mode 100644 index 94786e4..0000000 --- a/lighter/models/req_get_public_pools.py +++ /dev/null @@ -1,119 +0,0 @@ -# coding: utf-8 - -""" - - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - -from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator -from typing import Any, ClassVar, Dict, List, Optional -from typing_extensions import Annotated -from typing import Optional, Set -from typing_extensions import Self - -class ReqGetPublicPools(BaseModel): - """ - ReqGetPublicPools - """ # noqa: E501 - auth: Optional[StrictStr] = None - filter: Optional[StrictStr] = None - index: StrictInt - limit: Annotated[int, Field(le=100, strict=True, ge=1)] - account_index: Optional[StrictInt] = None - additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["auth", "filter", "index", "limit", "account_index"] - - @field_validator('filter') - def filter_validate_enum(cls, value): - """Validates the enum""" - if value is None: - return value - - if value not in set(['all', 'user', 'protocol', 'account_index']): - raise ValueError("must be one of enum values ('all', 'user', 'protocol', 'account_index')") - return value - - model_config = ConfigDict( - populate_by_name=True, - validate_assignment=True, - protected_namespaces=(), - ) - - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ReqGetPublicPools from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ReqGetPublicPools from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "auth": obj.get("auth"), - "filter": obj.get("filter"), - "index": obj.get("index"), - "limit": obj.get("limit"), - "account_index": obj.get("account_index") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj - - diff --git a/lighter/models/req_get_public_pools_metadata.py b/lighter/models/req_get_public_pools_metadata.py index ccb7397..9415178 100644 --- a/lighter/models/req_get_public_pools_metadata.py +++ b/lighter/models/req_get_public_pools_metadata.py @@ -27,7 +27,7 @@ class ReqGetPublicPoolsMetadata(BaseModel): """ ReqGetPublicPoolsMetadata """ # noqa: E501 - auth: Optional[StrictStr] = None + auth: Optional[StrictStr] = Field(default=None, description=" made optional to support header auth clients") filter: Optional[StrictStr] = None index: StrictInt limit: Annotated[int, Field(le=100, strict=True, ge=1)] @@ -102,7 +102,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "auth": obj.get("auth"), "filter": obj.get("filter"), "index": obj.get("index"), diff --git a/lighter/models/req_get_range_with_cursor.py b/lighter/models/req_get_range_with_cursor.py index dc7821e..e7ea2e5 100644 --- a/lighter/models/req_get_range_with_cursor.py +++ b/lighter/models/req_get_range_with_cursor.py @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "cursor": obj.get("cursor"), "limit": obj.get("limit") }) diff --git a/lighter/models/req_get_range_with_index.py b/lighter/models/req_get_range_with_index.py index e589449..4e5f7f9 100644 --- a/lighter/models/req_get_range_with_index.py +++ b/lighter/models/req_get_range_with_index.py @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "index": obj.get("index"), "limit": obj.get("limit") }) diff --git a/lighter/models/req_get_range_with_index_sortable.py b/lighter/models/req_get_range_with_index_sortable.py index d22bbb2..920b5bb 100644 --- a/lighter/models/req_get_range_with_index_sortable.py +++ b/lighter/models/req_get_range_with_index_sortable.py @@ -100,7 +100,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "index": obj.get("index"), "limit": obj.get("limit"), "sort": obj.get("sort") if obj.get("sort") is not None else 'asc' diff --git a/lighter/models/req_get_recent_trades.py b/lighter/models/req_get_recent_trades.py index 96dba79..f2f32ba 100644 --- a/lighter/models/req_get_recent_trades.py +++ b/lighter/models/req_get_recent_trades.py @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "market_id": obj.get("market_id"), "limit": obj.get("limit") }) diff --git a/lighter/models/req_get_trades.py b/lighter/models/req_get_trades.py index c760bce..acc205c 100644 --- a/lighter/models/req_get_trades.py +++ b/lighter/models/req_get_trades.py @@ -17,7 +17,7 @@ import re # noqa: F401 import json -from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated from typing import Optional, Set @@ -27,7 +27,7 @@ class ReqGetTrades(BaseModel): """ ReqGetTrades """ # noqa: E501 - auth: Optional[StrictStr] = None + auth: Optional[StrictStr] = Field(default=None, description=" made optional to support header auth clients") market_id: Optional[StrictInt] = None account_index: Optional[StrictInt] = -1 order_index: Optional[StrictInt] = None @@ -36,9 +36,12 @@ class ReqGetTrades(BaseModel): cursor: Optional[StrictStr] = None var_from: Optional[StrictInt] = Field(default=-1, alias="from") ask_filter: Optional[StrictInt] = None + role: Optional[StrictStr] = 'all' + type: Optional[StrictStr] = 'all' limit: Annotated[int, Field(le=100, strict=True, ge=1)] + aggregate: Optional[StrictBool] = False additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["auth", "market_id", "account_index", "order_index", "sort_by", "sort_dir", "cursor", "from", "ask_filter", "limit"] + __properties: ClassVar[List[str]] = ["auth", "market_id", "account_index", "order_index", "sort_by", "sort_dir", "cursor", "from", "ask_filter", "role", "type", "limit", "aggregate"] @field_validator('sort_by') def sort_by_validate_enum(cls, value): @@ -57,6 +60,26 @@ def sort_dir_validate_enum(cls, value): raise ValueError("must be one of enum values ('desc')") return value + @field_validator('role') + def role_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['all', 'maker', 'taker']): + raise ValueError("must be one of enum values ('all', 'maker', 'taker')") + return value + + @field_validator('type') + def type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['all', 'trade', 'liquidation', 'deleverage', 'market-settlement']): + raise ValueError("must be one of enum values ('all', 'trade', 'liquidation', 'deleverage', 'market-settlement')") + return value + model_config = ConfigDict( populate_by_name=True, validate_assignment=True, @@ -114,7 +137,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "auth": obj.get("auth"), "market_id": obj.get("market_id"), "account_index": obj.get("account_index") if obj.get("account_index") is not None else -1, @@ -124,7 +147,10 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: "cursor": obj.get("cursor"), "from": obj.get("from") if obj.get("from") is not None else -1, "ask_filter": obj.get("ask_filter"), - "limit": obj.get("limit") + "role": obj.get("role") if obj.get("role") is not None else 'all', + "type": obj.get("type") if obj.get("type") is not None else 'all', + "limit": obj.get("limit"), + "aggregate": obj.get("aggregate") if obj.get("aggregate") is not None else False }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/req_get_transfer_fee_info.py b/lighter/models/req_get_transfer_fee_info.py index 1d053be..1636b55 100644 --- a/lighter/models/req_get_transfer_fee_info.py +++ b/lighter/models/req_get_transfer_fee_info.py @@ -17,7 +17,7 @@ import re # noqa: F401 import json -from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set from typing_extensions import Self @@ -26,7 +26,7 @@ class ReqGetTransferFeeInfo(BaseModel): """ ReqGetTransferFeeInfo """ # noqa: E501 - auth: Optional[StrictStr] = None + auth: Optional[StrictStr] = Field(default=None, description=" made optional to support header auth clients") account_index: StrictInt to_account_index: Optional[StrictInt] = -1 additional_properties: Dict[str, Any] = {} @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "auth": obj.get("auth"), "account_index": obj.get("account_index"), "to_account_index": obj.get("to_account_index") if obj.get("to_account_index") is not None else -1 diff --git a/lighter/models/req_get_transfer_history.py b/lighter/models/req_get_transfer_history.py index b6b75ba..906242f 100644 --- a/lighter/models/req_get_transfer_history.py +++ b/lighter/models/req_get_transfer_history.py @@ -26,11 +26,11 @@ class ReqGetTransferHistory(BaseModel): """ ReqGetTransferHistory """ # noqa: E501 - account_index: StrictInt auth: Optional[StrictStr] = Field(default=None, description=" made optional to support header auth clients") + account_index: StrictInt cursor: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["account_index", "auth", "cursor"] + __properties: ClassVar[List[str]] = ["auth", "account_index", "cursor"] model_config = ConfigDict( populate_by_name=True, @@ -89,9 +89,9 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ - "account_index": obj.get("account_index"), + _obj = cls.model_construct(**{ "auth": obj.get("auth"), + "account_index": obj.get("account_index"), "cursor": obj.get("cursor") }) # store additional fields in additional_properties diff --git a/lighter/models/req_get_tx.py b/lighter/models/req_get_tx.py index 275c4ff..70706fd 100644 --- a/lighter/models/req_get_tx.py +++ b/lighter/models/req_get_tx.py @@ -95,7 +95,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "by": obj.get("by"), "value": obj.get("value") }) diff --git a/lighter/models/req_get_withdraw_history.py b/lighter/models/req_get_withdraw_history.py index ecd05c7..fc2f730 100644 --- a/lighter/models/req_get_withdraw_history.py +++ b/lighter/models/req_get_withdraw_history.py @@ -26,12 +26,12 @@ class ReqGetWithdrawHistory(BaseModel): """ ReqGetWithdrawHistory """ # noqa: E501 - account_index: StrictInt auth: Optional[StrictStr] = Field(default=None, description=" made optional to support header auth clients") + account_index: StrictInt cursor: Optional[StrictStr] = None filter: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["account_index", "auth", "cursor", "filter"] + __properties: ClassVar[List[str]] = ["auth", "account_index", "cursor", "filter"] @field_validator('filter') def filter_validate_enum(cls, value): @@ -100,9 +100,9 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ - "account_index": obj.get("account_index"), + _obj = cls.model_construct(**{ "auth": obj.get("auth"), + "account_index": obj.get("account_index"), "cursor": obj.get("cursor"), "filter": obj.get("filter") }) diff --git a/lighter/models/resp_change_account_tier.py b/lighter/models/resp_change_account_tier.py index 35b6c15..9e9b797 100644 --- a/lighter/models/resp_change_account_tier.py +++ b/lighter/models/resp_change_account_tier.py @@ -88,7 +88,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message") }) diff --git a/lighter/models/public_pools.py b/lighter/models/resp_get_api_tokens.py similarity index 80% rename from lighter/models/public_pools.py rename to lighter/models/resp_get_api_tokens.py index 1ad4092..7cb52b7 100644 --- a/lighter/models/public_pools.py +++ b/lighter/models/resp_get_api_tokens.py @@ -19,20 +19,19 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from lighter.models.public_pool import PublicPool +from lighter.models.api_token import ApiToken from typing import Optional, Set from typing_extensions import Self -class PublicPools(BaseModel): +class RespGetApiTokens(BaseModel): """ - PublicPools + RespGetApiTokens """ # noqa: E501 code: StrictInt message: Optional[StrictStr] = None - total: StrictInt - public_pools: List[PublicPool] + api_tokens: List[ApiToken] additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "total", "public_pools"] + __properties: ClassVar[List[str]] = ["code", "message", "api_tokens"] model_config = ConfigDict( populate_by_name=True, @@ -52,7 +51,7 @@ def to_json(self) -> str: @classmethod def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PublicPools from a JSON string""" + """Create an instance of RespGetApiTokens from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -75,13 +74,13 @@ def to_dict(self) -> Dict[str, Any]: exclude=excluded_fields, exclude_none=True, ) - # override the default output from pydantic by calling `to_dict()` of each item in public_pools (list) + # override the default output from pydantic by calling `to_dict()` of each item in api_tokens (list) _items = [] - if self.public_pools: - for _item in self.public_pools: + if self.api_tokens: + for _item in self.api_tokens: if _item: _items.append(_item.to_dict()) - _dict['public_pools'] = _items + _dict['api_tokens'] = _items # puts key-value pairs in additional_properties in the top level if self.additional_properties is not None: for _key, _value in self.additional_properties.items(): @@ -91,18 +90,17 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PublicPools from a dict""" + """Create an instance of RespGetApiTokens from a dict""" if obj is None: return None if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), - "total": obj.get("total"), - "public_pools": [PublicPool.from_dict(_item) for _item in obj["public_pools"]] if obj.get("public_pools") is not None else None + "api_tokens": [ApiToken.from_dict(_item) for _item in obj["api_tokens"]] if obj.get("api_tokens") is not None else None }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/blocks.py b/lighter/models/resp_get_bridges_by_l1_addr.py similarity index 82% rename from lighter/models/blocks.py rename to lighter/models/resp_get_bridges_by_l1_addr.py index 2591f16..923f331 100644 --- a/lighter/models/blocks.py +++ b/lighter/models/resp_get_bridges_by_l1_addr.py @@ -19,20 +19,19 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from lighter.models.block import Block +from lighter.models.bridge import Bridge from typing import Optional, Set from typing_extensions import Self -class Blocks(BaseModel): +class RespGetBridgesByL1Addr(BaseModel): """ - Blocks + RespGetBridgesByL1Addr """ # noqa: E501 code: StrictInt message: Optional[StrictStr] = None - total: StrictInt - blocks: List[Block] + bridges: List[Bridge] additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "total", "blocks"] + __properties: ClassVar[List[str]] = ["code", "message", "bridges"] model_config = ConfigDict( populate_by_name=True, @@ -52,7 +51,7 @@ def to_json(self) -> str: @classmethod def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Blocks from a JSON string""" + """Create an instance of RespGetBridgesByL1Addr from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -75,13 +74,13 @@ def to_dict(self) -> Dict[str, Any]: exclude=excluded_fields, exclude_none=True, ) - # override the default output from pydantic by calling `to_dict()` of each item in blocks (list) + # override the default output from pydantic by calling `to_dict()` of each item in bridges (list) _items = [] - if self.blocks: - for _item in self.blocks: + if self.bridges: + for _item in self.bridges: if _item: _items.append(_item.to_dict()) - _dict['blocks'] = _items + _dict['bridges'] = _items # puts key-value pairs in additional_properties in the top level if self.additional_properties is not None: for _key, _value in self.additional_properties.items(): @@ -91,18 +90,17 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Blocks from a dict""" + """Create an instance of RespGetBridgesByL1Addr from a dict""" if obj is None: return None if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), - "total": obj.get("total"), - "blocks": [Block.from_dict(_item) for _item in obj["blocks"]] if obj.get("blocks") is not None else None + "bridges": [Bridge.from_dict(_item) for _item in obj["bridges"]] if obj.get("bridges") is not None else None }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/resp_get_fast_bridge_info.py b/lighter/models/resp_get_fast_bridge_info.py index baf3922..8e38c73 100644 --- a/lighter/models/resp_get_fast_bridge_info.py +++ b/lighter/models/resp_get_fast_bridge_info.py @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "fast_bridge_limit": obj.get("fast_bridge_limit") diff --git a/lighter/models/resp_get_fastwithdrawal_info.py b/lighter/models/resp_get_fastwithdrawal_info.py new file mode 100644 index 0000000..38ece6c --- /dev/null +++ b/lighter/models/resp_get_fastwithdrawal_info.py @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class RespGetFastwithdrawalInfo(BaseModel): + """ + RespGetFastwithdrawalInfo + """ # noqa: E501 + code: StrictInt + message: Optional[StrictStr] = None + to_account_index: StrictInt + withdraw_limit: StrictStr + max_withdrawal_amount: StrictStr + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["code", "message", "to_account_index", "withdraw_limit", "max_withdrawal_amount"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of RespGetFastwithdrawalInfo from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of RespGetFastwithdrawalInfo from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_construct(**{ + "code": obj.get("code"), + "message": obj.get("message"), + "to_account_index": obj.get("to_account_index"), + "withdraw_limit": obj.get("withdraw_limit"), + "max_withdrawal_amount": obj.get("max_withdrawal_amount") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/lighter/models/current_height.py b/lighter/models/resp_get_is_next_bridge_fast.py similarity index 84% rename from lighter/models/current_height.py rename to lighter/models/resp_get_is_next_bridge_fast.py index 5aa2b8f..8245973 100644 --- a/lighter/models/current_height.py +++ b/lighter/models/resp_get_is_next_bridge_fast.py @@ -17,20 +17,20 @@ import re # noqa: F401 import json -from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr +from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set from typing_extensions import Self -class CurrentHeight(BaseModel): +class RespGetIsNextBridgeFast(BaseModel): """ - CurrentHeight + RespGetIsNextBridgeFast """ # noqa: E501 code: StrictInt message: Optional[StrictStr] = None - height: StrictInt + is_next_bridge_fast: StrictBool additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "height"] + __properties: ClassVar[List[str]] = ["code", "message", "is_next_bridge_fast"] model_config = ConfigDict( populate_by_name=True, @@ -50,7 +50,7 @@ def to_json(self) -> str: @classmethod def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of CurrentHeight from a JSON string""" + """Create an instance of RespGetIsNextBridgeFast from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -82,17 +82,17 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of CurrentHeight from a dict""" + """Create an instance of RespGetIsNextBridgeFast from a dict""" if obj is None: return None if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), - "height": obj.get("height") + "is_next_bridge_fast": obj.get("is_next_bridge_fast") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/resp_post_api_token.py b/lighter/models/resp_post_api_token.py new file mode 100644 index 0000000..b8b3ee2 --- /dev/null +++ b/lighter/models/resp_post_api_token.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class RespPostApiToken(BaseModel): + """ + RespPostApiToken + """ # noqa: E501 + code: StrictInt + message: Optional[StrictStr] = None + token_id: StrictInt + api_token: StrictStr + name: StrictStr + account_index: StrictInt + expiry: StrictInt + sub_account_access: StrictBool + revoked: StrictBool + scopes: StrictStr + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["code", "message", "token_id", "api_token", "name", "account_index", "expiry", "sub_account_access", "revoked", "scopes"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of RespPostApiToken from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of RespPostApiToken from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_construct(**{ + "code": obj.get("code"), + "message": obj.get("message"), + "token_id": obj.get("token_id"), + "api_token": obj.get("api_token"), + "name": obj.get("name"), + "account_index": obj.get("account_index"), + "expiry": obj.get("expiry"), + "sub_account_access": obj.get("sub_account_access"), + "revoked": obj.get("revoked"), + "scopes": obj.get("scopes") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/lighter/models/resp_public_pools_metadata.py b/lighter/models/resp_public_pools_metadata.py index 0719da8..f3406e7 100644 --- a/lighter/models/resp_public_pools_metadata.py +++ b/lighter/models/resp_public_pools_metadata.py @@ -97,7 +97,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "public_pools": [PublicPoolMetadata.from_dict(_item) for _item in obj["public_pools"]] if obj.get("public_pools") is not None else None diff --git a/lighter/models/resp_revoke_api_token.py b/lighter/models/resp_revoke_api_token.py new file mode 100644 index 0000000..91359b4 --- /dev/null +++ b/lighter/models/resp_revoke_api_token.py @@ -0,0 +1,106 @@ +# coding: utf-8 + +""" + + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class RespRevokeApiToken(BaseModel): + """ + RespRevokeApiToken + """ # noqa: E501 + code: StrictInt + message: Optional[StrictStr] = None + token_id: StrictInt + revoked: StrictBool + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["code", "message", "token_id", "revoked"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of RespRevokeApiToken from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of RespRevokeApiToken from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_construct(**{ + "code": obj.get("code"), + "message": obj.get("message"), + "token_id": obj.get("token_id"), + "revoked": obj.get("revoked") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/lighter/models/resp_send_tx.py b/lighter/models/resp_send_tx.py index cc6adcc..5bbdaa8 100644 --- a/lighter/models/resp_send_tx.py +++ b/lighter/models/resp_send_tx.py @@ -30,8 +30,9 @@ class RespSendTx(BaseModel): message: Optional[StrictStr] = None tx_hash: StrictStr predicted_execution_time_ms: StrictInt + volume_quota_remaining: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "tx_hash", "predicted_execution_time_ms"] + __properties: ClassVar[List[str]] = ["code", "message", "tx_hash", "predicted_execution_time_ms", "volume_quota_remaining"] model_config = ConfigDict( populate_by_name=True, @@ -90,11 +91,12 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "tx_hash": obj.get("tx_hash"), - "predicted_execution_time_ms": obj.get("predicted_execution_time_ms") + "predicted_execution_time_ms": obj.get("predicted_execution_time_ms"), + "volume_quota_remaining": obj.get("volume_quota_remaining") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/resp_send_tx_batch.py b/lighter/models/resp_send_tx_batch.py index 2b16358..0e408a2 100644 --- a/lighter/models/resp_send_tx_batch.py +++ b/lighter/models/resp_send_tx_batch.py @@ -30,8 +30,9 @@ class RespSendTxBatch(BaseModel): message: Optional[StrictStr] = None tx_hash: List[StrictStr] predicted_execution_time_ms: StrictInt + volume_quota_remaining: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["code", "message", "tx_hash", "predicted_execution_time_ms"] + __properties: ClassVar[List[str]] = ["code", "message", "tx_hash", "predicted_execution_time_ms", "volume_quota_remaining"] model_config = ConfigDict( populate_by_name=True, @@ -90,11 +91,12 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "tx_hash": obj.get("tx_hash"), - "predicted_execution_time_ms": obj.get("predicted_execution_time_ms") + "predicted_execution_time_ms": obj.get("predicted_execution_time_ms"), + "volume_quota_remaining": obj.get("volume_quota_remaining") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/resp_withdrawal_delay.py b/lighter/models/resp_withdrawal_delay.py index 3add899..dac6ebf 100644 --- a/lighter/models/resp_withdrawal_delay.py +++ b/lighter/models/resp_withdrawal_delay.py @@ -87,7 +87,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "seconds": obj.get("seconds") }) # store additional fields in additional_properties diff --git a/lighter/models/result_code.py b/lighter/models/result_code.py index a29a276..6e8eb96 100644 --- a/lighter/models/result_code.py +++ b/lighter/models/result_code.py @@ -88,7 +88,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message") }) diff --git a/lighter/models/risk_info.py b/lighter/models/risk_info.py index 93d571e..d0a5d2b 100644 --- a/lighter/models/risk_info.py +++ b/lighter/models/risk_info.py @@ -99,7 +99,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "cross_risk_parameters": RiskParameters.from_dict(obj["cross_risk_parameters"]) if obj.get("cross_risk_parameters") is not None else None, "isolated_risk_parameters": [RiskParameters.from_dict(_item) for _item in obj["isolated_risk_parameters"]] if obj.get("isolated_risk_parameters") is not None else None }) diff --git a/lighter/models/risk_parameters.py b/lighter/models/risk_parameters.py index 2084032..2d0463c 100644 --- a/lighter/models/risk_parameters.py +++ b/lighter/models/risk_parameters.py @@ -92,7 +92,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "market_id": obj.get("market_id"), "collateral": obj.get("collateral"), "total_account_value": obj.get("total_account_value"), diff --git a/lighter/models/share_price.py b/lighter/models/share_price.py index 6f347b4..923acec 100644 --- a/lighter/models/share_price.py +++ b/lighter/models/share_price.py @@ -88,7 +88,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "timestamp": obj.get("timestamp"), "share_price": obj.get("share_price") }) diff --git a/lighter/models/simple_order.py b/lighter/models/simple_order.py index a10be5d..b11a3a2 100644 --- a/lighter/models/simple_order.py +++ b/lighter/models/simple_order.py @@ -33,8 +33,9 @@ class SimpleOrder(BaseModel): remaining_base_amount: StrictStr price: StrictStr order_expiry: StrictInt + transaction_time: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["order_index", "order_id", "owner_account_index", "initial_base_amount", "remaining_base_amount", "price", "order_expiry"] + __properties: ClassVar[List[str]] = ["order_index", "order_id", "owner_account_index", "initial_base_amount", "remaining_base_amount", "price", "order_expiry", "transaction_time"] model_config = ConfigDict( populate_by_name=True, @@ -93,14 +94,15 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "order_index": obj.get("order_index"), "order_id": obj.get("order_id"), "owner_account_index": obj.get("owner_account_index"), "initial_base_amount": obj.get("initial_base_amount"), "remaining_base_amount": obj.get("remaining_base_amount"), "price": obj.get("price"), - "order_expiry": obj.get("order_expiry") + "order_expiry": obj.get("order_expiry"), + "transaction_time": obj.get("transaction_time") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/candlestick.py b/lighter/models/spot_market_stats.py similarity index 65% rename from lighter/models/candlestick.py rename to lighter/models/spot_market_stats.py index ea9d42e..60e7945 100644 --- a/lighter/models/candlestick.py +++ b/lighter/models/spot_market_stats.py @@ -17,25 +17,27 @@ import re # noqa: F401 import json -from pydantic import BaseModel, ConfigDict, StrictFloat, StrictInt +from pydantic import BaseModel, ConfigDict, StrictFloat, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Union from typing import Optional, Set from typing_extensions import Self -class Candlestick(BaseModel): +class SpotMarketStats(BaseModel): """ - Candlestick + SpotMarketStats """ # noqa: E501 - timestamp: StrictInt - open: Union[StrictFloat, StrictInt] - high: Union[StrictFloat, StrictInt] - low: Union[StrictFloat, StrictInt] - close: Union[StrictFloat, StrictInt] - volume0: Union[StrictFloat, StrictInt] - volume1: Union[StrictFloat, StrictInt] - last_trade_id: StrictInt + symbol: StrictStr + market_id: StrictInt + index_price: StrictStr + mid_price: StrictStr + last_trade_price: StrictStr + daily_base_token_volume: Union[StrictFloat, StrictInt] + daily_quote_token_volume: Union[StrictFloat, StrictInt] + daily_price_low: Union[StrictFloat, StrictInt] + daily_price_high: Union[StrictFloat, StrictInt] + daily_price_change: Union[StrictFloat, StrictInt] additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["timestamp", "open", "high", "low", "close", "volume0", "volume1", "last_trade_id"] + __properties: ClassVar[List[str]] = ["symbol", "market_id", "index_price", "mid_price", "last_trade_price", "daily_base_token_volume", "daily_quote_token_volume", "daily_price_low", "daily_price_high", "daily_price_change"] model_config = ConfigDict( populate_by_name=True, @@ -55,7 +57,7 @@ def to_json(self) -> str: @classmethod def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Candlestick from a JSON string""" + """Create an instance of SpotMarketStats from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -87,22 +89,24 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Candlestick from a dict""" + """Create an instance of SpotMarketStats from a dict""" if obj is None: return None if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ - "timestamp": obj.get("timestamp"), - "open": obj.get("open"), - "high": obj.get("high"), - "low": obj.get("low"), - "close": obj.get("close"), - "volume0": obj.get("volume0"), - "volume1": obj.get("volume1"), - "last_trade_id": obj.get("last_trade_id") + _obj = cls.model_construct(**{ + "symbol": obj.get("symbol"), + "market_id": obj.get("market_id"), + "index_price": obj.get("index_price"), + "mid_price": obj.get("mid_price"), + "last_trade_price": obj.get("last_trade_price"), + "daily_base_token_volume": obj.get("daily_base_token_volume"), + "daily_quote_token_volume": obj.get("daily_quote_token_volume"), + "daily_price_low": obj.get("daily_price_low"), + "daily_price_high": obj.get("daily_price_high"), + "daily_price_change": obj.get("daily_price_change") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/order_book_detail.py b/lighter/models/spot_order_book_detail.py similarity index 76% rename from lighter/models/order_book_detail.py rename to lighter/models/spot_order_book_detail.py index 012a8a5..b606737 100644 --- a/lighter/models/order_book_detail.py +++ b/lighter/models/spot_order_book_detail.py @@ -22,28 +22,27 @@ from typing import Optional, Set from typing_extensions import Self -class OrderBookDetail(BaseModel): +class SpotOrderBookDetail(BaseModel): """ - OrderBookDetail + SpotOrderBookDetail """ # noqa: E501 symbol: StrictStr market_id: StrictInt + market_type: StrictStr + base_asset_id: StrictInt + quote_asset_id: StrictInt status: StrictStr taker_fee: StrictStr maker_fee: StrictStr liquidation_fee: StrictStr min_base_amount: StrictStr min_quote_amount: StrictStr + order_quote_limit: StrictStr supported_size_decimals: StrictInt supported_price_decimals: StrictInt supported_quote_decimals: StrictInt size_decimals: StrictInt price_decimals: StrictInt - quote_multiplier: StrictInt - default_initial_margin_fraction: StrictInt - min_initial_margin_fraction: StrictInt - maintenance_margin_fraction: StrictInt - closeout_margin_fraction: StrictInt last_trade_price: Union[StrictFloat, StrictInt] daily_trades_count: StrictInt daily_base_token_volume: Union[StrictFloat, StrictInt] @@ -51,16 +50,22 @@ class OrderBookDetail(BaseModel): daily_price_low: Union[StrictFloat, StrictInt] daily_price_high: Union[StrictFloat, StrictInt] daily_price_change: Union[StrictFloat, StrictInt] - open_interest: Union[StrictFloat, StrictInt] daily_chart: Dict[str, Union[StrictFloat, StrictInt]] additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["symbol", "market_id", "status", "taker_fee", "maker_fee", "liquidation_fee", "min_base_amount", "min_quote_amount", "supported_size_decimals", "supported_price_decimals", "supported_quote_decimals", "size_decimals", "price_decimals", "quote_multiplier", "default_initial_margin_fraction", "min_initial_margin_fraction", "maintenance_margin_fraction", "closeout_margin_fraction", "last_trade_price", "daily_trades_count", "daily_base_token_volume", "daily_quote_token_volume", "daily_price_low", "daily_price_high", "daily_price_change", "open_interest", "daily_chart"] + __properties: ClassVar[List[str]] = ["symbol", "market_id", "market_type", "base_asset_id", "quote_asset_id", "status", "taker_fee", "maker_fee", "liquidation_fee", "min_base_amount", "min_quote_amount", "order_quote_limit", "supported_size_decimals", "supported_price_decimals", "supported_quote_decimals", "size_decimals", "price_decimals", "last_trade_price", "daily_trades_count", "daily_base_token_volume", "daily_quote_token_volume", "daily_price_low", "daily_price_high", "daily_price_change", "daily_chart"] + + @field_validator('market_type') + def market_type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['perp', 'spot']): + raise ValueError("must be one of enum values ('perp', 'spot')") + return value @field_validator('status') def status_validate_enum(cls, value): """Validates the enum""" - if value not in set(['inactive', 'frozen', 'active']): - raise ValueError("must be one of enum values ('inactive', 'frozen', 'active')") + if value not in set(['inactive', 'active']): + raise ValueError("must be one of enum values ('inactive', 'active')") return value model_config = ConfigDict( @@ -81,7 +86,7 @@ def to_json(self) -> str: @classmethod def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of OrderBookDetail from a JSON string""" + """Create an instance of SpotOrderBookDetail from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -113,32 +118,31 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of OrderBookDetail from a dict""" + """Create an instance of SpotOrderBookDetail from a dict""" if obj is None: return None if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "symbol": obj.get("symbol"), "market_id": obj.get("market_id"), + "market_type": obj.get("market_type"), + "base_asset_id": obj.get("base_asset_id"), + "quote_asset_id": obj.get("quote_asset_id"), "status": obj.get("status"), "taker_fee": obj.get("taker_fee"), "maker_fee": obj.get("maker_fee"), "liquidation_fee": obj.get("liquidation_fee"), "min_base_amount": obj.get("min_base_amount"), "min_quote_amount": obj.get("min_quote_amount"), + "order_quote_limit": obj.get("order_quote_limit"), "supported_size_decimals": obj.get("supported_size_decimals"), "supported_price_decimals": obj.get("supported_price_decimals"), "supported_quote_decimals": obj.get("supported_quote_decimals"), "size_decimals": obj.get("size_decimals"), "price_decimals": obj.get("price_decimals"), - "quote_multiplier": obj.get("quote_multiplier"), - "default_initial_margin_fraction": obj.get("default_initial_margin_fraction"), - "min_initial_margin_fraction": obj.get("min_initial_margin_fraction"), - "maintenance_margin_fraction": obj.get("maintenance_margin_fraction"), - "closeout_margin_fraction": obj.get("closeout_margin_fraction"), "last_trade_price": obj.get("last_trade_price"), "daily_trades_count": obj.get("daily_trades_count"), "daily_base_token_volume": obj.get("daily_base_token_volume"), @@ -146,7 +150,6 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: "daily_price_low": obj.get("daily_price_low"), "daily_price_high": obj.get("daily_price_high"), "daily_price_change": obj.get("daily_price_change"), - "open_interest": obj.get("open_interest"), "daily_chart": obj.get("daily_chart") }) # store additional fields in additional_properties diff --git a/lighter/models/status.py b/lighter/models/status.py index d2026f0..5c85974 100644 --- a/lighter/models/status.py +++ b/lighter/models/status.py @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "status": obj.get("status"), "network_id": obj.get("network_id"), "timestamp": obj.get("timestamp") diff --git a/lighter/models/sub_accounts.py b/lighter/models/sub_accounts.py index 76f4c0c..c51a05c 100644 --- a/lighter/models/sub_accounts.py +++ b/lighter/models/sub_accounts.py @@ -98,7 +98,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "l1_address": obj.get("l1_address"), diff --git a/lighter/models/ticker.py b/lighter/models/ticker.py index 96a5cd4..7c262c2 100644 --- a/lighter/models/ticker.py +++ b/lighter/models/ticker.py @@ -96,7 +96,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "s": obj.get("s"), "a": PriceLevel.from_dict(obj["a"]) if obj.get("a") is not None else None, "b": PriceLevel.from_dict(obj["b"]) if obj.get("b") is not None else None diff --git a/lighter/models/trade.py b/lighter/models/trade.py index 9156a47..be9c2ee 100644 --- a/lighter/models/trade.py +++ b/lighter/models/trade.py @@ -35,29 +35,32 @@ class Trade(BaseModel): usd_amount: StrictStr ask_id: StrictInt bid_id: StrictInt + ask_client_id: StrictInt + bid_client_id: StrictInt ask_account_id: StrictInt bid_account_id: StrictInt is_maker_ask: StrictBool block_height: StrictInt timestamp: StrictInt - taker_fee: Optional[StrictInt] + taker_fee: StrictInt taker_position_size_before: StrictStr taker_entry_quote_before: StrictStr - taker_initial_margin_fraction_before: Optional[StrictInt] - taker_position_sign_changed: Optional[StrictBool] - maker_fee: Optional[StrictInt] + taker_initial_margin_fraction_before: StrictInt + taker_position_sign_changed: StrictBool + maker_fee: StrictInt maker_position_size_before: StrictStr maker_entry_quote_before: StrictStr - maker_initial_margin_fraction_before: Optional[StrictInt] - maker_position_sign_changed: Optional[StrictBool] + maker_initial_margin_fraction_before: StrictInt + maker_position_sign_changed: StrictBool + transaction_time: StrictInt additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["trade_id", "tx_hash", "type", "market_id", "size", "price", "usd_amount", "ask_id", "bid_id", "ask_account_id", "bid_account_id", "is_maker_ask", "block_height", "timestamp", "taker_fee", "taker_position_size_before", "taker_entry_quote_before", "taker_initial_margin_fraction_before", "taker_position_sign_changed", "maker_fee", "maker_position_size_before", "maker_entry_quote_before", "maker_initial_margin_fraction_before", "maker_position_sign_changed"] + __properties: ClassVar[List[str]] = ["trade_id", "tx_hash", "type", "market_id", "size", "price", "usd_amount", "ask_id", "bid_id", "ask_client_id", "bid_client_id", "ask_account_id", "bid_account_id", "is_maker_ask", "block_height", "timestamp", "taker_fee", "taker_position_size_before", "taker_entry_quote_before", "taker_initial_margin_fraction_before", "taker_position_sign_changed", "maker_fee", "maker_position_size_before", "maker_entry_quote_before", "maker_initial_margin_fraction_before", "maker_position_sign_changed", "transaction_time"] @field_validator('type') def type_validate_enum(cls, value): """Validates the enum""" - if value not in set(['trade', 'liquidation', 'deleverage']): - raise ValueError("must be one of enum values ('trade', 'liquidation', 'deleverage')") + if value not in set(['trade', 'liquidation', 'deleverage', 'market-settlement']): + raise ValueError("must be one of enum values ('trade', 'liquidation', 'deleverage', 'market-settlement')") return value model_config = ConfigDict( @@ -117,7 +120,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "trade_id": obj.get("trade_id"), "tx_hash": obj.get("tx_hash"), "type": obj.get("type"), @@ -127,6 +130,8 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: "usd_amount": obj.get("usd_amount"), "ask_id": obj.get("ask_id"), "bid_id": obj.get("bid_id"), + "ask_client_id": obj.get("ask_client_id"), + "bid_client_id": obj.get("bid_client_id"), "ask_account_id": obj.get("ask_account_id"), "bid_account_id": obj.get("bid_account_id"), "is_maker_ask": obj.get("is_maker_ask"), @@ -141,7 +146,8 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: "maker_position_size_before": obj.get("maker_position_size_before"), "maker_entry_quote_before": obj.get("maker_entry_quote_before"), "maker_initial_margin_fraction_before": obj.get("maker_initial_margin_fraction_before"), - "maker_position_sign_changed": obj.get("maker_position_sign_changed") + "maker_position_sign_changed": obj.get("maker_position_sign_changed"), + "transaction_time": obj.get("transaction_time") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/lighter/models/trades.py b/lighter/models/trades.py index ea2097a..9d1bd0e 100644 --- a/lighter/models/trades.py +++ b/lighter/models/trades.py @@ -98,7 +98,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "next_cursor": obj.get("next_cursor"), diff --git a/lighter/models/transfer_fee_info.py b/lighter/models/transfer_fee_info.py index b4ee332..27d8ab8 100644 --- a/lighter/models/transfer_fee_info.py +++ b/lighter/models/transfer_fee_info.py @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "transfer_fee_usdc": obj.get("transfer_fee_usdc") diff --git a/lighter/models/transfer_history.py b/lighter/models/transfer_history.py index 9c415e6..3f5d1b7 100644 --- a/lighter/models/transfer_history.py +++ b/lighter/models/transfer_history.py @@ -98,7 +98,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "transfers": [TransferHistoryItem.from_dict(_item) for _item in obj["transfers"]] if obj.get("transfers") is not None else None, diff --git a/lighter/models/transfer_history_item.py b/lighter/models/transfer_history_item.py index dcebc4a..717fa5c 100644 --- a/lighter/models/transfer_history_item.py +++ b/lighter/models/transfer_history_item.py @@ -27,22 +27,40 @@ class TransferHistoryItem(BaseModel): TransferHistoryItem """ # noqa: E501 id: StrictStr + asset_id: StrictInt amount: StrictStr + fee: StrictStr timestamp: StrictInt type: StrictStr from_l1_address: StrictStr to_l1_address: StrictStr from_account_index: StrictInt to_account_index: StrictInt + from_route: StrictStr + to_route: StrictStr tx_hash: StrictStr additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["id", "amount", "timestamp", "type", "from_l1_address", "to_l1_address", "from_account_index", "to_account_index", "tx_hash"] + __properties: ClassVar[List[str]] = ["id", "asset_id", "amount", "fee", "timestamp", "type", "from_l1_address", "to_l1_address", "from_account_index", "to_account_index", "from_route", "to_route", "tx_hash"] @field_validator('type') def type_validate_enum(cls, value): """Validates the enum""" - if value not in set(['L2TransferInflow', 'L2TransferOutflow']): - raise ValueError("must be one of enum values ('L2TransferInflow', 'L2TransferOutflow')") + if value not in set(['L2TransferInflow', 'L2TransferOutflow', 'L2BurnSharesInflow', 'L2BurnSharesOutflow', 'L2MintSharesInflow', 'L2MintSharesOutflow', 'L2SelfTransfer']): + raise ValueError("must be one of enum values ('L2TransferInflow', 'L2TransferOutflow', 'L2BurnSharesInflow', 'L2BurnSharesOutflow', 'L2MintSharesInflow', 'L2MintSharesOutflow', 'L2SelfTransfer')") + return value + + @field_validator('from_route') + def from_route_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['spot', 'perps']): + raise ValueError("must be one of enum values ('spot', 'perps')") + return value + + @field_validator('to_route') + def to_route_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['spot', 'perps']): + raise ValueError("must be one of enum values ('spot', 'perps')") return value model_config = ConfigDict( @@ -102,15 +120,19 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "id": obj.get("id"), + "asset_id": obj.get("asset_id"), "amount": obj.get("amount"), + "fee": obj.get("fee"), "timestamp": obj.get("timestamp"), "type": obj.get("type"), "from_l1_address": obj.get("from_l1_address"), "to_l1_address": obj.get("to_l1_address"), "from_account_index": obj.get("from_account_index"), "to_account_index": obj.get("to_account_index"), + "from_route": obj.get("from_route"), + "to_route": obj.get("to_route"), "tx_hash": obj.get("tx_hash") }) # store additional fields in additional_properties diff --git a/lighter/models/tx.py b/lighter/models/tx.py deleted file mode 100644 index 1b78ad1..0000000 --- a/lighter/models/tx.py +++ /dev/null @@ -1,129 +0,0 @@ -# coding: utf-8 - -""" - - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - - The version of the OpenAPI document: - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - -from __future__ import annotations -import pprint -import re # noqa: F401 -import json - -from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr -from typing import Any, ClassVar, Dict, List -from typing_extensions import Annotated -from typing import Optional, Set -from typing_extensions import Self - -class Tx(BaseModel): - """ - Tx - """ # noqa: E501 - hash: StrictStr - type: Annotated[int, Field(le=64, strict=True, ge=1)] - info: StrictStr - event_info: StrictStr - status: StrictInt - transaction_index: StrictInt - l1_address: StrictStr - account_index: StrictInt - nonce: StrictInt - expire_at: StrictInt - block_height: StrictInt - queued_at: StrictInt - executed_at: StrictInt - sequence_index: StrictInt - parent_hash: StrictStr - additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["hash", "type", "info", "event_info", "status", "transaction_index", "l1_address", "account_index", "nonce", "expire_at", "block_height", "queued_at", "executed_at", "sequence_index", "parent_hash"] - - model_config = ConfigDict( - populate_by_name=True, - validate_assignment=True, - protected_namespaces=(), - ) - - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Tx from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict - - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Tx from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "hash": obj.get("hash"), - "type": obj.get("type"), - "info": obj.get("info"), - "event_info": obj.get("event_info"), - "status": obj.get("status"), - "transaction_index": obj.get("transaction_index"), - "l1_address": obj.get("l1_address"), - "account_index": obj.get("account_index"), - "nonce": obj.get("nonce"), - "expire_at": obj.get("expire_at"), - "block_height": obj.get("block_height"), - "queued_at": obj.get("queued_at"), - "executed_at": obj.get("executed_at"), - "sequence_index": obj.get("sequence_index"), - "parent_hash": obj.get("parent_hash") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj - - diff --git a/lighter/models/tx_hash.py b/lighter/models/tx_hash.py index 86cb1ed..06cfc5e 100644 --- a/lighter/models/tx_hash.py +++ b/lighter/models/tx_hash.py @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "tx_hash": obj.get("tx_hash") diff --git a/lighter/models/tx_hashes.py b/lighter/models/tx_hashes.py index 807aa59..a313f12 100644 --- a/lighter/models/tx_hashes.py +++ b/lighter/models/tx_hashes.py @@ -89,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "tx_hash": obj.get("tx_hash") diff --git a/lighter/models/validator_info.py b/lighter/models/validator_info.py index ca08bdf..7af526e 100644 --- a/lighter/models/validator_info.py +++ b/lighter/models/validator_info.py @@ -88,7 +88,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "address": obj.get("address"), "is_active": obj.get("is_active") }) diff --git a/lighter/models/withdraw_history.py b/lighter/models/withdraw_history.py index cdcb8c1..a25230c 100644 --- a/lighter/models/withdraw_history.py +++ b/lighter/models/withdraw_history.py @@ -98,7 +98,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "code": obj.get("code"), "message": obj.get("message"), "withdraws": [WithdrawHistoryItem.from_dict(_item) for _item in obj["withdraws"]] if obj.get("withdraws") is not None else None, diff --git a/lighter/models/withdraw_history_item.py b/lighter/models/withdraw_history_item.py index fdc9a82..9812939 100644 --- a/lighter/models/withdraw_history_item.py +++ b/lighter/models/withdraw_history_item.py @@ -27,13 +27,14 @@ class WithdrawHistoryItem(BaseModel): WithdrawHistoryItem """ # noqa: E501 id: StrictStr + asset_id: StrictInt amount: StrictStr timestamp: StrictInt status: StrictStr type: StrictStr l1_tx_hash: StrictStr additional_properties: Dict[str, Any] = {} - __properties: ClassVar[List[str]] = ["id", "amount", "timestamp", "status", "type", "l1_tx_hash"] + __properties: ClassVar[List[str]] = ["id", "asset_id", "amount", "timestamp", "status", "type", "l1_tx_hash"] @field_validator('status') def status_validate_enum(cls, value): @@ -106,8 +107,9 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "id": obj.get("id"), + "asset_id": obj.get("asset_id"), "amount": obj.get("amount"), "timestamp": obj.get("timestamp"), "status": obj.get("status"), diff --git a/lighter/models/ws_account_assets.py b/lighter/models/ws_account_assets.py new file mode 100644 index 0000000..03520dd --- /dev/null +++ b/lighter/models/ws_account_assets.py @@ -0,0 +1,86 @@ +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from lighter.models.account_asset import AccountAsset +from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr, Field +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set + +class WSAccountAssets(BaseModel): + type: StrictStr + channel: StrictStr + assets: Dict[StrictStr, AccountAsset] + account_id: StrictInt + + additional_properties: Dict[str, Any] = Field(default_factory=dict) + __properties: ClassVar[List[str]] = ["type", "channel", "assets"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + def to_str(self) -> str: + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional["WSAccountAssets"]: + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + excluded_fields: Set[str] = {"additional_properties"} + + # dump base fields + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + + # add extra fields + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional["WSAccountAssets"]: + if obj["type"] != "subscribed/account_all_assets" and obj["type"] != "update/account_all_assets": + raise ValueError(f"invalid type {obj['type']} for WSAccountAssets") + + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + # parse inner assets dict into AccountAsset objects + raw_assets = obj.get("assets") or {} + parsed_assets: Dict[str, AccountAsset] = { + k: AccountAsset.from_dict(v) for k, v in raw_assets.items() + } + + account_id = int(obj.get("channel").split(":")[1]) + + _obj = cls.model_validate( + { + "type": obj.get("type"), + "channel": obj.get("channel"), + "assets": parsed_assets, + "account_id": account_id + } + ) + + # store additional fields + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj \ No newline at end of file diff --git a/lighter/models/zk_lighter_info.py b/lighter/models/zk_lighter_info.py index 81fcb14..e3bbace 100644 --- a/lighter/models/zk_lighter_info.py +++ b/lighter/models/zk_lighter_info.py @@ -87,7 +87,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({ + _obj = cls.model_construct(**{ "contract_address": obj.get("contract_address") }) # store additional fields in additional_properties diff --git a/lighter/nonce_manager.py b/lighter/nonce_manager.py index cf4c730..c2c6db6 100644 --- a/lighter/nonce_manager.py +++ b/lighter/nonce_manager.py @@ -1,19 +1,18 @@ import abc import enum -from typing import Optional, Tuple +from typing import Optional, Tuple, List import requests -from lighter import api_client -from lighter.api import transaction_api +from lighter.api_client import ApiClient from lighter.errors import ValidationError -def get_nonce_from_api(client: api_client.ApiClient, account_index: int, api_key_index: int) -> int: +def get_nonce_from_api(client: ApiClient, account_index: int, api_key: int) -> int: # uses request to avoid async initialization req = requests.get( client.configuration.host + "/api/v1/nextNonce", - params={"account_index": account_index, "api_key_index": api_key_index}, + params={"account_index": account_index, "api_key_index": api_key}, ) if req.status_code != 200: raise Exception(f"couldn't get nonce {req.content}") @@ -22,85 +21,80 @@ def get_nonce_from_api(client: api_client.ApiClient, account_index: int, api_key class NonceManager(abc.ABC): def __init__( - self, - account_index: int, - api_client: api_client.ApiClient, - start_api_key: int, - end_api_key: Optional[int] = None, + self, + account_index: int, + api_client: ApiClient, + api_keys_list: List[int], ): - if end_api_key is None: - end_api_key = start_api_key - if start_api_key > end_api_key or start_api_key >= 255 or end_api_key >= 255: - raise ValidationError(f"invalid range {start_api_key=} {end_api_key=}") - self.start_api_key = start_api_key - self.end_api_key = end_api_key - self.current_api_key = end_api_key # start will be used for the first tx + if len(api_keys_list) == 0: + raise ValidationError(f"No API Key provided") + + self.current = 0 # cycle through api keys self.account_index = account_index self.api_client = api_client + self.api_keys_list = api_keys_list self.nonce = { - api_key_index: get_nonce_from_api(api_client, account_index, api_key_index) - 1 - for api_key_index in range(start_api_key, end_api_key + 1) + api_keys_list[i]: get_nonce_from_api(api_client, account_index, api_keys_list[i]) - 1 + for i in range(len(api_keys_list)) } + def refresh_nonce(self, api_key: int) -> int: + self.nonce[api_key] = get_nonce_from_api(self.api_client, self.account_index, api_key) + return self.nonce[api_key] + def hard_refresh_nonce(self, api_key: int): self.nonce[api_key] = get_nonce_from_api(self.api_client, self.account_index, api_key) - 1 @abc.abstractmethod - def next_nonce(self) -> Tuple[int, int]: + def next_nonce(self, api_key: Optional[int] = None) -> Tuple[int, int]: pass - def acknowledge_failure(self, api_key_index: int) -> None: + def acknowledge_failure(self, api_key: int) -> None: pass -def increment_circular(idx: int, start_idx: int, end_idx: int) -> int: - idx += 1 - if idx > end_idx: - return start_idx - return idx - - class OptimisticNonceManager(NonceManager): def __init__( - self, - account_index: int, - api_client: api_client.ApiClient, - start_api_key: int, - end_api_key: Optional[int] = None, + self, + account_index: int, + api_client: ApiClient, + api_keys_list: List[int] ) -> None: - super().__init__(account_index, api_client, start_api_key, end_api_key) + super().__init__(account_index, api_client, api_keys_list) + + def next_nonce(self, api_key: Optional[int] = None) -> Tuple[int, int]: + if api_key is None: + self.current = (self.current + 1) % len(self.api_keys_list) + api_key = self.api_keys_list[self.current] - def next_nonce(self) -> Tuple[int, int]: - self.current_api_key = increment_circular(self.current_api_key, self.start_api_key, self.end_api_key) - self.nonce[self.current_api_key] += 1 - return (self.current_api_key, self.nonce[self.current_api_key]) + self.nonce[api_key] += 1 + return api_key, self.nonce[api_key] - def acknowledge_failure(self, api_key_index: int) -> None: - self.nonce[api_key_index] -= 1 + def acknowledge_failure(self, api_key: int) -> None: + self.nonce[api_key] -= 1 class ApiNonceManager(NonceManager): def __init__( - self, - account_index: int, - api_client: api_client.ApiClient, - start_api_key: int, - end_api_key: Optional[int] = None, + self, + account_index: int, + api_client: ApiClient, + api_keys_list: List[int], ) -> None: - super().__init__(account_index, api_client, start_api_key, end_api_key) + super().__init__(account_index, api_client, api_keys_list) - def next_nonce(self) -> Tuple[int, int]: + def next_nonce(self, api_key: Optional[int] = None) -> Tuple[int, int]: """ It is recommended to wait at least 350ms before using the same api key. Please be mindful of your transaction frequency when using this nonce manager. predicted_execution_time_ms from the response could give you a tighter bound. """ - self.current_api_key = increment_circular(self.current_api_key, self.start_api_key, self.end_api_key) - self.nonce[self.current_api_key] = get_nonce_from_api(self.api_client, self.account_index, self.current_api_key) - return (self.current_api_key, self.nonce[self.current_api_key]) + if api_key is None: + self.current = (self.current + 1) % len(self.api_keys_list) + api_key = self.api_keys_list[self.current] - def refresh_nonce(self, api_key_index: int) -> int: - self.nonce[api_key_index] = get_nonce_from_api(self.api_client, self.start_api_key, self.end_api_key) + nonce = self.refresh_nonce(api_key) + return api_key, nonce class NonceManagerType(enum.Enum): @@ -109,24 +103,21 @@ class NonceManagerType(enum.Enum): def nonce_manager_factory( - nonce_manager_type: NonceManagerType, - account_index: int, - api_client: api_client.ApiClient, - start_api_key: int, - end_api_key: Optional[int] = None, + nonce_manager_type: NonceManagerType, + account_index: int, + api_client: ApiClient, + api_keys_list: List[int], ) -> NonceManager: if nonce_manager_type == NonceManagerType.OPTIMISTIC: return OptimisticNonceManager( account_index=account_index, api_client=api_client, - start_api_key=start_api_key, - end_api_key=end_api_key, + api_keys_list=api_keys_list, ) elif nonce_manager_type == NonceManagerType.API: return ApiNonceManager( account_index=account_index, api_client=api_client, - start_api_key=start_api_key, - end_api_key=end_api_key, + api_keys_list=api_keys_list, ) raise ValidationError("invalid nonce manager type") diff --git a/lighter/signer_client.py b/lighter/signer_client.py index ca464a7..b86b763 100644 --- a/lighter/signer_client.py +++ b/lighter/signer_client.py @@ -6,7 +6,7 @@ import logging import os import time -from typing import Dict, List, Optional, Tuple +from typing import Dict, List, Optional, Union, Tuple from eth_account import Account from eth_account.messages import encode_defunct @@ -17,6 +17,7 @@ from lighter.models import TxHash from lighter import nonce_manager from lighter.models.resp_send_tx import RespSendTx +from lighter.models.resp_send_tx_batch import RespSendTxBatch from lighter.transactions import CreateOrder, CancelOrder, Withdraw, CreateGroupedOrders CODE_OK = 200 @@ -25,6 +26,7 @@ class ApiKeyResponse(ctypes.Structure): _fields_ = [("privateKey", ctypes.c_char_p), ("publicKey", ctypes.c_char_p), ("err", ctypes.c_char_p)] + class CreateOrderTxReq(ctypes.Structure): _fields_ = [ ("MarketIndex", ctypes.c_uint8), @@ -39,11 +41,25 @@ class CreateOrderTxReq(ctypes.Structure): ("OrderExpiry", ctypes.c_longlong), ] + class StrOrErr(ctypes.Structure): _fields_ = [("str", ctypes.c_char_p), ("err", ctypes.c_char_p)] -def _initialize_signer(): +class SignedTxResponse(ctypes.Structure): + _fields_ = [ + ("txType", ctypes.c_uint8), + ("txInfo", ctypes.c_char_p), + ("txHash", ctypes.c_char_p), + ("messageToSign", ctypes.c_char_p), + ("err", ctypes.c_char_p), + ] + + +__signer = None + + +def __get_shared_library(): is_linux = platform.system() == "Linux" is_mac = platform.system() == "Darwin" is_windows = platform.system() == "Windows" @@ -54,11 +70,13 @@ def _initialize_signer(): path_to_signer_folders = os.path.join(current_file_directory, "signers") if is_arm and is_mac: - return ctypes.CDLL(os.path.join(path_to_signer_folders, "signer-arm64.dylib")) + return ctypes.CDLL(os.path.join(path_to_signer_folders, "lighter-signer-darwin-arm64.dylib")) elif is_linux and is_x64: - return ctypes.CDLL(os.path.join(path_to_signer_folders, "signer-amd64.so")) + return ctypes.CDLL(os.path.join(path_to_signer_folders, "lighter-signer-linux-amd64.so")) + elif is_linux and is_arm: + return ctypes.CDLL(os.path.join(path_to_signer_folders, "lighter-signer-linux-arm64.so")) elif is_windows and is_x64: - return ctypes.CDLL(os.path.join(path_to_signer_folders, "signer-amd64.dll")) + return ctypes.CDLL(os.path.join(path_to_signer_folders, "lighter-signer-windows-amd64.dll")) else: raise Exception( f"Unsupported platform/architecture: {platform.system()}/{platform.machine()}. " @@ -66,13 +84,83 @@ def _initialize_signer(): ) -def create_api_key(seed=""): - signer = _initialize_signer() - signer.GenerateAPIKey.argtypes = [ - ctypes.c_char_p, - ] +def __populate_shared_library_functions(signer): + signer.GenerateAPIKey.argtypes = [] signer.GenerateAPIKey.restype = ApiKeyResponse - result = signer.GenerateAPIKey(ctypes.c_char_p(seed.encode("utf-8"))) + + signer.CreateClient.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_longlong] + signer.CreateClient.restype = ctypes.c_char_p + + signer.CheckClient.argtypes = [ctypes.c_int, ctypes.c_longlong] + signer.CheckClient.restype = ctypes.c_char_p + + signer.SignChangePubKey.argtypes = [ctypes.c_char_p, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignChangePubKey.restype = SignedTxResponse + + signer.SignCreateOrder.argtypes = [ctypes.c_int, ctypes.c_longlong, ctypes.c_longlong, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, + ctypes.c_int, ctypes.c_int, ctypes.c_longlong, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignCreateOrder.restype = SignedTxResponse + + signer.SignCreateGroupedOrders.argtypes = [ctypes.c_uint8, ctypes.POINTER(CreateOrderTxReq), ctypes.c_int, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignCreateGroupedOrders.restype = SignedTxResponse + + signer.SignCancelOrder.argtypes = [ctypes.c_int, ctypes.c_longlong, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignCancelOrder.restype = SignedTxResponse + + signer.SignWithdraw.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_longlong, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignWithdraw.restype = SignedTxResponse + + signer.SignCreateSubAccount.argtypes = [ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignCreateSubAccount.restype = SignedTxResponse + + signer.SignCancelAllOrders.argtypes = [ctypes.c_int, ctypes.c_longlong, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignCancelAllOrders.restype = SignedTxResponse + + signer.SignModifyOrder.argtypes = [ctypes.c_int, ctypes.c_longlong, ctypes.c_longlong, ctypes.c_longlong, ctypes.c_longlong, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignModifyOrder.restype = SignedTxResponse + + signer.SignTransfer.argtypes = [ctypes.c_longlong, ctypes.c_int16, ctypes.c_int8, ctypes.c_int8, ctypes.c_longlong, ctypes.c_longlong, ctypes.c_char_p, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignTransfer.restype = SignedTxResponse + + signer.SignCreatePublicPool.argtypes = [ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignCreatePublicPool.restype = SignedTxResponse + + signer.SignUpdatePublicPool.argtypes = [ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignUpdatePublicPool.restype = SignedTxResponse + + signer.SignMintShares.argtypes = [ctypes.c_longlong, ctypes.c_longlong, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignMintShares.restype = SignedTxResponse + + signer.SignBurnShares.argtypes = [ctypes.c_longlong, ctypes.c_longlong, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignBurnShares.restype = SignedTxResponse + + signer.SignUpdateLeverage.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignUpdateLeverage.restype = SignedTxResponse + + signer.CreateAuthToken.argtypes = [ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.CreateAuthToken.restype = StrOrErr + + # Note: SwitchAPIKey is no longer exported in the new binary + # All functions now take api_key_index directly, so switching is handled via parameters + + signer.SignUpdateMargin.argtypes = [ctypes.c_int, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong] + signer.SignUpdateMargin.restype = SignedTxResponse + + +def get_signer(): + # check if singleton exists already + global __signer + if __signer is not None: + return __signer + + # create shared library & populate methods + __signer = __get_shared_library() + __populate_shared_library_functions(__signer) + return __signer + + +def create_api_key(): + result = get_signer().GenerateAPIKey() private_key_str = result.privateKey.decode("utf-8") if result.privateKey else None public_key_str = result.publicKey.decode("utf-8") if result.publicKey else None @@ -95,13 +183,10 @@ async def wrapper(self, *args, **kwargs): bound_args = sig.bind(self, *args, **kwargs) bound_args.apply_defaults() # Extract api_key_index and nonce from kwargs or use defaults - api_key_index = bound_args.arguments.get("api_key_index", -1) + api_key_index = bound_args.arguments.get("api_key_index", 255) nonce = bound_args.arguments.get("nonce", -1) - if api_key_index == -1 and nonce == -1: + if api_key_index == 255 and nonce == -1: api_key_index, nonce = self.nonce_manager.next_nonce() - err = self.switch_api_key(api_key_index) - if err != None: - raise Exception(f"error switching api key: {err}") # Call the original function with modified kwargs ret: TxHash @@ -124,22 +209,17 @@ async def wrapper(self, *args, **kwargs): class SignerClient: - USDC_TICKER_SCALE = 1e6 + DEFAULT_NONCE = -1 + DEFAULT_API_KEY_INDEX = 255 - TX_TYPE_CHANGE_PUB_KEY = 8 - TX_TYPE_CREATE_SUB_ACCOUNT = 9 - TX_TYPE_CREATE_PUBLIC_POOL = 10 - TX_TYPE_UPDATE_PUBLIC_POOL = 11 - TX_TYPE_TRANSFER = 12 - TX_TYPE_WITHDRAW = 13 - TX_TYPE_CREATE_ORDER = 14 - TX_TYPE_CANCEL_ORDER = 15 - TX_TYPE_CANCEL_ALL_ORDERS = 16 - TX_TYPE_MODIFY_ORDER = 17 - TX_TYPE_MINT_SHARES = 18 - TX_TYPE_BURN_SHARES = 19 - TX_TYPE_UPDATE_LEVERAGE = 20 - TX_TYPE_CREATE_GROUP_ORDER = 28 + ETH_TICKER_SCALE = 1e8 + USDC_TICKER_SCALE = 1e6 + LIT_TICKER_SCALE = 1e8 + LINK_TICKER_SCALE = 1e8 + UNI_TICKER_SCALE = 1e8 + AAVE_TICKER_SCALE = 1e8 + SKY_TICKER_SCALE = 1e8 + LDO_TICKER_SCALE = 1e8 ORDER_TYPE_LIMIT = 0 ORDER_TYPE_MARKET = 1 @@ -163,85 +243,111 @@ class SignerClient: DEFAULT_10_MIN_AUTH_EXPIRY = -1 MINUTE = 60 - CROSS_MARGIN_MODE = 0 + CROSS_MARGIN_MODE = 0 ISOLATED_MARGIN_MODE = 1 + ISOLATED_MARGIN_REMOVE_COLLATERAL = 0 + ISOLATED_MARGIN_ADD_COLLATERAL = 1 + GROUPING_TYPE_ONE_TRIGGERS_THE_OTHER = 1 - GROUPING_TYPE_ONE_CANCELS_THE_OTHER = 2 + GROUPING_TYPE_ONE_CANCELS_THE_OTHER = 2 GROUPING_TYPE_ONE_TRIGGERS_A_ONE_CANCELS_THE_OTHER = 3 + ROUTE_PERP = 0 + ROUTE_SPOT = 1 + + ASSET_ID_ETH = 1 + ASSET_ID_LIT = 2 + ASSET_ID_USDC = 3 + ASSET_ID_LINK = 5 + ASSET_ID_UNI = 6 + ASSET_ID_AAVE = 7 + ASSET_ID_SKY = 8 + ASSET_ID_LDO = 9 + + ASSET_TO_TICKER_SCALE = { + ASSET_ID_ETH: ETH_TICKER_SCALE, + ASSET_ID_LIT: LIT_TICKER_SCALE, + ASSET_ID_USDC: USDC_TICKER_SCALE, + ASSET_ID_LINK: LINK_TICKER_SCALE, + ASSET_ID_UNI: UNI_TICKER_SCALE, + ASSET_ID_AAVE: AAVE_TICKER_SCALE, + ASSET_ID_SKY: SKY_TICKER_SCALE, + ASSET_ID_LDO: LDO_TICKER_SCALE, + } + def __init__( - self, - url, - private_key, - api_key_index, - account_index, - max_api_key_index=-1, - private_keys: Optional[Dict[int, str]] = None, - nonce_management_type=nonce_manager.NonceManagerType.OPTIMISTIC, + self, + url, + account_index, + api_private_keys: Dict[int, str], + nonce_management_type=nonce_manager.NonceManagerType.OPTIMISTIC, ): - """ - First private key needs to be passed separately for backwards compatibility. - This may get deprecated in a future version. - """ - chain_id = 304 if "mainnet" in url else 300 - - # api_key_index=0 is generally used by frontend - if private_key.startswith("0x"): - private_key = private_key[2:] self.url = url - self.private_key = private_key - self.chain_id = chain_id - self.api_key_index = api_key_index - if max_api_key_index == -1: - self.end_api_key_index = api_key_index - else: - self.end_api_key_index = max_api_key_index + self.chain_id = 304 if "mainnet" in url else 300 - private_keys = private_keys or {} - self.validate_api_private_keys(private_key, private_keys) - self.api_key_dict = self.build_api_key_dict(private_key, private_keys) + self.validate_api_private_keys(api_private_keys) + self.api_key_dict = api_private_keys self.account_index = account_index - self.signer = _initialize_signer() + self.signer = get_signer() self.api_client = lighter.ApiClient(configuration=Configuration(host=url)) self.tx_api = lighter.TransactionApi(self.api_client) self.order_api = lighter.OrderApi(self.api_client) + self.nonce_manager = nonce_manager.nonce_manager_factory( nonce_manager_type=nonce_management_type, account_index=account_index, api_client=self.api_client, - start_api_key=self.api_key_index, - end_api_key=self.end_api_key_index, + api_keys_list=list(api_private_keys.keys()), ) - for api_key in range(self.api_key_index, self.end_api_key_index + 1): - self.create_client(api_key) - - def validate_api_private_keys(self, initial_private_key: str, private_keys: Dict[int, str]): - if len(private_keys) == self.end_api_key_index - self.api_key_index + 1: - if not self.are_keys_equal(private_keys[self.api_key_index], initial_private_key): - raise ValidationError("inconsistent private keys") - return # this is all we need to check in this case - if len(private_keys) != self.end_api_key_index - self.api_key_index: - raise ValidationError("unexpected number of private keys") - for api_key in range(self.api_key_index + 1, self.end_api_key_index): - if api_key not in private_keys: - raise Exception(f"missing {api_key=} private key!") - - def build_api_key_dict(self, private_key, private_keys): - if len(private_keys) == self.end_api_key_index - self.api_key_index: - private_keys[self.api_key_index] = private_key - return private_keys - - def create_client(self, api_key_index=None): - self.signer.CreateClient.argtypes = [ - ctypes.c_char_p, - ctypes.c_char_p, - ctypes.c_int, - ctypes.c_int, - ctypes.c_longlong, - ] - api_key_index = api_key_index or self.api_key_index - self.signer.CreateClient.restype = ctypes.c_char_p + for api_key_index in api_private_keys.keys(): + self.create_client(api_key_index) + + # === signer helpers === + @staticmethod + def __decode_tx_info(result: SignedTxResponse) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + if result.err: + error = result.err.decode("utf-8") + return None, None, None, error + + # Use txType from response if available, otherwise use the provided type + tx_type = result.txType + tx_info_str = result.txInfo.decode("utf-8") if result.txInfo else None + tx_hash_str = result.txHash.decode("utf-8") if result.txHash else None + + return tx_type, tx_info_str, tx_hash_str, None + + @staticmethod + def __decode_and_sign_tx_info(eth_private_key: str, result: SignedTxResponse) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + if result.err: + err = result.err.decode("utf-8") + return None, None, None, err + + tx_type = result.txType + tx_info_str = result.txInfo.decode("utf-8") if result.txInfo else None + tx_hash_str = result.txHash.decode("utf-8") if result.txHash else None + msg_to_sign = result.messageToSign.decode("utf-8") if result.messageToSign else None + + # sign the message + acct = Account.from_key(eth_private_key) + message = encode_defunct(text=msg_to_sign) + signature = acct.sign_message(message) + + # add signature to tx_info + tx_info = json.loads(tx_info_str) + tx_info["L1Sig"] = signature.signature.to_0x_hex() + return tx_type, json.dumps(tx_info), tx_hash_str, None + + def validate_api_private_keys(self, private_keys: Dict[int, str]): + if len(private_keys) == 0: + raise ValidationError("No API keys provided") + + # trim 0x + for api_key_index, private_key in private_keys.items(): + if private_key.startswith("0x"): + private_keys[api_key_index] = private_key[2:] + + def create_client(self, api_key_index): err = self.signer.CreateClient( self.url.encode("utf-8"), self.api_key_dict[api_key_index].encode("utf-8"), @@ -253,107 +359,89 @@ def create_client(self, api_key_index=None): if err is None: return - err_str = err.decode("utf-8") - raise Exception(err_str) - - # check_client verifies that the given API key associated with (api_key_index, account_index) matches the one on Lighter - def check_client(self): - self.signer.CheckClient.argtypes = [ - ctypes.c_int, - ctypes.c_longlong, - ] - self.signer.CheckClient.restype = ctypes.c_char_p - - for api_key in range(self.api_key_index, self.end_api_key_index + 1): - result = self.signer.CheckClient(api_key, self.account_index) - if result: - return result.decode("utf-8") + f" on api key {self.api_key_index}" - return result.decode("utf-8") if result else None - - def switch_api_key(self, api_key: int): - self.signer.SwitchAPIKey.argtypes = [ctypes.c_int] - self.signer.CheckClient.restype = ctypes.c_char_p - result = self.signer.SwitchAPIKey(api_key) - return result.decode("utf-8") if result else None - - def create_api_key(self, seed=""): - self.signer.GenerateAPIKey.argtypes = [ - ctypes.c_char_p, - ] - self.signer.GenerateAPIKey.restype = ApiKeyResponse - result = self.signer.GenerateAPIKey(ctypes.c_char_p(seed.encode("utf-8"))) - - private_key_str = result.str.decode("utf-8") if result.privateKey else None - public_key_str = result.str.decode("utf-8") if result.publicKey else None - error = result.err.decode("utf-8") if result.err else None - - return private_key_str, public_key_str, error + if err is not None: + raise Exception(err.decode("utf-8")) - def sign_change_api_key(self, eth_private_key, new_pubkey: str, nonce: int): - self.signer.SignChangePubKey.argtypes = [ - ctypes.c_char_p, - ctypes.c_longlong, - ] - self.signer.SignChangePubKey.restype = StrOrErr - result = self.signer.SignChangePubKey(ctypes.c_char_p(new_pubkey.encode("utf-8")), nonce) + def __signer_check_client( + self, + api_key_index: int, + account_index: int, + ) -> Optional[str]: + err = self.signer.CheckClient(api_key_index, account_index) + if err is None: + return None - tx_info_str = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None - if error is not None: - return None, error + return err.decode("utf-8") - # fetch message to sign - tx_info = json.loads(tx_info_str) - msg_to_sign = tx_info["MessageToSign"] - del tx_info["MessageToSign"] + # check_client verifies that the given API key associated with (api_key_index, account_index) matches the one on Lighter + def check_client(self): + for api_key in self.api_key_dict.keys(): + err = self.__signer_check_client(api_key, self.account_index) + if err is not None: + return err + f" on api key {api_key}" + return None - # sign the message - acct = Account.from_key(eth_private_key) - message = encode_defunct(text=msg_to_sign) - signature = acct.sign_message(message) - tx_info["L1Sig"] = signature.signature.to_0x_hex() - return json.dumps(tx_info), None + @staticmethod + def create_api_key(self): + return create_api_key() def get_api_key_nonce(self, api_key_index: int, nonce: int) -> Tuple[int, int]: - if api_key_index != -1 and nonce != -1: + if api_key_index != self.DEFAULT_API_KEY_INDEX and nonce != self.DEFAULT_NONCE: return api_key_index, nonce - if nonce != -1: - if self.api_key_index == self.end_api_key_index: + + if nonce != self.DEFAULT_NONCE: + if len(self.api_key_dict) == 1: return self.nonce_manager.next_nonce() else: raise Exception("ambiguous api key") return self.nonce_manager.next_nonce() + def create_auth_token_with_expiry(self, deadline: int = DEFAULT_10_MIN_AUTH_EXPIRY, *, timestamp: int = None, api_key_index: int = DEFAULT_API_KEY_INDEX): + if deadline == SignerClient.DEFAULT_10_MIN_AUTH_EXPIRY: + deadline = 10 * SignerClient.MINUTE + if timestamp is None: + timestamp = int(time.time()) + + result = self.signer.CreateAuthToken(deadline+timestamp, api_key_index, self.account_index) + + auth = result.str.decode("utf-8") if result.str else None + error = result.err.decode("utf-8") if result.err else None + return auth, error + + def sign_change_api_key(self, eth_private_key: str, new_pubkey: str, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_and_sign_tx_info(eth_private_key, self.signer.SignChangePubKey( + ctypes.c_char_p(new_pubkey.encode("utf-8")), + nonce, + api_key_index, + self.account_index + )) + + async def change_api_key(self, eth_private_key: str, new_pubkey: str, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX): + tx_type, tx_info, tx_hash, error = self.sign_change_api_key(eth_private_key, new_pubkey, nonce, api_key_index) + if error is not None: + return None, error + + logging.debug(f"Change Pub Key TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Change Pub Key Send. TxResponse: {api_response}") + return api_response, None + def sign_create_order( - self, - market_index, - client_order_index, - base_amount, - price, - is_ask, - order_type, - time_in_force, - reduce_only, - trigger_price, - order_expiry=DEFAULT_28_DAY_ORDER_EXPIRY, - nonce=-1, - ): - self.signer.SignCreateOrder.argtypes = [ - ctypes.c_int, - ctypes.c_longlong, - ctypes.c_longlong, - ctypes.c_int, - ctypes.c_int, - ctypes.c_int, - ctypes.c_int, - ctypes.c_int, - ctypes.c_int, - ctypes.c_longlong, - ctypes.c_longlong, - ] - self.signer.SignCreateOrder.restype = StrOrErr - - result = self.signer.SignCreateOrder( + self, + market_index, + client_order_index, + base_amount, + price, + is_ask, + order_type, + time_in_force, + reduce_only=False, + trigger_price=NIL_TRIGGER_PRICE, + order_expiry=DEFAULT_28_DAY_ORDER_EXPIRY, + nonce: int = DEFAULT_NONCE, + api_key_index: int = DEFAULT_API_KEY_INDEX + ) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_tx_info(self.signer.SignCreateOrder( market_index, client_order_index, base_amount, @@ -365,255 +453,80 @@ def sign_create_order( trigger_price, order_expiry, nonce, - ) - - tx_info = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None - - return tx_info, error + api_key_index, + self.account_index, + )) def sign_create_grouped_orders( - self, - grouping_type: int, - orders: List[CreateOrderTxReq], - nonce=-1, - ): + self, + grouping_type: int, + orders: List[CreateOrderTxReq], + nonce: int = DEFAULT_NONCE, + api_key_index=DEFAULT_API_KEY_INDEX + ) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: arr_type = CreateOrderTxReq * len(orders) orders_arr = arr_type(*orders) - self.signer.SignCreateGroupedOrders.argtypes = [ - ctypes.c_uint8, - ctypes.POINTER(CreateOrderTxReq), - ctypes.c_int, - ctypes.c_longlong, - ] - self.signer.SignCreateGroupedOrders.restype = StrOrErr - - result = self.signer.SignCreateGroupedOrders( - grouping_type, orders_arr, len(orders), nonce - ) - - tx_info = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None - return tx_info, error - - def sign_cancel_order(self, market_index, order_index, nonce=-1): - self.signer.SignCancelOrder.argtypes = [ - ctypes.c_int, - ctypes.c_longlong, - ctypes.c_longlong, - ] - self.signer.SignCancelOrder.restype = StrOrErr - - result = self.signer.SignCancelOrder(market_index, order_index, nonce) - - tx_info = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None - - return tx_info, error - - def sign_withdraw(self, usdc_amount, nonce=-1): - self.signer.SignWithdraw.argtypes = [ctypes.c_longlong, ctypes.c_longlong] - self.signer.SignWithdraw.restype = StrOrErr - - result = self.signer.SignWithdraw(usdc_amount, nonce) - - tx_info = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None - - return tx_info, error - - def sign_create_sub_account(self, nonce=-1): - self.signer.SignCreateSubAccount.argtypes = [ctypes.c_longlong] - self.signer.SignCreateSubAccount.restype = StrOrErr - - result = self.signer.SignCreateSubAccount(nonce) - - tx_info = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None - - return tx_info, error - - def sign_cancel_all_orders(self, time_in_force, time, nonce=-1): - self.signer.SignCancelAllOrders.argtypes = [ - ctypes.c_int, - ctypes.c_longlong, - ctypes.c_longlong, - ] - self.signer.SignCancelAllOrders.restype = StrOrErr + return self.__decode_tx_info(self.signer.SignCreateGroupedOrders( + grouping_type, orders_arr, len(orders), nonce, api_key_index, self.account_index + )) - result = self.signer.SignCancelAllOrders(time_in_force, time, nonce) + def sign_cancel_order(self, market_index: int, order_index: int, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_tx_info(self.signer.SignCancelOrder(market_index, order_index, nonce, api_key_index, self.account_index)) - tx_info = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None + def sign_withdraw(self, asset_index: int, route_type: int, amount: int, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_tx_info(self.signer.SignWithdraw(asset_index, route_type, amount, nonce, api_key_index, self.account_index)) - return tx_info, error + def sign_create_sub_account(self, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_tx_info(self.signer.SignCreateSubAccount(nonce, api_key_index, self.account_index)) - def sign_modify_order(self, market_index, order_index, base_amount, price, trigger_price, nonce=-1): - self.signer.SignModifyOrder.argtypes = [ - ctypes.c_int, - ctypes.c_longlong, - ctypes.c_longlong, - ctypes.c_longlong, - ctypes.c_longlong, - ctypes.c_longlong, - ] - self.signer.SignModifyOrder.restype = StrOrErr + def sign_cancel_all_orders(self, time_in_force: int, timestamp_ms: int, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_tx_info(self.signer.SignCancelAllOrders(time_in_force, timestamp_ms, nonce, api_key_index, self.account_index)) - result = self.signer.SignModifyOrder(market_index, order_index, base_amount, price, trigger_price, nonce) + def sign_modify_order(self, market_index: int, order_index: int, base_amount: int, price: int, trigger_price: int = NIL_TRIGGER_PRICE, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_tx_info(self.signer.SignModifyOrder(market_index, order_index, base_amount, price, trigger_price, nonce, api_key_index, self.account_index)) - tx_info = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None + def sign_transfer(self, eth_private_key: str, to_account_index: int, asset_id: int, route_from: int, route_to: int, usdc_amount: int, fee: int, memo: str, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_and_sign_tx_info(eth_private_key, self.signer.SignTransfer(to_account_index, asset_id, route_from, route_to, usdc_amount, fee, ctypes.c_char_p(memo.encode("utf-8")), nonce, api_key_index, self.account_index)) - return tx_info, error - - def sign_transfer(self, eth_private_key, to_account_index, usdc_amount, fee, memo, nonce=-1): - self.signer.SignTransfer.argtypes = [ - ctypes.c_longlong, - ctypes.c_longlong, - ctypes.c_longlong, - ctypes.c_char_p, - ctypes.c_longlong, - ] - self.signer.SignTransfer.restype = StrOrErr - result = self.signer.SignTransfer(to_account_index, usdc_amount, fee, ctypes.c_char_p(memo.encode("utf-8")), nonce) - - tx_info_str = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None + def sign_transfer_same_master_account(self, to_account_index: int, asset_id: int, route_from: int, route_to: int, usdc_amount: int, fee: int, memo: str, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_tx_info(self.signer.SignTransfer(to_account_index, asset_id, route_from, route_to, usdc_amount, fee, ctypes.c_char_p(memo.encode("utf-8")), nonce, api_key_index, self.account_index)) - if error: - return tx_info_str, error - - # fetch message to sign - tx_info = json.loads(tx_info_str) - msg_to_sign = tx_info["MessageToSign"] - del tx_info["MessageToSign"] + def sign_create_public_pool(self, operator_fee: int, initial_total_shares: int, min_operator_share_rate: int, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_tx_info(self.signer.SignCreatePublicPool(operator_fee, initial_total_shares, min_operator_share_rate, nonce, api_key_index, self.account_index)) - # sign the message - acct = Account.from_key(eth_private_key) - message = encode_defunct(text=msg_to_sign) - signature = acct.sign_message(message) - tx_info["L1Sig"] = signature.signature.to_0x_hex() - return json.dumps(tx_info), None + def sign_update_public_pool(self, public_pool_index: int, status: int, operator_fee: int, min_operator_share_rate: int, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_tx_info(self.signer.SignUpdatePublicPool(public_pool_index, status, operator_fee, min_operator_share_rate, nonce, api_key_index, self.account_index)) - def sign_create_public_pool(self, operator_fee, initial_total_shares, min_operator_share_rate, nonce=-1): - self.signer.SignCreatePublicPool.argtypes = [ - ctypes.c_longlong, - ctypes.c_longlong, - ctypes.c_longlong, - ctypes.c_longlong, - ] - self.signer.SignCreatePublicPool.restype = StrOrErr - - result = self.signer.SignCreatePublicPool(operator_fee, initial_total_shares, min_operator_share_rate, nonce) - - tx_info = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None - - return tx_info, error - - def sign_update_public_pool(self, public_pool_index, status, operator_fee, min_operator_share_rate, nonce=-1): - self.signer.SignUpdatePublicPool.argtypes = [ - ctypes.c_longlong, - ctypes.c_int, - ctypes.c_longlong, - ctypes.c_longlong, - ctypes.c_longlong, - ] - self.signer.SignUpdatePublicPool.restype = StrOrErr - - result = self.signer.SignUpdatePublicPool( - public_pool_index, status, operator_fee, min_operator_share_rate, nonce - ) - - tx_info = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None - - return tx_info, error - - def sign_mint_shares(self, public_pool_index, share_amount, nonce=-1): - self.signer.SignMintShares.argtypes = [ - ctypes.c_longlong, - ctypes.c_longlong, - ctypes.c_longlong, - ] - self.signer.SignMintShares.restype = StrOrErr - - result = self.signer.SignMintShares(public_pool_index, share_amount, nonce) - - tx_info = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None - - return tx_info, error - - def sign_burn_shares(self, public_pool_index, share_amount, nonce=-1): - self.signer.SignBurnShares.argtypes = [ - ctypes.c_longlong, - ctypes.c_longlong, - ctypes.c_longlong, - ] - self.signer.SignBurnShares.restype = StrOrErr - - result = self.signer.SignBurnShares(public_pool_index, share_amount, nonce) - - tx_info = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None - - return tx_info, error - - def sign_update_leverage(self, market_index, fraction, margin_mode, nonce=-1): - self.signer.SignUpdateLeverage.argtypes = [ - ctypes.c_int, - ctypes.c_int, - ctypes.c_int, - ctypes.c_longlong, - ] - self.signer.SignUpdateLeverage.restype = StrOrErr - result = self.signer.SignUpdateLeverage(market_index, fraction, margin_mode, nonce) - - tx_info = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None - return tx_info, error - - def create_auth_token_with_expiry(self, deadline: int = DEFAULT_10_MIN_AUTH_EXPIRY): - if deadline == SignerClient.DEFAULT_10_MIN_AUTH_EXPIRY: - deadline = int(time.time() + 10 * SignerClient.MINUTE) - self.signer.CreateAuthToken.argtypes = [ctypes.c_longlong] - self.signer.CreateAuthToken.restype = StrOrErr - result = self.signer.CreateAuthToken(deadline) - - auth = result.str.decode("utf-8") if result.str else None - error = result.err.decode("utf-8") if result.err else None - return auth, error + def sign_mint_shares(self, public_pool_index: int, share_amount: int, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_tx_info(self.signer.SignMintShares(public_pool_index, share_amount, nonce, api_key_index, self.account_index)) - async def change_api_key(self, eth_private_key: str, new_pubkey: str, nonce=-1): - tx_info, error = self.sign_change_api_key(eth_private_key, new_pubkey, nonce) - if error is not None: - return None, error + def sign_burn_shares(self, public_pool_index: int, share_amount: int, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_tx_info(self.signer.SignBurnShares(public_pool_index, share_amount, nonce, api_key_index, self.account_index)) - logging.debug(f"Change Pub Key Tx Info: {tx_info}") + def sign_update_leverage(self, market_index: int, fraction: int, margin_mode: int, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_tx_info(self.signer.SignUpdateLeverage(market_index, fraction, margin_mode, nonce, api_key_index, self.account_index)) - api_response = await self.send_tx(tx_type=self.TX_TYPE_CHANGE_PUB_KEY, tx_info=tx_info) - logging.debug(f"Change Pub Key Send Tx Response: {api_response}") - return api_response, None + def sign_update_margin(self, market_index: int, usdc_amount: int, direction: int, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[str, str, str, None], Tuple[None, None, None, str]]: + return self.__decode_tx_info(self.signer.SignUpdateMargin(market_index, usdc_amount, direction, nonce, api_key_index, self.account_index)) @process_api_key_and_nonce async def create_order( - self, - market_index, - client_order_index, - base_amount, - price, - is_ask, - order_type, - time_in_force, - reduce_only=False, - trigger_price=NIL_TRIGGER_PRICE, - order_expiry=DEFAULT_28_DAY_ORDER_EXPIRY, - nonce=-1, - api_key_index=-1, - ) -> (CreateOrder, TxHash, str): - tx_info, error = self.sign_create_order( + self, + market_index, + client_order_index, + base_amount, + price, + is_ask, + order_type, + time_in_force, + reduce_only=False, + trigger_price=NIL_TRIGGER_PRICE, + order_expiry=DEFAULT_28_DAY_ORDER_EXPIRY, + nonce: int = DEFAULT_NONCE, + api_key_index: int = DEFAULT_API_KEY_INDEX + ) -> Union[Tuple[CreateOrder, RespSendTx, None], Tuple[None, None, str]]: + tx_type, tx_info, tx_hash, error = self.sign_create_order( market_index, client_order_index, base_amount, @@ -621,51 +534,53 @@ async def create_order( int(is_ask), order_type, time_in_force, - int(reduce_only), + reduce_only, trigger_price, order_expiry, nonce, + api_key_index, ) if error is not None: return None, None, error - logging.debug(f"Create Order Tx Info: {tx_info}") - api_response = await self.send_tx(tx_type=self.TX_TYPE_CREATE_ORDER, tx_info=tx_info) - logging.debug(f"Create Order Send Tx Response: {api_response}") + logging.debug(f"Create Order TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Create Order Send. TxResponse: {api_response}") return CreateOrder.from_json(tx_info), api_response, None @process_api_key_and_nonce async def create_grouped_orders( - self, - grouping_type: int, - orders: List[CreateOrderTxReq], - nonce=-1, - api_key_index=-1, - ) -> (CreateGroupedOrders, TxHash, str): - tx_info, error = self.sign_create_grouped_orders( + self, + grouping_type: int, + orders: List[CreateOrderTxReq], + nonce: int = DEFAULT_NONCE, + api_key_index: int = DEFAULT_API_KEY_INDEX + ) ->Union[Tuple[CreateGroupedOrders, RespSendTx, None], Tuple[None, None, str]]: + tx_type, tx_info, tx_hash, error = self.sign_create_grouped_orders( grouping_type, orders, nonce, + api_key_index ) if error is not None: return None, None, error - logging.debug(f"Create Grouped Orders Tx Info: {tx_info}") - api_response = await self.send_tx(tx_type=self.TX_TYPE_CREATE_GROUP_ORDER, tx_info=tx_info) - logging.debug(f"Create Grouped Orders Send Tx Response: {api_response}") + logging.debug(f"Create Grouped Orders TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Create Grouped Orders Send. TxResponse: {api_response}") return CreateGroupedOrders.from_json(tx_info), api_response, None async def create_market_order( - self, - market_index, - client_order_index, - base_amount, - avg_execution_price, - is_ask, - reduce_only: bool = False, - nonce=-1, - api_key_index=-1, - ) -> (CreateOrder, TxHash, str): + self, + market_index, + client_order_index, + base_amount, + avg_execution_price, + is_ask, + reduce_only: bool = False, + nonce: int = DEFAULT_NONCE, + api_key_index: int = DEFAULT_API_KEY_INDEX + ) -> Union[Tuple[CreateOrder, RespSendTx, None], Tuple[None, None, str]]: return await self.create_order( market_index, client_order_index, @@ -682,20 +597,21 @@ async def create_market_order( # will only do the amount such that the slippage is limited to the value provided async def create_market_order_limited_slippage( - self, - market_index, - client_order_index, - base_amount, - max_slippage, - is_ask, - reduce_only: bool = False, - nonce=-1, - api_key_index=-1, - ideal_price=None - ) -> (CreateOrder, TxHash, str): + self, + market_index, + client_order_index, + base_amount, + max_slippage, + is_ask, + reduce_only: bool = False, + nonce: int = DEFAULT_NONCE, + api_key_index: int = DEFAULT_API_KEY_INDEX, + ideal_price=None + ) -> Union[Tuple[CreateOrder, RespSendTx, None], Tuple[None, None, str]]: if ideal_price is None: order_book_orders = await self.order_api.order_book_orders(market_index, 1) - logging.debug("Create market order limited slippage is doing an API call to get the current ideal price. You can also provide it yourself to avoid this.") + logging.debug( + "Create market order limited slippage is doing an API call to get the current ideal price. You can also provide it yourself to avoid this.") ideal_price = int((order_book_orders.bids[0].price if is_ask else order_book_orders.asks[0].price).replace(".", "")) acceptable_execution_price = round(ideal_price * (1 + max_slippage * (-1 if is_ask else 1))) @@ -715,17 +631,17 @@ async def create_market_order_limited_slippage( # will only execute the order if it executes with slippage <= max_slippage async def create_market_order_if_slippage( - self, - market_index, - client_order_index, - base_amount, - max_slippage, - is_ask, - reduce_only: bool = False, - nonce=-1, - api_key_index=-1, - ideal_price=None - ) -> (CreateOrder, TxHash, str): + self, + market_index, + client_order_index, + base_amount, + max_slippage, + is_ask, + reduce_only: bool = False, + nonce: int = DEFAULT_NONCE, + api_key_index: int = DEFAULT_API_KEY_INDEX, + ideal_price=None + ) -> Union[Tuple[CreateOrder, RespSendTx, None], Tuple[None, None, str]]: order_book_orders = await self.order_api.order_book_orders(market_index, 100) if ideal_price is None: ideal_price = int((order_book_orders.bids[0].price if is_ask else order_book_orders.asks[0].price).replace(".", "")) @@ -763,17 +679,22 @@ async def create_market_order_if_slippage( ) @process_api_key_and_nonce - async def cancel_order(self, market_index, order_index, nonce=-1, api_key_index=-1) -> (CancelOrder, TxHash, str): - tx_info, error = self.sign_cancel_order(market_index, order_index, nonce) + async def cancel_order(self, market_index, order_index, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX + ) -> Union[Tuple[CancelOrder, RespSendTx, None], Tuple[None, None, str]]: + tx_type, tx_info, tx_hash, error = self.sign_cancel_order(market_index, order_index, nonce, api_key_index) + if error is not None: return None, None, error - logging.debug(f"Cancel Order Tx Info: {tx_info}") - api_response = await self.send_tx(tx_type=self.TX_TYPE_CANCEL_ORDER, tx_info=tx_info) - logging.debug(f"Cancel Order Send Tx Response: {api_response}") + logging.debug(f"Cancel Order TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Cancel Order Send. TxResponse: {api_response}") return CancelOrder.from_json(tx_info), api_response, None - async def create_tp_order(self, market_index, client_order_index, base_amount, trigger_price, price, is_ask, reduce_only=False, nonce=-1, api_key_index=-1) -> (CreateOrder, TxHash, str): + async def create_tp_order(self, market_index, client_order_index, base_amount, trigger_price, price, is_ask, reduce_only=False, + nonce: int = DEFAULT_NONCE, + api_key_index: int = DEFAULT_API_KEY_INDEX + ) -> Union[Tuple[CreateOrder, RespSendTx, None], Tuple[None, None, str]]: return await self.create_order( market_index, client_order_index, @@ -786,10 +707,13 @@ async def create_tp_order(self, market_index, client_order_index, base_amount, t trigger_price, self.DEFAULT_28_DAY_ORDER_EXPIRY, nonce, - api_key_index=api_key_index, + api_key_index, ) - async def create_tp_limit_order(self, market_index, client_order_index, base_amount, trigger_price, price, is_ask, reduce_only=False, nonce=-1, api_key_index=-1) -> (CreateOrder, TxHash, str): + async def create_tp_limit_order(self, market_index, client_order_index, base_amount, trigger_price, price, is_ask, reduce_only=False, + nonce: int = DEFAULT_NONCE, + api_key_index: int = DEFAULT_API_KEY_INDEX + ) -> Union[Tuple[CreateOrder, RespSendTx, None], Tuple[None, None, str]]: return await self.create_order( market_index, client_order_index, @@ -805,7 +729,10 @@ async def create_tp_limit_order(self, market_index, client_order_index, base_amo api_key_index, ) - async def create_sl_order(self, market_index, client_order_index, base_amount, trigger_price, price, is_ask, reduce_only=False, nonce=-1, api_key_index=-1) -> (CreateOrder, TxHash, str): + async def create_sl_order(self, market_index, client_order_index, base_amount, trigger_price, price, is_ask, reduce_only=False, + nonce: int = DEFAULT_NONCE, + api_key_index: int = DEFAULT_API_KEY_INDEX + ) -> Union[Tuple[CreateOrder, RespSendTx, None], Tuple[None, None, str]]: return await self.create_order( market_index, client_order_index, @@ -818,10 +745,13 @@ async def create_sl_order(self, market_index, client_order_index, base_amount, t trigger_price, self.DEFAULT_28_DAY_ORDER_EXPIRY, nonce, - api_key_index=api_key_index, + api_key_index, ) - async def create_sl_limit_order(self, market_index, client_order_index, base_amount, trigger_price, price, is_ask, reduce_only=False, nonce=-1, api_key_index=-1) -> (CreateOrder, TxHash, str): + async def create_sl_limit_order(self, market_index, client_order_index, base_amount, trigger_price, price, is_ask, reduce_only=False, + nonce: int = DEFAULT_NONCE, + api_key_index: int = DEFAULT_API_KEY_INDEX + ) -> Union[Tuple[CreateOrder, RespSendTx, None], Tuple[None, None, str]]: return await self.create_order( market_index, client_order_index, @@ -838,136 +768,181 @@ async def create_sl_limit_order(self, market_index, client_order_index, base_amo ) @process_api_key_and_nonce - async def withdraw(self, usdc_amount, nonce=-1, api_key_index=-1) -> (Withdraw, TxHash): - usdc_amount = int(usdc_amount * self.USDC_TICKER_SCALE) + async def withdraw(self, asset_id: int, route_type: int, amount: float, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX) -> Union[Tuple[Withdraw, RespSendTx, None], Tuple[None, None, str]]: + if asset_id in self.ASSET_TO_TICKER_SCALE: + amount = int(amount * self.ASSET_TO_TICKER_SCALE[asset_id]) + else: + raise ValueError(f"Unsupported asset id: {asset_id}") - tx_info, error = self.sign_withdraw(usdc_amount, nonce) + tx_type, tx_info, tx_hash, error = self.sign_withdraw(asset_id, route_type, amount, nonce, api_key_index) if error is not None: return None, None, error - logging.debug(f"Withdraw Tx Info: {tx_info}") - api_response = await self.send_tx(tx_type=self.TX_TYPE_WITHDRAW, tx_info=tx_info) - logging.debug(f"Withdraw Send Tx Response: {api_response}") + logging.debug(f"Withdraw TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Withdraw Send. TxResponse: {api_response}") return Withdraw.from_json(tx_info), api_response, None - async def create_sub_account(self, nonce=-1): - tx_info, error = self.sign_create_sub_account(nonce) + @process_api_key_and_nonce + async def create_sub_account(self, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX): + tx_type, tx_info, tx_hash, error = self.sign_create_sub_account(nonce, api_key_index) if error is not None: return None, None, error - logging.debug(f"Create Sub Account Tx Info: {tx_info}") - api_response = await self.send_tx(tx_type=self.TX_TYPE_CREATE_SUB_ACCOUNT, tx_info=tx_info) - logging.debug(f"Create Sub Account Send Tx Response: {api_response}") + logging.debug(f"Create Sub Account TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Create Sub Account Send. TxResponse: {api_response}") return tx_info, api_response, None @process_api_key_and_nonce - async def cancel_all_orders(self, time_in_force, time, nonce=-1, api_key_index=-1): - tx_info, error = self.sign_cancel_all_orders(time_in_force, time, nonce) + async def cancel_all_orders(self, time_in_force, timestamp_ms, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX)-> Union[Tuple[Withdraw, RespSendTx, None], Tuple[None, None, str]]: + tx_type, tx_info, tx_hash, error = self.sign_cancel_all_orders(time_in_force, timestamp_ms, nonce, api_key_index) if error is not None: return None, None, error - logging.debug(f"Cancel All Orders Tx Info: {tx_info}") - api_response = await self.send_tx(tx_type=self.TX_TYPE_CANCEL_ALL_ORDERS, tx_info=tx_info) - logging.debug(f"Cancel All Orders Send Tx Response: {api_response}") + logging.debug(f"Cancel All Orders TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Cancel All Orders Send. TxResponse: {api_response}") return tx_info, api_response, None @process_api_key_and_nonce async def modify_order( - self, market_index, order_index, base_amount, price, trigger_price, nonce=-1, api_key_index=-1 + self, market_index, order_index, base_amount, price, trigger_price=NIL_TRIGGER_PRICE, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX ): - tx_info, error = self.sign_modify_order(market_index, order_index, base_amount, price, trigger_price, nonce) + tx_type, tx_info, tx_hash, error = self.sign_modify_order(market_index, order_index, base_amount, price, trigger_price, nonce, api_key_index) if error is not None: return None, None, error - logging.debug(f"Modify Order Tx Info: {tx_info}") - api_response = await self.send_tx(tx_type=self.TX_TYPE_MODIFY_ORDER, tx_info=tx_info) - logging.debug(f"Modify Order Send Tx Response: {api_response}") + logging.debug(f"Modify Order TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Modify Order Send. TxResponse: {api_response}") return tx_info, api_response, None @process_api_key_and_nonce - async def transfer(self, eth_private_key: str, to_account_index, usdc_amount, fee, memo, nonce=-1, api_key_index=-1): - usdc_amount = int(usdc_amount * self.USDC_TICKER_SCALE) + async def transfer(self, eth_private_key: str, to_account_index: int, asset_id: int, route_from: int, route_to: int, amount: float, fee: int, memo: str, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX): + if asset_id in self.ASSET_TO_TICKER_SCALE: + amount = int(amount * self.ASSET_TO_TICKER_SCALE[asset_id]) + else: + raise ValueError(f"Unsupported asset id: {asset_id}") - tx_info, error = self.sign_transfer(eth_private_key, to_account_index, usdc_amount, fee, memo, nonce) + tx_type, tx_info, tx_hash, error = self.sign_transfer(eth_private_key, to_account_index, asset_id, route_from, route_to, amount, fee, memo, nonce, api_key_index) if error is not None: return None, None, error - logging.debug(f"Transfer Tx Info: {tx_info}") - api_response = await self.send_tx(tx_type=self.TX_TYPE_TRANSFER, tx_info=tx_info) - logging.debug(f"Transfer Send Tx Response: {api_response}") + logging.debug(f"Transfer TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Transfer Send. TxResponse: {api_response}") + return tx_info, api_response, None + + @process_api_key_and_nonce + async def transfer_same_master_account(self, to_account_index: int, asset_id: int, route_from: int, route_to: int, amount: float, fee: int, memo: str, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX): + if asset_id in self.ASSET_TO_TICKER_SCALE: + amount = int(amount * self.ASSET_TO_TICKER_SCALE[asset_id]) + else: + raise ValueError(f"Unsupported asset id: {asset_id}") + + tx_type, tx_info, tx_hash, error = self.sign_transfer_same_master_account(to_account_index, asset_id, route_from, route_to, amount, fee, memo, nonce, api_key_index) + if error is not None: + return None, None, error + + logging.debug(f"Transfer TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Transfer Send. TxResponse: {api_response}") return tx_info, api_response, None @process_api_key_and_nonce async def create_public_pool( - self, operator_fee, initial_total_shares, min_operator_share_rate, nonce=-1, api_key_index=-1 + self, operator_fee, initial_total_shares, min_operator_share_rate, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX ): - tx_info, error = self.sign_create_public_pool( - operator_fee, initial_total_shares, min_operator_share_rate, nonce + tx_type, tx_info, tx_hash, error = self.sign_create_public_pool( + operator_fee, initial_total_shares, min_operator_share_rate, nonce, api_key_index ) if error is not None: return None, None, error - logging.debug(f"Create Public Pool Tx Info: {tx_info}") - api_response = await self.send_tx(tx_type=self.TX_TYPE_CREATE_PUBLIC_POOL, tx_info=tx_info) - logging.debug(f"Create Public Pool Send Tx Response: {api_response}") + logging.debug(f"Create Public Pool TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Create Public Pool Send. TxResponse: {api_response}") return tx_info, api_response, None @process_api_key_and_nonce async def update_public_pool( - self, public_pool_index, status, operator_fee, min_operator_share_rate, nonce=-1, api_key_index=-1 + self, public_pool_index, status, operator_fee, min_operator_share_rate, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX ): - tx_info, error = self.sign_update_public_pool( - public_pool_index, status, operator_fee, min_operator_share_rate, nonce + tx_type, tx_info, tx_hash, error = self.sign_update_public_pool( + public_pool_index, status, operator_fee, min_operator_share_rate, nonce, api_key_index ) if error is not None: return None, None, error - logging.debug(f"Update Public Pool Tx Info: {tx_info}") - api_response = await self.send_tx(tx_type=self.TX_TYPE_UPDATE_PUBLIC_POOL, tx_info=tx_info) - logging.debug(f"Update Public Pool Send Tx Response: {api_response}") + logging.debug(f"Update Public Pool TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Update Public Pool Send. TxResponse: {api_response}") return tx_info, api_response, None @process_api_key_and_nonce - async def mint_shares(self, public_pool_index, share_amount, nonce=-1, api_key_index=-1): - tx_info, error = self.sign_mint_shares(public_pool_index, share_amount, nonce) + async def mint_shares(self, public_pool_index, share_amount, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX): + tx_type, tx_info, tx_hash, error = self.sign_mint_shares(public_pool_index, share_amount, nonce, api_key_index) if error is not None: return None, None, error - logging.debug(f"Mint Shares Tx Info: {tx_info}") - api_response = await self.send_tx(tx_type=self.TX_TYPE_MINT_SHARES, tx_info=tx_info) - logging.debug(f"Mint Shares Send Tx Response: {api_response}") + logging.debug(f"Mint Shares TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Mint Shares Send. TxResponse: {api_response}") return tx_info, api_response, None @process_api_key_and_nonce - async def burn_shares(self, public_pool_index, share_amount, nonce=-1, api_key_index=-1): - tx_info, error = self.sign_burn_shares(public_pool_index, share_amount, nonce) + async def burn_shares(self, public_pool_index, share_amount, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX): + tx_type, tx_info, tx_hash, error = self.sign_burn_shares(public_pool_index, share_amount, nonce, api_key_index) if error is not None: return None, None, error - logging.debug(f"Burn Shares Tx Info: {tx_info}") - api_response = await self.send_tx(tx_type=self.TX_TYPE_BURN_SHARES, tx_info=tx_info) - logging.debug(f"Burn Shares Send Tx Response: {api_response}") + logging.debug(f"Burn Shares TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Burn Shares Send. TxResponse: {api_response}") return tx_info, api_response, None - + @process_api_key_and_nonce - async def update_leverage(self, market_index, margin_mode, leverage, nonce=-1, api_key_index=-1): + async def update_leverage(self, market_index, margin_mode, leverage, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX): imf = int(10_000 / leverage) - tx_info, error = self.sign_update_leverage(market_index, imf, margin_mode, nonce) + tx_type, tx_info, tx_hash, error = self.sign_update_leverage(market_index, imf, margin_mode, nonce, api_key_index) if error is not None: return None, None, error - logging.debug(f"Update Leverage Tx Info: {tx_info}") - api_response = await self.send_tx(tx_type=self.TX_TYPE_UPDATE_LEVERAGE, tx_info=tx_info) + logging.debug(f"Update Leverage TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) logging.debug(f"Update Leverage Tx Response: {api_response}") return tx_info, api_response, None + @process_api_key_and_nonce + async def update_margin(self, market_index: int, usdc_amount: float, direction: int, nonce: int = DEFAULT_NONCE, api_key_index: int = DEFAULT_API_KEY_INDEX): + usdc_amount = int(usdc_amount * self.USDC_TICKER_SCALE) + tx_type, tx_info, tx_hash, error = self.sign_update_margin(market_index, usdc_amount, direction, nonce, api_key_index) + + if error is not None: + return None, None, error + + logging.debug(f"Update Margin TxHash: {tx_hash} TxInfo: {tx_info}") + api_response = await self.send_tx(tx_type=tx_type, tx_info=tx_info) + logging.debug(f"Update Margin Tx Response: {api_response}") + return tx_info, api_response, None async def send_tx(self, tx_type: StrictInt, tx_info: str) -> RespSendTx: if tx_info[0] != "{": raise Exception(tx_info) return await self.tx_api.send_tx(tx_type=tx_type, tx_info=tx_info) + async def send_tx_batch(self, tx_types: List[StrictInt], tx_infos: List[str]) -> RespSendTxBatch: + if len(tx_types) != len(tx_infos): + raise Exception("Tx types and tx infos must be of same length") + if len(tx_types) == 0: + raise Exception("Empty tx types and tx infos") + + if tx_infos[0][0] != "{": + raise Exception(tx_infos) + return await self.tx_api.send_tx_batch(tx_types=json.dumps(tx_types), tx_infos=json.dumps(tx_infos)) + async def close(self): await self.api_client.close() diff --git a/lighter/signers/README.md b/lighter/signers/README.md index f5295bb..3408e2a 100644 --- a/lighter/signers/README.md +++ b/lighter/signers/README.md @@ -2,56 +2,24 @@ This directory contains various signer implementations for the Lighter Protocol. -## Available Signers - -### Native Binary Signers - -- `signer-amd64.so` - Linux AMD64 native signer -- `signer-arm64.dylib` - macOS ARM64 native signer -- `signer-amd64.dll` - Windows AMD64 native signer - -These binaries are compiled from the Go implementation in [lighter-go](https://github.com/elliottech/lighter-go) and -provide high-performance cryptographic operations for the Lighter Protocol. - ## Usage The Python SDK automatically selects the correct native binary signer based on your platform: -- ✅ **Linux (x86_64)**: Uses `signer-amd64.so` -- ✅ **macOS (ARM64)**: Uses `signer-arm64.dylib` -- ✅ **Windows (x86_64)**: Uses `signer-amd64.dll` - -No additional configuration is required - the SDK detects your platform and loads the appropriate signer. - -## Building Signers -All native signers are built from the Go implementation in [lighter-go](https://github.com/elliottech/lighter-go). +| Platform | Architecture | Binary | +|----------|-----------------------|-------------------------------------| +| Linux | x86_64 | `lighter-signer-linux-amd64.so` | +| Linux | ARM64 | `lighter-signer-linux-amd64.so` | +| macOS | ARM64 (Apple Silicon) | `lighter-signer-darwin-arm64.dylib` | +| Windows | x86_64 | `lighter-signer-windows-amd64.dll` | -To build signers locally,Import lighter-go repo: +No additional configuration is required - the SDK detects your platform and loads the appropriate signer. \ +If you encounter issues with missing binaries, ensure the appropriate signer binary is present in this directory. -```bash -# From lighter-go/ directory -just build-linux-local # Linux AMD64 -just build-darwin-local # macOS ARM64 -just build-windows-local # Windows AMD64 -``` - -Or use Docker for cross-compilation: - -```bash -just build-linux-docker -just build-windows-docker -``` - -## Supported Platforms - -The Python SDK supports the following platforms out of the box: - -| Platform | Architecture | Binary | -|----------|-----------------------|----------------------| -| Linux | x86_64 | `signer-amd64.so` | -| macOS | ARM64 (Apple Silicon) | `signer-arm64.dylib` | -| Windows | x86_64 | `signer-amd64.dll` | +## Building Signers -If you encounter issues with missing binaries, ensure the appropriate signer binary is present in this directory. You -can build it from `lighter-go/` using the commands above. \ No newline at end of file +These binaries are compiled from the Go implementation in [lighter-go](https://github.com/elliottech/lighter-go) and +provide high-performance cryptographic operations for the Lighter Protocol. \ +There are `.h` files for easier integrations in other languages, like C, C++, Rust. \ +For building the signers yourself, you can find the steps in the lighter-go repo. diff --git a/lighter/signers/lighter-signer-darwin-arm64.dylib b/lighter/signers/lighter-signer-darwin-arm64.dylib new file mode 100644 index 0000000..cb267ad Binary files /dev/null and b/lighter/signers/lighter-signer-darwin-arm64.dylib differ diff --git a/lighter/signers/lighter-signer-darwin-arm64.h b/lighter/signers/lighter-signer-darwin-arm64.h new file mode 100644 index 0000000..307323c --- /dev/null +++ b/lighter/signers/lighter-signer-darwin-arm64.h @@ -0,0 +1,136 @@ +/* Code generated by cmd/cgo; DO NOT EDIT. */ + +/* package command-line-arguments */ + + +#line 1 "cgo-builtin-export-prolog" + +#include + +#ifndef GO_CGO_EXPORT_PROLOGUE_H +#define GO_CGO_EXPORT_PROLOGUE_H + +#ifndef GO_CGO_GOSTRING_TYPEDEF +typedef struct { const char *p; ptrdiff_t n; } _GoString_; +#endif + +#endif + +/* Start of preamble from import "C" comments. */ + + +#line 16 "main.go" + +#include +#include +typedef struct { + char* str; + char* err; +} StrOrErr; + +typedef struct { + uint8_t txType; + char* txInfo; + char* txHash; + char* messageToSign; + char* err; +} SignedTxResponse; + +typedef struct { + char* privateKey; + char* publicKey; + char* err; +} ApiKeyResponse; + +typedef struct { + uint8_t MarketIndex; + int64_t ClientOrderIndex; + int64_t BaseAmount; + uint32_t Price; + uint8_t IsAsk; + uint8_t Type; + uint8_t TimeInForce; + uint8_t ReduceOnly; + uint32_t TriggerPrice; + int64_t OrderExpiry; +} CreateOrderTxReq; + +#line 1 "cgo-generated-wrapper" + + +/* End of preamble from import "C" comments. */ + + +/* Start of boilerplate cgo prologue. */ +#line 1 "cgo-gcc-export-header-prolog" + +#ifndef GO_CGO_PROLOGUE_H +#define GO_CGO_PROLOGUE_H + +typedef signed char GoInt8; +typedef unsigned char GoUint8; +typedef short GoInt16; +typedef unsigned short GoUint16; +typedef int GoInt32; +typedef unsigned int GoUint32; +typedef long long GoInt64; +typedef unsigned long long GoUint64; +typedef GoInt64 GoInt; +typedef GoUint64 GoUint; +typedef size_t GoUintptr; +typedef float GoFloat32; +typedef double GoFloat64; +#ifdef _MSC_VER +#include +typedef _Fcomplex GoComplex64; +typedef _Dcomplex GoComplex128; +#else +typedef float _Complex GoComplex64; +typedef double _Complex GoComplex128; +#endif + +/* + static assertion to make sure the file is being used on architecture + at least with matching size of GoInt. +*/ +typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1]; + +#ifndef GO_CGO_GOSTRING_TYPEDEF +typedef _GoString_ GoString; +#endif +typedef void *GoMap; +typedef void *GoChan; +typedef struct { void *t; void *v; } GoInterface; +typedef struct { void *data; GoInt len; GoInt cap; } GoSlice; + +#endif + +/* End of boilerplate cgo prologue. */ + +#ifdef __cplusplus +extern "C" { +#endif + +extern ApiKeyResponse GenerateAPIKey(); +extern char* CreateClient(char* cUrl, char* cPrivateKey, int cChainId, int cApiKeyIndex, long long cAccountIndex); +extern char* CheckClient(int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignChangePubKey(char* cPubKey, long long cNonce, int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignCreateOrder(int cMarketIndex, long long cClientOrderIndex, long long cBaseAmount, int cPrice, int cIsAsk, int cOrderType, int cTimeInForce, int cReduceOnly, int cTriggerPrice, long long cOrderExpiry, long long cNonce, int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignCreateGroupedOrders(uint8_t cGroupingType, CreateOrderTxReq* cOrders, int cLen, long long cNonce, int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignCancelOrder(int cMarketIndex, long long cOrderIndex, long long cNonce, int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignWithdraw(int cAssetIndex, int cRouteType, unsigned long long cAmount, long long cNonce, int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignCreateSubAccount(long long cNonce, int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignCancelAllOrders(int cTimeInForce, long long cTime, long long cNonce, int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignModifyOrder(int cMarketIndex, long long cIndex, long long cBaseAmount, long long cPrice, long long cTriggerPrice, long long cNonce, int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignTransfer(long long cToAccountIndex, int16_t cAssetIndex, uint8_t cFromRouteType, uint8_t cToRouteType, long long cAmount, long long cUsdcFee, char* cMemo, long long cNonce, int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignCreatePublicPool(long long cOperatorFee, int cInitialTotalShares, long long cMinOperatorShareRate, long long cNonce, int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignUpdatePublicPool(long long cPublicPoolIndex, int cStatus, long long cOperatorFee, int cMinOperatorShareRate, long long cNonce, int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignMintShares(long long cPublicPoolIndex, long long cShareAmount, long long cNonce, int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignBurnShares(long long cPublicPoolIndex, long long cShareAmount, long long cNonce, int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignUpdateLeverage(int cMarketIndex, int cInitialMarginFraction, int cMarginMode, long long cNonce, int cApiKeyIndex, long long cAccountIndex); +extern StrOrErr CreateAuthToken(long long cDeadline, int cApiKeyIndex, long long cAccountIndex); +extern SignedTxResponse SignUpdateMargin(int cMarketIndex, long long cUSDCAmount, int cDirection, long long cNonce, int cApiKeyIndex, long long cAccountIndex); + +#ifdef __cplusplus +} +#endif diff --git a/lighter/signers/lighter-signer-linux-amd64.h b/lighter/signers/lighter-signer-linux-amd64.h new file mode 100644 index 0000000..b097024 --- /dev/null +++ b/lighter/signers/lighter-signer-linux-amd64.h @@ -0,0 +1,136 @@ +/* Code generated by cmd/cgo; DO NOT EDIT. */ + +/* package github.com/elliottech/lighter-go/sharedlib */ + + +#line 1 "cgo-builtin-export-prolog" + +#include + +#ifndef GO_CGO_EXPORT_PROLOGUE_H +#define GO_CGO_EXPORT_PROLOGUE_H + +#ifndef GO_CGO_GOSTRING_TYPEDEF +typedef struct { const char *p; ptrdiff_t n; } _GoString_; +#endif + +#endif + +/* Start of preamble from import "C" comments. */ + + +#line 16 "main.go" + +#include +#include +typedef struct { + char* str; + char* err; +} StrOrErr; + +typedef struct { + uint8_t txType; + char* txInfo; + char* txHash; + char* messageToSign; + char* err; +} SignedTxResponse; + +typedef struct { + char* privateKey; + char* publicKey; + char* err; +} ApiKeyResponse; + +typedef struct { + uint8_t MarketIndex; + int64_t ClientOrderIndex; + int64_t BaseAmount; + uint32_t Price; + uint8_t IsAsk; + uint8_t Type; + uint8_t TimeInForce; + uint8_t ReduceOnly; + uint32_t TriggerPrice; + int64_t OrderExpiry; +} CreateOrderTxReq; + +#line 1 "cgo-generated-wrapper" + + +/* End of preamble from import "C" comments. */ + + +/* Start of boilerplate cgo prologue. */ +#line 1 "cgo-gcc-export-header-prolog" + +#ifndef GO_CGO_PROLOGUE_H +#define GO_CGO_PROLOGUE_H + +typedef signed char GoInt8; +typedef unsigned char GoUint8; +typedef short GoInt16; +typedef unsigned short GoUint16; +typedef int GoInt32; +typedef unsigned int GoUint32; +typedef long long GoInt64; +typedef unsigned long long GoUint64; +typedef GoInt64 GoInt; +typedef GoUint64 GoUint; +typedef size_t GoUintptr; +typedef float GoFloat32; +typedef double GoFloat64; +#ifdef _MSC_VER +#include +typedef _Fcomplex GoComplex64; +typedef _Dcomplex GoComplex128; +#else +typedef float _Complex GoComplex64; +typedef double _Complex GoComplex128; +#endif + +/* + static assertion to make sure the file is being used on architecture + at least with matching size of GoInt. +*/ +typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1]; + +#ifndef GO_CGO_GOSTRING_TYPEDEF +typedef _GoString_ GoString; +#endif +typedef void *GoMap; +typedef void *GoChan; +typedef struct { void *t; void *v; } GoInterface; +typedef struct { void *data; GoInt len; GoInt cap; } GoSlice; + +#endif + +/* End of boilerplate cgo prologue. */ + +#ifdef __cplusplus +extern "C" { +#endif + +extern ApiKeyResponse GenerateAPIKey(); +extern char* CreateClient(char* cUrl, char* cPrivateKey, int cChainId, int cApiKeyIndex, long long int cAccountIndex); +extern char* CheckClient(int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignChangePubKey(char* cPubKey, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignCreateOrder(int cMarketIndex, long long int cClientOrderIndex, long long int cBaseAmount, int cPrice, int cIsAsk, int cOrderType, int cTimeInForce, int cReduceOnly, int cTriggerPrice, long long int cOrderExpiry, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignCreateGroupedOrders(uint8_t cGroupingType, CreateOrderTxReq* cOrders, int cLen, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignCancelOrder(int cMarketIndex, long long int cOrderIndex, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignWithdraw(int cAssetIndex, int cRouteType, long long unsigned int cAmount, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignCreateSubAccount(long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignCancelAllOrders(int cTimeInForce, long long int cTime, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignModifyOrder(int cMarketIndex, long long int cIndex, long long int cBaseAmount, long long int cPrice, long long int cTriggerPrice, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignTransfer(long long int cToAccountIndex, int16_t cAssetIndex, uint8_t cFromRouteType, uint8_t cToRouteType, long long int cAmount, long long int cUsdcFee, char* cMemo, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignCreatePublicPool(long long int cOperatorFee, int cInitialTotalShares, long long int cMinOperatorShareRate, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignUpdatePublicPool(long long int cPublicPoolIndex, int cStatus, long long int cOperatorFee, int cMinOperatorShareRate, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignMintShares(long long int cPublicPoolIndex, long long int cShareAmount, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignBurnShares(long long int cPublicPoolIndex, long long int cShareAmount, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignUpdateLeverage(int cMarketIndex, int cInitialMarginFraction, int cMarginMode, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern StrOrErr CreateAuthToken(long long int cDeadline, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignUpdateMargin(int cMarketIndex, long long int cUSDCAmount, int cDirection, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); + +#ifdef __cplusplus +} +#endif diff --git a/lighter/signers/signer-amd64.so b/lighter/signers/lighter-signer-linux-amd64.so similarity index 54% rename from lighter/signers/signer-amd64.so rename to lighter/signers/lighter-signer-linux-amd64.so index 7e3a900..fa3f8c6 100644 Binary files a/lighter/signers/signer-amd64.so and b/lighter/signers/lighter-signer-linux-amd64.so differ diff --git a/lighter/signers/lighter-signer-linux-arm64.h b/lighter/signers/lighter-signer-linux-arm64.h new file mode 100644 index 0000000..b097024 --- /dev/null +++ b/lighter/signers/lighter-signer-linux-arm64.h @@ -0,0 +1,136 @@ +/* Code generated by cmd/cgo; DO NOT EDIT. */ + +/* package github.com/elliottech/lighter-go/sharedlib */ + + +#line 1 "cgo-builtin-export-prolog" + +#include + +#ifndef GO_CGO_EXPORT_PROLOGUE_H +#define GO_CGO_EXPORT_PROLOGUE_H + +#ifndef GO_CGO_GOSTRING_TYPEDEF +typedef struct { const char *p; ptrdiff_t n; } _GoString_; +#endif + +#endif + +/* Start of preamble from import "C" comments. */ + + +#line 16 "main.go" + +#include +#include +typedef struct { + char* str; + char* err; +} StrOrErr; + +typedef struct { + uint8_t txType; + char* txInfo; + char* txHash; + char* messageToSign; + char* err; +} SignedTxResponse; + +typedef struct { + char* privateKey; + char* publicKey; + char* err; +} ApiKeyResponse; + +typedef struct { + uint8_t MarketIndex; + int64_t ClientOrderIndex; + int64_t BaseAmount; + uint32_t Price; + uint8_t IsAsk; + uint8_t Type; + uint8_t TimeInForce; + uint8_t ReduceOnly; + uint32_t TriggerPrice; + int64_t OrderExpiry; +} CreateOrderTxReq; + +#line 1 "cgo-generated-wrapper" + + +/* End of preamble from import "C" comments. */ + + +/* Start of boilerplate cgo prologue. */ +#line 1 "cgo-gcc-export-header-prolog" + +#ifndef GO_CGO_PROLOGUE_H +#define GO_CGO_PROLOGUE_H + +typedef signed char GoInt8; +typedef unsigned char GoUint8; +typedef short GoInt16; +typedef unsigned short GoUint16; +typedef int GoInt32; +typedef unsigned int GoUint32; +typedef long long GoInt64; +typedef unsigned long long GoUint64; +typedef GoInt64 GoInt; +typedef GoUint64 GoUint; +typedef size_t GoUintptr; +typedef float GoFloat32; +typedef double GoFloat64; +#ifdef _MSC_VER +#include +typedef _Fcomplex GoComplex64; +typedef _Dcomplex GoComplex128; +#else +typedef float _Complex GoComplex64; +typedef double _Complex GoComplex128; +#endif + +/* + static assertion to make sure the file is being used on architecture + at least with matching size of GoInt. +*/ +typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1]; + +#ifndef GO_CGO_GOSTRING_TYPEDEF +typedef _GoString_ GoString; +#endif +typedef void *GoMap; +typedef void *GoChan; +typedef struct { void *t; void *v; } GoInterface; +typedef struct { void *data; GoInt len; GoInt cap; } GoSlice; + +#endif + +/* End of boilerplate cgo prologue. */ + +#ifdef __cplusplus +extern "C" { +#endif + +extern ApiKeyResponse GenerateAPIKey(); +extern char* CreateClient(char* cUrl, char* cPrivateKey, int cChainId, int cApiKeyIndex, long long int cAccountIndex); +extern char* CheckClient(int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignChangePubKey(char* cPubKey, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignCreateOrder(int cMarketIndex, long long int cClientOrderIndex, long long int cBaseAmount, int cPrice, int cIsAsk, int cOrderType, int cTimeInForce, int cReduceOnly, int cTriggerPrice, long long int cOrderExpiry, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignCreateGroupedOrders(uint8_t cGroupingType, CreateOrderTxReq* cOrders, int cLen, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignCancelOrder(int cMarketIndex, long long int cOrderIndex, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignWithdraw(int cAssetIndex, int cRouteType, long long unsigned int cAmount, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignCreateSubAccount(long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignCancelAllOrders(int cTimeInForce, long long int cTime, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignModifyOrder(int cMarketIndex, long long int cIndex, long long int cBaseAmount, long long int cPrice, long long int cTriggerPrice, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignTransfer(long long int cToAccountIndex, int16_t cAssetIndex, uint8_t cFromRouteType, uint8_t cToRouteType, long long int cAmount, long long int cUsdcFee, char* cMemo, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignCreatePublicPool(long long int cOperatorFee, int cInitialTotalShares, long long int cMinOperatorShareRate, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignUpdatePublicPool(long long int cPublicPoolIndex, int cStatus, long long int cOperatorFee, int cMinOperatorShareRate, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignMintShares(long long int cPublicPoolIndex, long long int cShareAmount, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignBurnShares(long long int cPublicPoolIndex, long long int cShareAmount, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignUpdateLeverage(int cMarketIndex, int cInitialMarginFraction, int cMarginMode, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern StrOrErr CreateAuthToken(long long int cDeadline, int cApiKeyIndex, long long int cAccountIndex); +extern SignedTxResponse SignUpdateMargin(int cMarketIndex, long long int cUSDCAmount, int cDirection, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); + +#ifdef __cplusplus +} +#endif diff --git a/lighter/signers/lighter-signer-linux-arm64.so b/lighter/signers/lighter-signer-linux-arm64.so new file mode 100644 index 0000000..d9254e8 Binary files /dev/null and b/lighter/signers/lighter-signer-linux-arm64.so differ diff --git a/lighter/signers/signer-amd64.dll b/lighter/signers/lighter-signer-windows-amd64.dll similarity index 62% rename from lighter/signers/signer-amd64.dll rename to lighter/signers/lighter-signer-windows-amd64.dll index fdf817a..9d1c2f4 100644 Binary files a/lighter/signers/signer-amd64.dll and b/lighter/signers/lighter-signer-windows-amd64.dll differ diff --git a/lighter/signers/lighter-signer-windows-amd64.h b/lighter/signers/lighter-signer-windows-amd64.h new file mode 100644 index 0000000..164e01c --- /dev/null +++ b/lighter/signers/lighter-signer-windows-amd64.h @@ -0,0 +1,136 @@ +/* Code generated by cmd/cgo; DO NOT EDIT. */ + +/* package github.com/elliottech/lighter-go/sharedlib */ + + +#line 1 "cgo-builtin-export-prolog" + +#include + +#ifndef GO_CGO_EXPORT_PROLOGUE_H +#define GO_CGO_EXPORT_PROLOGUE_H + +#ifndef GO_CGO_GOSTRING_TYPEDEF +typedef struct { const char *p; ptrdiff_t n; } _GoString_; +#endif + +#endif + +/* Start of preamble from import "C" comments. */ + + +#line 16 "main.go" + +#include +#include +typedef struct { + char* str; + char* err; +} StrOrErr; + +typedef struct { + uint8_t txType; + char* txInfo; + char* txHash; + char* messageToSign; + char* err; +} SignedTxResponse; + +typedef struct { + char* privateKey; + char* publicKey; + char* err; +} ApiKeyResponse; + +typedef struct { + uint8_t MarketIndex; + int64_t ClientOrderIndex; + int64_t BaseAmount; + uint32_t Price; + uint8_t IsAsk; + uint8_t Type; + uint8_t TimeInForce; + uint8_t ReduceOnly; + uint32_t TriggerPrice; + int64_t OrderExpiry; +} CreateOrderTxReq; + +#line 1 "cgo-generated-wrapper" + + +/* End of preamble from import "C" comments. */ + + +/* Start of boilerplate cgo prologue. */ +#line 1 "cgo-gcc-export-header-prolog" + +#ifndef GO_CGO_PROLOGUE_H +#define GO_CGO_PROLOGUE_H + +typedef signed char GoInt8; +typedef unsigned char GoUint8; +typedef short GoInt16; +typedef unsigned short GoUint16; +typedef int GoInt32; +typedef unsigned int GoUint32; +typedef long long GoInt64; +typedef unsigned long long GoUint64; +typedef GoInt64 GoInt; +typedef GoUint64 GoUint; +typedef size_t GoUintptr; +typedef float GoFloat32; +typedef double GoFloat64; +#ifdef _MSC_VER +#include +typedef _Fcomplex GoComplex64; +typedef _Dcomplex GoComplex128; +#else +typedef float _Complex GoComplex64; +typedef double _Complex GoComplex128; +#endif + +/* + static assertion to make sure the file is being used on architecture + at least with matching size of GoInt. +*/ +typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1]; + +#ifndef GO_CGO_GOSTRING_TYPEDEF +typedef _GoString_ GoString; +#endif +typedef void *GoMap; +typedef void *GoChan; +typedef struct { void *t; void *v; } GoInterface; +typedef struct { void *data; GoInt len; GoInt cap; } GoSlice; + +#endif + +/* End of boilerplate cgo prologue. */ + +#ifdef __cplusplus +extern "C" { +#endif + +extern __declspec(dllexport) ApiKeyResponse GenerateAPIKey(); +extern __declspec(dllexport) char* CreateClient(char* cUrl, char* cPrivateKey, int cChainId, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) char* CheckClient(int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignChangePubKey(char* cPubKey, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignCreateOrder(int cMarketIndex, long long int cClientOrderIndex, long long int cBaseAmount, int cPrice, int cIsAsk, int cOrderType, int cTimeInForce, int cReduceOnly, int cTriggerPrice, long long int cOrderExpiry, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignCreateGroupedOrders(uint8_t cGroupingType, CreateOrderTxReq* cOrders, int cLen, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignCancelOrder(int cMarketIndex, long long int cOrderIndex, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignWithdraw(int cAssetIndex, int cRouteType, long long unsigned int cAmount, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignCreateSubAccount(long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignCancelAllOrders(int cTimeInForce, long long int cTime, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignModifyOrder(int cMarketIndex, long long int cIndex, long long int cBaseAmount, long long int cPrice, long long int cTriggerPrice, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignTransfer(long long int cToAccountIndex, int16_t cAssetIndex, uint8_t cFromRouteType, uint8_t cToRouteType, long long int cAmount, long long int cUsdcFee, char* cMemo, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignCreatePublicPool(long long int cOperatorFee, int cInitialTotalShares, long long int cMinOperatorShareRate, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignUpdatePublicPool(long long int cPublicPoolIndex, int cStatus, long long int cOperatorFee, int cMinOperatorShareRate, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignMintShares(long long int cPublicPoolIndex, long long int cShareAmount, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignBurnShares(long long int cPublicPoolIndex, long long int cShareAmount, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignUpdateLeverage(int cMarketIndex, int cInitialMarginFraction, int cMarginMode, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) StrOrErr CreateAuthToken(long long int cDeadline, int cApiKeyIndex, long long int cAccountIndex); +extern __declspec(dllexport) SignedTxResponse SignUpdateMargin(int cMarketIndex, long long int cUSDCAmount, int cDirection, long long int cNonce, int cApiKeyIndex, long long int cAccountIndex); + +#ifdef __cplusplus +} +#endif diff --git a/lighter/signers/signer-arm64.dylib b/lighter/signers/signer-arm64.dylib deleted file mode 100644 index 1080f8e..0000000 Binary files a/lighter/signers/signer-arm64.dylib and /dev/null differ diff --git a/openapi.json b/openapi.json index 37729d5..d42774f 100644 --- a/openapi.json +++ b/openapi.json @@ -106,7 +106,14 @@ { "name": "authorization", "description": " make required after integ is done", - "in": "header", + "in": "query", + "required": false, + "type": "string" + }, + { + "name": "auth", + "description": " made optional to support header auth clients", + "in": "query", "required": false, "type": "string" }, @@ -122,14 +129,7 @@ "in": "query", "required": true, "type": "integer", - "format": "uint8" - }, - { - "name": "auth", - "description": " made optional to support header auth clients", - "in": "query", - "required": false, - "type": "string" + "format": "int16" } ], "tags": [ @@ -163,7 +163,7 @@ { "name": "authorization", "description": " make required after integ is done", - "in": "header", + "in": "query", "required": false, "type": "string" }, @@ -186,7 +186,7 @@ "in": "query", "required": false, "type": "integer", - "format": "uint8", + "format": "int16", "default": "255" }, { @@ -247,13 +247,6 @@ } }, "parameters": [ - { - "name": "authorization", - "description": " make required after integ is done", - "in": "header", - "required": false, - "type": "string" - }, { "name": "account_index", "in": "query", @@ -261,6 +254,13 @@ "type": "integer", "format": "int64" }, + { + "name": "authorization", + "description": " make required after integ is done", + "in": "query", + "required": false, + "type": "string" + }, { "name": "auth", "description": " made optional to support header auth clients", @@ -335,88 +335,6 @@ "description": "Get account metadatas" } }, - "/api/v1/accountTxs": { - "get": { - "summary": "accountTxs", - "operationId": "accountTxs", - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/Txs" - } - }, - "400": { - "description": "Bad request", - "schema": { - "$ref": "#/definitions/ResultCode" - } - } - }, - "parameters": [ - { - "name": "authorization", - "in": "header", - "required": false, - "type": "string" - }, - { - "name": "index", - "in": "query", - "required": false, - "type": "integer", - "format": "int64" - }, - { - "name": "limit", - "in": "query", - "required": true, - "type": "integer", - "format": "int64", - "minimum": 1, - "maximum": 100 - }, - { - "name": "by", - "in": "query", - "required": true, - "type": "string", - "enum": [ - "account_index" - ] - }, - { - "name": "value", - "in": "query", - "required": true, - "type": "string" - }, - { - "name": "types", - "in": "query", - "required": false, - "type": "array", - "items": { - "type": "integer", - "format": "uint8" - } - }, - { - "name": "auth", - "in": "query", - "required": false, - "type": "string" - } - ], - "tags": [ - "transaction" - ], - "consumes": [ - "multipart/form-data" - ], - "description": "Get transactions of a specific account" - } - }, "/api/v1/accountsByL1Address": { "get": { "summary": "accountsByL1Address", @@ -520,15 +438,15 @@ "description": "Get account api key. Set `api_key_index` to 255 to retrieve all api keys associated with the account." } }, - "/api/v1/block": { + "/api/v1/assetDetails": { "get": { - "summary": "block", - "operationId": "block", + "summary": "assetDetails", + "operationId": "assetDetails", "responses": { "200": { "description": "A successful response.", "schema": { - "$ref": "#/definitions/Blocks" + "$ref": "#/definitions/AssetDetails" } }, "400": { @@ -540,40 +458,32 @@ }, "parameters": [ { - "name": "by", - "in": "query", - "required": true, - "type": "string", - "enum": [ - "commitment", - "height" - ] - }, - { - "name": "value", + "name": "asset_id", "in": "query", - "required": true, - "type": "string" + "required": false, + "type": "integer", + "format": "int16", + "default": "0" } ], "tags": [ - "block" + "order" ], "consumes": [ "multipart/form-data" ], - "description": "Get block by its height or commitment" + "description": "Get asset details" } }, - "/api/v1/blockTxs": { + "/api/v1/bridges": { "get": { - "summary": "blockTxs", - "operationId": "blockTxs", + "summary": "bridges", + "operationId": "bridges", "responses": { "200": { "description": "A successful response.", "schema": { - "$ref": "#/definitions/Txs" + "$ref": "#/definitions/RespGetBridgesByL1Addr" } }, "400": { @@ -585,40 +495,30 @@ }, "parameters": [ { - "name": "by", - "in": "query", - "required": true, - "type": "string", - "enum": [ - "block_height", - "block_commitment" - ] - }, - { - "name": "value", + "name": "l1_address", "in": "query", "required": true, "type": "string" } ], "tags": [ - "transaction" + "bridge" ], "consumes": [ "multipart/form-data" ], - "description": "Get transactions in a block" + "description": "Get bridges for given l1 address" } }, - "/api/v1/blocks": { + "/api/v1/bridges/isNextBridgeFast": { "get": { - "summary": "blocks", - "operationId": "blocks", + "summary": "bridges_isNextBridgeFast", + "operationId": "bridges_isNextBridgeFast", "responses": { "200": { "description": "A successful response.", "schema": { - "$ref": "#/definitions/Blocks" + "$ref": "#/definitions/RespGetIsNextBridgeFast" } }, "400": { @@ -630,51 +530,30 @@ }, "parameters": [ { - "name": "index", - "in": "query", - "required": false, - "type": "integer", - "format": "int64" - }, - { - "name": "limit", + "name": "l1_address", "in": "query", "required": true, - "type": "integer", - "format": "int64", - "minimum": 1, - "maximum": 100 - }, - { - "name": "sort", - "in": "query", - "required": false, - "type": "string", - "enum": [ - "asc", - "desc" - ], - "default": "asc" + "type": "string" } ], "tags": [ - "block" + "bridge" ], "consumes": [ "multipart/form-data" ], - "description": "Get blocks" + "description": "Get if next bridge is fast" } }, - "/api/v1/candlesticks": { + "/api/v1/candles": { "get": { - "summary": "candlesticks", - "operationId": "candlesticks", + "summary": "candles", + "operationId": "candles", "responses": { "200": { "description": "A successful response.", "schema": { - "$ref": "#/definitions/Candlesticks" + "$ref": "#/definitions/Candles" } }, "400": { @@ -690,7 +569,7 @@ "in": "query", "required": true, "type": "integer", - "format": "uint8" + "format": "int16" }, { "name": "resolution", @@ -701,9 +580,12 @@ "1m", "5m", "15m", + "30m", "1h", "4h", - "1d" + "12h", + "1d", + "1w" ] }, { @@ -746,7 +628,7 @@ "consumes": [ "multipart/form-data" ], - "description": "Get candlesticks" + "description": "Get candles (optimized with shortened fields and smaller response size)" } }, "/api/v1/changeAccountTier": { @@ -793,30 +675,6 @@ "description": "Change account tier" } }, - "/api/v1/currentHeight": { - "get": { - "summary": "currentHeight", - "operationId": "currentHeight", - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/CurrentHeight" - } - }, - "400": { - "description": "Bad request", - "schema": { - "$ref": "#/definitions/ResultCode" - } - } - }, - "tags": [ - "block" - ], - "description": "Get current height" - } - }, "/api/v1/deposit/history": { "get": { "summary": "deposit_history", @@ -839,17 +697,10 @@ { "name": "authorization", "description": " make required after integ is done", - "in": "header", + "in": "query", "required": false, "type": "string" }, - { - "name": "account_index", - "in": "query", - "required": true, - "type": "integer", - "format": "int64" - }, { "name": "auth", "description": " made optional to support header auth clients", @@ -857,6 +708,13 @@ "required": false, "type": "string" }, + { + "name": "account_index", + "in": "query", + "required": true, + "type": "integer", + "format": "int64" + }, { "name": "l1_address", "in": "query", @@ -935,12 +793,14 @@ "parameters": [ { "name": "authorization", - "in": "header", + "description": " make required after integ is done", + "in": "query", "required": false, "type": "string" }, { "name": "auth", + "description": " made optional to support header auth clients", "in": "query", "required": false, "type": "string" @@ -958,7 +818,7 @@ "in": "query", "required": false, "type": "integer", - "format": "uint8", + "format": "int16", "default": "255" }, { @@ -1005,15 +865,15 @@ "description": "Get fast bridge info" } }, - "/api/v1/funding-rates": { - "get": { - "summary": "funding-rates", - "operationId": "funding-rates", + "/api/v1/fastwithdraw": { + "post": { + "summary": "fastwithdraw", + "operationId": "fastwithdraw", "responses": { "200": { "description": "A successful response.", "schema": { - "$ref": "#/definitions/FundingRates" + "$ref": "#/definitions/ResultCode" } }, "400": { @@ -1023,21 +883,41 @@ } } }, + "parameters": [ + { + "name": "authorization", + "description": " make required after integ is done", + "in": "header", + "required": false, + "type": "string" + }, + { + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/ReqFastwithdraw" + } + } + ], "tags": [ - "funding" + "bridge" ], - "description": "Get funding rates" + "consumes": [ + "multipart/form-data" + ], + "description": "Fast withdraw" } }, - "/api/v1/fundings": { + "/api/v1/fastwithdraw/info": { "get": { - "summary": "fundings", - "operationId": "fundings", + "summary": "fastwithdraw_info", + "operationId": "fastwithdraw_info", "responses": { "200": { "description": "A successful response.", "schema": { - "$ref": "#/definitions/Fundings" + "$ref": "#/definitions/RespGetFastwithdrawalInfo" } }, "400": { @@ -1049,32 +929,149 @@ }, "parameters": [ { - "name": "market_id", + "name": "authorization", + "description": " make required after integ is done", "in": "query", - "required": true, - "type": "integer", - "format": "uint8" + "required": false, + "type": "string" }, { - "name": "resolution", + "name": "auth", + "description": " made optional to support header auth clients", "in": "query", - "required": true, - "type": "string", - "enum": [ - "1h", - "1d" - ] + "required": false, + "type": "string" }, { - "name": "start_timestamp", + "name": "account_index", "in": "query", "required": true, "type": "integer", - "format": "int64", - "minimum": 0, - "maximum": 5000000000000 - }, - { + "format": "int64" + } + ], + "tags": [ + "bridge" + ], + "consumes": [ + "multipart/form-data" + ], + "description": "Get fast withdraw info" + } + }, + "/api/v1/faucet": { + "get": { + "summary": "faucet", + "operationId": "faucet", + "responses": { + "200": { + "description": "A successful response.", + "schema": { + "$ref": "#/definitions/ResultCode" + } + }, + "400": { + "description": "Bad request", + "schema": { + "$ref": "#/definitions/ResultCode" + } + } + }, + "parameters": [ + { + "name": "l1_address", + "in": "query", + "required": true, + "type": "string" + }, + { + "name": "do_l1_transfer", + "in": "query", + "required": true, + "type": "boolean", + "format": "boolean", + "default": "false" + } + ], + "tags": [ + "account" + ], + "consumes": [ + "multipart/form-data" + ], + "description": "Request funds from faucet" + } + }, + "/api/v1/funding-rates": { + "get": { + "summary": "funding-rates", + "operationId": "funding-rates", + "responses": { + "200": { + "description": "A successful response.", + "schema": { + "$ref": "#/definitions/FundingRates" + } + }, + "400": { + "description": "Bad request", + "schema": { + "$ref": "#/definitions/ResultCode" + } + } + }, + "tags": [ + "funding" + ], + "description": "Get funding rates" + } + }, + "/api/v1/fundings": { + "get": { + "summary": "fundings", + "operationId": "fundings", + "responses": { + "200": { + "description": "A successful response.", + "schema": { + "$ref": "#/definitions/Fundings" + } + }, + "400": { + "description": "Bad request", + "schema": { + "$ref": "#/definitions/ResultCode" + } + } + }, + "parameters": [ + { + "name": "market_id", + "in": "query", + "required": true, + "type": "integer", + "format": "int16" + }, + { + "name": "resolution", + "in": "query", + "required": true, + "type": "string", + "enum": [ + "1h", + "1d" + ] + }, + { + "name": "start_timestamp", + "in": "query", + "required": true, + "type": "integer", + "format": "int64", + "minimum": 0, + "maximum": 5000000000000 + }, + { "name": "end_timestamp", "in": "query", "required": true, @@ -1171,7 +1168,7 @@ { "name": "authorization", "description": " make required after integ is done", - "in": "header", + "in": "query", "required": false, "type": "string" }, @@ -1194,7 +1191,7 @@ "in": "query", "required": false, "type": "integer", - "format": "uint8", + "format": "int16", "default": "255" }, { @@ -1333,8 +1330,20 @@ "in": "query", "required": false, "type": "integer", - "format": "uint8", + "format": "int16", "default": "255" + }, + { + "name": "filter", + "in": "query", + "required": false, + "type": "string", + "enum": [ + "all", + "spot", + "perp" + ], + "default": "all" } ], "tags": [ @@ -1370,7 +1379,7 @@ "in": "query", "required": true, "type": "integer", - "format": "uint8" + "format": "int16" }, { "name": "limit", @@ -1379,7 +1388,7 @@ "type": "integer", "format": "int64", "minimum": 1, - "maximum": 100 + "maximum": 250 } ], "tags": [ @@ -1415,8 +1424,20 @@ "in": "query", "required": false, "type": "integer", - "format": "uint8", + "format": "int16", "default": "255" + }, + { + "name": "filter", + "in": "query", + "required": false, + "type": "string", + "enum": [ + "all", + "spot", + "perp" + ], + "default": "all" } ], "tags": [ @@ -1449,12 +1470,14 @@ "parameters": [ { "name": "authorization", - "in": "header", + "description": " make required after integ is done", + "in": "query", "required": false, "type": "string" }, { "name": "auth", + "description": " made optional to support header auth clients", "in": "query", "required": false, "type": "string" @@ -1552,12 +1575,14 @@ "parameters": [ { "name": "authorization", - "in": "header", + "description": " make required after integ is done", + "in": "query", "required": false, "type": "string" }, { "name": "auth", + "description": " made optional to support header auth clients", "in": "query", "required": false, "type": "string" @@ -1574,7 +1599,7 @@ "in": "query", "required": false, "type": "integer", - "format": "uint8", + "format": "int16", "default": "255" }, { @@ -1614,15 +1639,15 @@ "description": "Get accounts position fundings" } }, - "/api/v1/publicPools": { + "/api/v1/publicPoolsMetadata": { "get": { - "summary": "publicPools", - "operationId": "publicPools", + "summary": "publicPoolsMetadata", + "operationId": "publicPoolsMetadata", "responses": { "200": { "description": "A successful response.", "schema": { - "$ref": "#/definitions/PublicPools" + "$ref": "#/definitions/RespPublicPoolsMetadata" } }, "400": { @@ -1635,12 +1660,14 @@ "parameters": [ { "name": "authorization", - "in": "header", + "description": " make required after integ is done", + "in": "query", "required": false, "type": "string" }, { "name": "auth", + "description": " made optional to support header auth clients", "in": "query", "required": false, "type": "string" @@ -1687,18 +1714,18 @@ "consumes": [ "multipart/form-data" ], - "description": "Get public pools" + "description": "Get public pools metadata" } }, - "/api/v1/publicPoolsMetadata": { + "/api/v1/recentTrades": { "get": { - "summary": "publicPoolsMetadata", - "operationId": "publicPoolsMetadata", + "summary": "recentTrades", + "operationId": "recentTrades", "responses": { "200": { "description": "A successful response.", "schema": { - "$ref": "#/definitions/RespPublicPoolsMetadata" + "$ref": "#/definitions/Trades" } }, "400": { @@ -1710,35 +1737,11 @@ }, "parameters": [ { - "name": "authorization", - "in": "header", - "required": false, - "type": "string" - }, - { - "name": "auth", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "filter", - "in": "query", - "required": false, - "type": "string", - "enum": [ - "all", - "user", - "protocol", - "account_index" - ] - }, - { - "name": "index", + "name": "market_id", "in": "query", "required": true, "type": "integer", - "format": "int64" + "format": "int16" }, { "name": "limit", @@ -1748,33 +1751,26 @@ "format": "int64", "minimum": 1, "maximum": 100 - }, - { - "name": "account_index", - "in": "query", - "required": false, - "type": "integer", - "format": "int64" } ], "tags": [ - "account" + "order" ], "consumes": [ "multipart/form-data" ], - "description": "Get public pools metadata" + "description": "Get recent trades" } }, - "/api/v1/recentTrades": { - "get": { - "summary": "recentTrades", - "operationId": "recentTrades", + "/api/v1/sendTx": { + "post": { + "summary": "sendTx", + "operationId": "sendTx", "responses": { "200": { "description": "A successful response.", "schema": { - "$ref": "#/definitions/Trades" + "$ref": "#/definitions/RespSendTx" } }, "400": { @@ -1786,40 +1782,32 @@ }, "parameters": [ { - "name": "market_id", - "in": "query", - "required": true, - "type": "integer", - "format": "uint8" - }, - { - "name": "limit", - "in": "query", + "name": "body", + "in": "body", "required": true, - "type": "integer", - "format": "int64", - "minimum": 1, - "maximum": 100 + "schema": { + "$ref": "#/definitions/ReqSendTx" + } } ], "tags": [ - "order" + "transaction" ], "consumes": [ "multipart/form-data" ], - "description": "Get recent trades" + "description": "You need to sign the transaction body before sending it to the server. More details can be found in the Get Started docs: [Get Started For Programmers](https://apidocs.lighter.xyz/docs/get-started-for-programmers)" } }, - "/api/v1/referral/points": { - "get": { - "summary": "referral_points", - "operationId": "referral_points", + "/api/v1/sendTxBatch": { + "post": { + "summary": "sendTxBatch", + "operationId": "sendTxBatch", "responses": { "200": { "description": "A successful response.", "schema": { - "$ref": "#/definitions/ReferralPoints" + "$ref": "#/definitions/RespSendTxBatch" } }, "400": { @@ -1831,16 +1819,46 @@ }, "parameters": [ { - "name": "authorization", - "description": " make required after integ is done", - "in": "header", - "required": false, - "type": "string" - }, - { - "name": "auth", - "description": " made optional to support header auth clients", - "in": "query", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/ReqSendTxBatch" + } + } + ], + "tags": [ + "transaction" + ], + "consumes": [ + "multipart/form-data" + ], + "description": "You need to sign the transaction body before sending it to the server. More details can be found in the Get Started docs: [Get Started For Programmers](https://apidocs.lighter.xyz/docs/get-started-for-programmers)" + } + }, + "/api/v1/tokens": { + "get": { + "summary": "tokens", + "operationId": "tokens", + "responses": { + "200": { + "description": "A successful response.", + "schema": { + "$ref": "#/definitions/RespGetApiTokens" + } + }, + "400": { + "description": "Bad request", + "schema": { + "$ref": "#/definitions/ResultCode" + } + } + }, + "parameters": [ + { + "name": "authorization", + "description": " make required after integ is done", + "in": "header", "required": false, "type": "string" }, @@ -1853,23 +1871,23 @@ } ], "tags": [ - "referral" + "account" ], "consumes": [ "multipart/form-data" ], - "description": "Get referral points" + "description": "Get api tokens of an account" } }, - "/api/v1/sendTx": { + "/api/v1/tokens/create": { "post": { - "summary": "sendTx", - "operationId": "sendTx", + "summary": "tokens_create", + "operationId": "tokens_create", "responses": { "200": { "description": "A successful response.", "schema": { - "$ref": "#/definitions/RespSendTx" + "$ref": "#/definitions/RespPostApiToken" } }, "400": { @@ -1880,33 +1898,39 @@ } }, "parameters": [ + { + "name": "authorization", + "in": "header", + "required": false, + "type": "string" + }, { "name": "body", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/ReqSendTx" + "$ref": "#/definitions/ReqPostApiToken" } } ], "tags": [ - "transaction" + "account" ], "consumes": [ "multipart/form-data" ], - "description": "You need to sign the transaction body before sending it to the server. More details can be found in the Get Started docs: [Get Started For Programmers](https://apidocs.lighter.xyz/docs/get-started-for-programmers)" + "description": "Create api token" } }, - "/api/v1/sendTxBatch": { + "/api/v1/tokens/revoke": { "post": { - "summary": "sendTxBatch", - "operationId": "sendTxBatch", + "summary": "tokens_revoke", + "operationId": "tokens_revoke", "responses": { "200": { "description": "A successful response.", "schema": { - "$ref": "#/definitions/RespSendTxBatch" + "$ref": "#/definitions/RespRevokeApiToken" } }, "400": { @@ -1917,22 +1941,28 @@ } }, "parameters": [ + { + "name": "authorization", + "in": "header", + "required": false, + "type": "string" + }, { "name": "body", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/ReqSendTxBatch" + "$ref": "#/definitions/ReqRevokeApiToken" } } ], "tags": [ - "transaction" + "account" ], "consumes": [ "multipart/form-data" ], - "description": "You need to sign the transaction body before sending it to the server. More details can be found in the Get Started docs: [Get Started For Programmers](https://apidocs.lighter.xyz/docs/get-started-for-programmers)" + "description": "Revoke api token" } }, "/api/v1/trades": { @@ -1956,12 +1986,14 @@ "parameters": [ { "name": "authorization", - "in": "header", + "description": " make required after integ is done", + "in": "query", "required": false, "type": "string" }, { "name": "auth", + "description": " made optional to support header auth clients", "in": "query", "required": false, "type": "string" @@ -1971,7 +2003,7 @@ "in": "query", "required": false, "type": "integer", - "format": "uint8", + "format": "int16", "default": "255" }, { @@ -2032,6 +2064,32 @@ "format": "int8", "default": "-1" }, + { + "name": "role", + "in": "query", + "required": false, + "type": "string", + "enum": [ + "all", + "maker", + "taker" + ], + "default": "all" + }, + { + "name": "type", + "in": "query", + "required": false, + "type": "string", + "enum": [ + "all", + "trade", + "liquidation", + "deleverage", + "market-settlement" + ], + "default": "all" + }, { "name": "limit", "in": "query", @@ -2040,6 +2098,14 @@ "format": "int64", "minimum": 1, "maximum": 100 + }, + { + "name": "aggregate", + "in": "query", + "required": false, + "type": "boolean", + "format": "boolean", + "default": "false" } ], "tags": [ @@ -2073,17 +2139,10 @@ { "name": "authorization", "description": " make required after integ is done", - "in": "header", + "in": "query", "required": false, "type": "string" }, - { - "name": "account_index", - "in": "query", - "required": true, - "type": "integer", - "format": "int64" - }, { "name": "auth", "description": " made optional to support header auth clients", @@ -2091,6 +2150,13 @@ "required": false, "type": "string" }, + { + "name": "account_index", + "in": "query", + "required": true, + "type": "integer", + "format": "int64" + }, { "name": "cursor", "in": "query", @@ -2128,12 +2194,14 @@ "parameters": [ { "name": "authorization", - "in": "header", + "description": " make required after integ is done", + "in": "query", "required": false, "type": "string" }, { "name": "auth", + "description": " made optional to support header auth clients", "in": "query", "required": false, "type": "string" @@ -2243,51 +2311,6 @@ "description": "Get L1 transaction by L1 transaction hash" } }, - "/api/v1/txs": { - "get": { - "summary": "txs", - "operationId": "txs", - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/Txs" - } - }, - "400": { - "description": "Bad request", - "schema": { - "$ref": "#/definitions/ResultCode" - } - } - }, - "parameters": [ - { - "name": "index", - "in": "query", - "required": false, - "type": "integer", - "format": "int64" - }, - { - "name": "limit", - "in": "query", - "required": true, - "type": "integer", - "format": "int64", - "minimum": 1, - "maximum": 100 - } - ], - "tags": [ - "transaction" - ], - "consumes": [ - "multipart/form-data" - ], - "description": "Get transactions which are already packed into blocks" - } - }, "/api/v1/withdraw/history": { "get": { "summary": "withdraw_history", @@ -2310,17 +2333,10 @@ { "name": "authorization", "description": " make required after integ is done", - "in": "header", + "in": "query", "required": false, "type": "string" }, - { - "name": "account_index", - "in": "query", - "required": true, - "type": "integer", - "format": "int64" - }, { "name": "auth", "description": " made optional to support header auth clients", @@ -2328,6 +2344,13 @@ "required": false, "type": "string" }, + { + "name": "account_index", + "in": "query", + "required": true, + "type": "integer", + "format": "int64" + }, { "name": "cursor", "in": "query", @@ -2462,6 +2485,11 @@ "collateral": { "type": "string", "example": "46342" + }, + "transaction_time": { + "type": "integer", + "format": "int64", + "example": "1257894000000000" } }, "title": "Account", @@ -2476,7 +2504,8 @@ "pending_order_count", "available_balance", "status", - "collateral" + "collateral", + "transaction_time" ] }, "AccountApiKeys": { @@ -2503,6 +2532,35 @@ "api_keys" ] }, + "AccountAsset": { + "type": "object", + "properties": { + "symbol": { + "type": "string", + "example": "USDC" + }, + "asset_id": { + "type": "integer", + "format": "int16", + "example": "1" + }, + "balance": { + "type": "string", + "example": "1000" + }, + "locked_balance": { + "type": "string", + "example": "1000" + } + }, + "title": "AccountAsset", + "required": [ + "symbol", + "asset_id", + "balance", + "locked_balance" + ] + }, "AccountLimits": { "type": "object", "properties": { @@ -2519,16 +2577,27 @@ "format": "int32", "example": "25" }, + "max_llp_amount": { + "type": "string", + "example": "1000000" + }, "user_tier": { "type": "string", "example": "std" + }, + "can_create_public_pool": { + "type": "boolean", + "format": "boolean", + "example": "true" } }, "title": "AccountLimits", "required": [ "code", "max_llp_percentage", - "user_tier" + "max_llp_amount", + "user_tier", + "can_create_public_pool" ] }, "AccountMarginStats": { @@ -2574,7 +2643,7 @@ "properties": { "market_id": { "type": "integer", - "format": "uint8", + "format": "int16", "example": "1" }, "daily_trades_count": { @@ -2745,7 +2814,7 @@ "properties": { "market_id": { "type": "integer", - "format": "uint8", + "format": "int16", "example": "1" }, "symbol": { @@ -2947,13 +3016,18 @@ "created_at": { "type": "integer", "format": "int64" + }, + "expired_at": { + "type": "integer", + "format": "int64" } }, "title": "Announcement", "required": [ "title", "content", - "created_at" + "created_at", + "expired_at" ] }, "Announcements": { @@ -3000,6 +3074,11 @@ }, "public_key": { "type": "string" + }, + "transaction_time": { + "type": "integer", + "format": "int64", + "example": "1257894000000000" } }, "title": "ApiKey", @@ -3007,106 +3086,237 @@ "account_index", "api_key_index", "nonce", - "public_key" + "public_key", + "transaction_time" ] }, - "Block": { + "ApiToken": { "type": "object", "properties": { - "commitment": { - "type": "string" - }, - "height": { + "token_id": { "type": "integer", "format": "int64" }, - "state_root": { - "type": "string" - }, - "priority_operations": { - "type": "integer", - "format": "int32" - }, - "on_chain_l2_operations": { - "type": "integer", - "format": "int32" - }, - "pending_on_chain_operations_pub_data": { + "api_token": { "type": "string" }, - "committed_tx_hash": { + "name": { "type": "string" }, - "committed_at": { + "account_index": { "type": "integer", "format": "int64" }, - "verified_tx_hash": { - "type": "string" - }, - "verified_at": { + "expiry": { "type": "integer", "format": "int64" }, - "txs": { - "type": "array", - "items": { - "$ref": "#/definitions/Tx" - } + "sub_account_access": { + "type": "boolean", + "format": "boolean" }, - "status": { - "type": "integer", - "format": "int64" + "revoked": { + "type": "boolean", + "format": "boolean" }, - "size": { - "type": "integer", - "format": "uin16" + "scopes": { + "type": "string" } }, - "title": "Block", + "title": "ApiToken", "required": [ - "commitment", - "height", - "state_root", - "priority_operations", - "on_chain_l2_operations", - "pending_on_chain_operations_pub_data", - "committed_tx_hash", - "committed_at", - "verified_tx_hash", - "verified_at", - "txs", - "status", - "size" + "token_id", + "api_token", + "name", + "account_index", + "expiry", + "sub_account_access", + "revoked", + "scopes" ] }, - "Blocks": { + "Asset": { "type": "object", "properties": { - "code": { + "asset_id": { "type": "integer", - "format": "int32", - "example": "200" + "format": "int16", + "example": "1" }, - "message": { - "type": "string" + "symbol": { + "type": "string", + "example": "ETH" }, - "total": { + "l1_decimals": { "type": "integer", - "format": "int64" + "format": "uint8", + "example": "18" }, - "blocks": { + "decimals": { + "type": "integer", + "format": "uint8", + "example": "2" + }, + "min_transfer_amount": { + "type": "string", + "example": "0.01" + }, + "min_withdrawal_amount": { + "type": "string", + "example": "0.01" + }, + "margin_mode": { + "type": "string", + "example": "enabled", + "enum": [ + "enabled", + "disabled" + ] + }, + "index_price": { + "type": "string", + "example": "3024.66" + }, + "l1_address": { + "type": "string", + "example": "0x0000000000000000000000000000000000000000" + } + }, + "title": "Asset", + "required": [ + "asset_id", + "symbol", + "l1_decimals", + "decimals", + "min_transfer_amount", + "min_withdrawal_amount", + "margin_mode", + "index_price", + "l1_address" + ] + }, + "AssetDetails": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32", + "example": "200" + }, + "message": { + "type": "string" + }, + "asset_details": { "type": "array", "items": { - "$ref": "#/definitions/Block" + "$ref": "#/definitions/Asset" } } }, - "title": "Blocks", + "title": "AssetDetails", "required": [ "code", - "total", - "blocks" + "asset_details" + ] + }, + "Auth": { + "type": "object", + "properties": { + "auth": { + "type": "string", + "description": " made optional to support header auth clients" + } + }, + "title": "Auth", + "required": [ + "auth" + ] + }, + "Bridge": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "version": { + "type": "integer", + "format": "int32", + "enum": [ + "1", + "2" + ] + }, + "source": { + "type": "string", + "example": "Arbitrum" + }, + "source_chain_id": { + "type": "string", + "example": "42161" + }, + "fast_bridge_tx_hash": { + "type": "string", + "example": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" + }, + "batch_claim_tx_hash": { + "type": "string", + "example": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" + }, + "cctp_burn_tx_hash": { + "type": "string", + "example": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" + }, + "amount": { + "type": "string" + }, + "intent_address": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "pending", + "bridging", + "completed" + ] + }, + "step": { + "type": "string" + }, + "description": { + "type": "string" + }, + "created_at": { + "type": "integer", + "format": "int64" + }, + "updated_at": { + "type": "integer", + "format": "int64" + }, + "is_external_deposit": { + "type": "boolean", + "format": "boolean" + } + }, + "title": "Bridge", + "required": [ + "id", + "version", + "source", + "source_chain_id", + "fast_bridge_tx_hash", + "batch_claim_tx_hash", + "cctp_burn_tx_hash", + "amount", + "intent_address", + "status", + "step", + "description", + "created_at", + "updated_at", + "is_external_deposit" ] }, "BridgeSupportedNetwork": { @@ -3132,63 +3342,99 @@ "explorer" ] }, - "Candlestick": { + "Candle": { "type": "object", "properties": { - "timestamp": { + "t": { "type": "integer", "format": "int64", - "example": "1640995200" + "example": "1640995200", + "description": " timestamp" }, - "open": { + "o": { "type": "number", "format": "double", - "example": "3024.66" + "example": "3024.66", + "description": " open" }, - "high": { + "h": { "type": "number", "format": "double", - "example": "3034.66" + "example": "3034.66", + "description": " high" }, - "low": { + "l": { "type": "number", "format": "double", - "example": "3014.66" + "example": "3014.66", + "description": " low" }, - "close": { + "c": { "type": "number", "format": "double", - "example": "3024.66" + "example": "3024.66", + "description": " close" }, - "volume0": { + "O": { "type": "number", "format": "double", - "example": "235.25" + "example": "3024.66", + "description": " open_raw" }, - "volume1": { + "H": { "type": "number", "format": "double", - "example": "93566.25" + "example": "3034.66", + "description": " high_raw" }, - "last_trade_id": { + "L": { + "type": "number", + "format": "double", + "example": "3014.66", + "description": " low_raw" + }, + "C": { + "type": "number", + "format": "double", + "example": "3024.66", + "description": " close_raw" + }, + "v": { + "type": "number", + "format": "double", + "example": "235.25", + "description": " volume0" + }, + "V": { + "type": "number", + "format": "double", + "example": "93566.25", + "description": " volume1" + }, + "i": { "type": "integer", "format": "int64", - "example": "1" + "example": "1", + "description": " last_trade_id" } }, - "title": "Candlestick", + "title": "Candle", "required": [ - "timestamp", - "open", - "high", - "low", - "close", - "volume0", - "volume1", - "last_trade_id" + "t", + "o", + "h", + "l", + "c", + "O", + "H", + "L", + "C", + "v", + "V", + "i" ] }, - "Candlesticks": { + "Candles": { "type": "object", "properties": { "code": { @@ -3199,22 +3445,24 @@ "message": { "type": "string" }, - "resolution": { + "r": { "type": "string", - "example": "15m" + "example": "15m", + "description": " resolution" }, - "candlesticks": { + "c": { "type": "array", "items": { - "$ref": "#/definitions/Candlestick" - } + "$ref": "#/definitions/Candle" + }, + "description": " candles" } }, - "title": "Candlesticks", + "title": "Candles", "required": [ "code", - "resolution", - "candlesticks" + "r", + "c" ] }, "ContractAddress": { @@ -3235,28 +3483,6 @@ "address" ] }, - "CurrentHeight": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32", - "example": "200" - }, - "message": { - "type": "string" - }, - "height": { - "type": "integer", - "format": "int64" - } - }, - "title": "CurrentHeight", - "required": [ - "code", - "height" - ] - }, "Cursor": { "type": "object", "properties": { @@ -3320,6 +3546,11 @@ "id": { "type": "string" }, + "asset_id": { + "type": "integer", + "format": "int16", + "example": "1" + }, "amount": { "type": "string", "example": "0.1" @@ -3346,6 +3577,7 @@ "title": "DepositHistoryItem", "required": [ "id", + "asset_id", "amount", "timestamp", "status", @@ -3410,6 +3642,11 @@ "type": "string", "example": "46342" }, + "transaction_time": { + "type": "integer", + "format": "int64", + "example": "1257894000000000" + }, "account_index": { "type": "integer", "format": "int64" @@ -3435,6 +3672,12 @@ "$ref": "#/definitions/AccountPosition" } }, + "assets": { + "type": "array", + "items": { + "$ref": "#/definitions/AccountAsset" + } + }, "total_asset_value": { "type": "string", "example": "19995" @@ -3466,12 +3709,14 @@ "available_balance", "status", "collateral", + "transaction_time", "account_index", "name", "description", "can_invite", "referral_points_percentage", "positions", + "assets", "total_asset_value", "cross_asset_value", "pool_info", @@ -3536,6 +3781,26 @@ "format": "double", "example": "3024.66" }, + "open_raw": { + "type": "number", + "format": "double", + "example": "3024.66" + }, + "high_raw": { + "type": "number", + "format": "double", + "example": "3034.66" + }, + "low_raw": { + "type": "number", + "format": "double", + "example": "3014.66" + }, + "close_raw": { + "type": "number", + "format": "double", + "example": "3024.66" + }, "volume0": { "type": "number", "format": "double", @@ -3564,6 +3829,10 @@ "high", "low", "close", + "open_raw", + "high_raw", + "low_raw", + "close_raw", "volume0", "volume1", "last_trade_id", @@ -3653,6 +3922,16 @@ "type": "string", "example": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" }, + "api_key_index": { + "type": "integer", + "format": "uint8", + "example": "0" + }, + "transaction_time": { + "type": "integer", + "format": "int64", + "example": "1257894000000000" + }, "committed_at": { "type": "integer", "format": "int64", @@ -3682,6 +3961,8 @@ "executed_at", "sequence_index", "parent_hash", + "api_key_index", + "transaction_time", "committed_at", "verified_at" ] @@ -3784,7 +4065,7 @@ "properties": { "market_id": { "type": "integer", - "format": "uint8" + "format": "int16" }, "exchange": { "type": "string", @@ -3925,6 +4206,10 @@ }, "maker_fee": { "type": "string" + }, + "transaction_time": { + "type": "integer", + "format": "int64" } }, "title": "LiqTrade", @@ -3932,7 +4217,8 @@ "price", "size", "taker_fee", - "maker_fee" + "maker_fee", + "transaction_time" ] }, "Liquidation": { @@ -3944,7 +4230,7 @@ }, "market_id": { "type": "integer", - "format": "uint8" + "format": "int16" }, "type": { "type": "string", @@ -4032,98 +4318,50 @@ "liquidations" ] }, - "MarketInfo": { + "MarketConfig": { "type": "object", "properties": { - "market_id": { + "market_margin_mode": { "type": "integer", - "format": "uint8", - "example": "1" - }, - "index_price": { - "type": "string", - "example": "3024.66" + "format": "int32" }, - "mark_price": { - "type": "string", - "example": "3024.66" + "insurance_fund_account_index": { + "type": "integer", + "format": "int64" }, - "open_interest": { - "type": "string", - "example": "235.25" + "liquidation_mode": { + "type": "integer", + "format": "int32" }, - "last_trade_price": { - "type": "string", - "example": "3024.66" + "force_reduce_only": { + "type": "boolean", + "format": "boolean" }, - "current_funding_rate": { - "type": "string", - "example": "0.0001" + "trading_hours": { + "type": "string" + } + }, + "title": "MarketConfig", + "required": [ + "market_margin_mode", + "insurance_fund_account_index", + "liquidation_mode", + "force_reduce_only", + "trading_hours" + ] + }, + "NextNonce": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32", + "example": "200" }, - "funding_rate": { - "type": "string", - "example": "0.0001" + "message": { + "type": "string" }, - "funding_timestamp": { - "type": "integer", - "format": "int64", - "example": "1640995200" - }, - "daily_base_token_volume": { - "type": "number", - "format": "double", - "example": "235.25" - }, - "daily_quote_token_volume": { - "type": "number", - "format": "double", - "example": "93566.25" - }, - "daily_price_low": { - "type": "number", - "format": "double", - "example": "3014.66" - }, - "daily_price_high": { - "type": "number", - "format": "double", - "example": "3024.66" - }, - "daily_price_change": { - "type": "number", - "format": "double", - "example": "3.66" - } - }, - "title": "MarketInfo", - "required": [ - "market_id", - "index_price", - "mark_price", - "open_interest", - "last_trade_price", - "current_funding_rate", - "funding_rate", - "funding_timestamp", - "daily_base_token_volume", - "daily_quote_token_volume", - "daily_price_low", - "daily_price_high", - "daily_price_change" - ] - }, - "NextNonce": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32", - "example": "200" - }, - "message": { - "type": "string" - }, - "nonce": { + "nonce": { "type": "integer", "format": "int64", "example": "722" @@ -4158,7 +4396,7 @@ }, "market_index": { "type": "integer", - "format": "uint8", + "format": "int16", "example": "1" }, "owner_account_index": { @@ -4270,7 +4508,8 @@ "canceled-expired", "canceled-oco", "canceled-child", - "canceled-liquidation" + "canceled-liquidation", + "canceled-invalid-balance" ] }, "trigger_status": { @@ -4319,6 +4558,21 @@ "type": "integer", "format": "int64", "example": "1640995200" + }, + "created_at": { + "type": "integer", + "format": "int64", + "example": "1640995200" + }, + "updated_at": { + "type": "integer", + "format": "int64", + "example": "1640995200" + }, + "transaction_time": { + "type": "integer", + "format": "int64", + "example": "1257894000000000" } }, "title": "Order", @@ -4353,7 +4607,10 @@ "to_trigger_order_id_1", "to_cancel_order_id_0", "block_height", - "timestamp" + "timestamp", + "created_at", + "updated_at", + "transaction_time" ] }, "OrderBook": { @@ -4365,15 +4622,32 @@ }, "market_id": { "type": "integer", - "format": "uint8", + "format": "int16", + "example": "1" + }, + "market_type": { + "type": "string", + "example": "perp", + "enum": [ + "perp", + "spot" + ] + }, + "base_asset_id": { + "type": "integer", + "format": "int16", "example": "1" }, + "quote_asset_id": { + "type": "integer", + "format": "int16", + "example": "2" + }, "status": { "type": "string", "example": "active", "enum": [ "inactive", - "frozen", "active" ] }, @@ -4397,6 +4671,10 @@ "type": "string", "example": "0.1" }, + "order_quote_limit": { + "type": "string", + "example": "235.25" + }, "supported_size_decimals": { "type": "integer", "format": "uint8", @@ -4417,12 +4695,16 @@ "required": [ "symbol", "market_id", + "market_type", + "base_asset_id", + "quote_asset_id", "status", "taker_fee", "maker_fee", "liquidation_fee", "min_base_amount", "min_quote_amount", + "order_quote_limit", "supported_size_decimals", "supported_price_decimals", "supported_quote_decimals" @@ -4455,6 +4737,11 @@ "type": "integer", "format": "int64", "example": "0" + }, + "nonce": { + "type": "integer", + "format": "int64", + "example": "0" } }, "title": "OrderBookDepth", @@ -4462,99 +4749,130 @@ "code", "asks", "bids", - "offset" + "offset", + "nonce" ] }, - "OrderBookDetail": { + "OrderBookDepthWithBeginNonce": { "type": "object", "properties": { - "symbol": { - "type": "string", - "example": "ETH" - }, - "market_id": { - "type": "integer", - "format": "uint8", - "example": "1" - }, - "status": { - "type": "string", - "example": "active", - "enum": [ - "inactive", - "frozen", - "active" - ] - }, - "taker_fee": { - "type": "string", - "example": "0.0001" - }, - "maker_fee": { - "type": "string", - "example": "0.0000" - }, - "liquidation_fee": { - "type": "string", - "example": "0.01" - }, - "min_base_amount": { - "type": "string", - "example": "0.01" + "asks": { + "type": "array", + "items": { + "$ref": "#/definitions/PriceLevel" + } }, - "min_quote_amount": { - "type": "string", - "example": "0.1" + "bids": { + "type": "array", + "items": { + "$ref": "#/definitions/PriceLevel" + } }, - "supported_size_decimals": { + "offset": { "type": "integer", - "format": "uint8", - "example": "4" + "format": "int64", + "example": "0" }, - "supported_price_decimals": { + "nonce": { "type": "integer", - "format": "uint8", - "example": "4" + "format": "int64", + "example": "0" }, - "supported_quote_decimals": { + "begin_nonce": { "type": "integer", - "format": "uint8", - "example": "4" - }, - "size_decimals": { + "format": "int64", + "example": "0" + } + }, + "title": "OrderBookDepthWithBeginNonce", + "required": [ + "asks", + "bids", + "offset", + "nonce", + "begin_nonce" + ] + }, + "OrderBookDetails": { + "type": "object", + "properties": { + "code": { "type": "integer", - "format": "uint8", - "example": "4" + "format": "int32", + "example": "200" }, - "price_decimals": { - "type": "integer", - "format": "uint8", - "example": "4" + "message": { + "type": "string" }, - "quote_multiplier": { - "type": "integer", - "format": "int64", - "example": "10000" + "order_book_details": { + "type": "array", + "items": { + "$ref": "#/definitions/PerpsOrderBookDetail" + } }, - "default_initial_margin_fraction": { + "spot_order_book_details": { + "type": "array", + "items": { + "$ref": "#/definitions/SpotOrderBookDetail" + } + } + }, + "title": "OrderBookDetails", + "required": [ + "code", + "order_book_details", + "spot_order_book_details" + ] + }, + "OrderBookOrders": { + "type": "object", + "properties": { + "code": { "type": "integer", - "format": "uin16", - "example": "100" + "format": "int32", + "example": "200" }, - "min_initial_margin_fraction": { - "type": "integer", - "format": "uin16", - "example": "100" + "message": { + "type": "string" }, - "maintenance_margin_fraction": { + "total_asks": { "type": "integer", - "format": "uin16", - "example": "50" + "format": "int64", + "example": "1" }, - "closeout_margin_fraction": { + "asks": { + "type": "array", + "items": { + "$ref": "#/definitions/SimpleOrder" + } + }, + "total_bids": { "type": "integer", - "format": "uin16", - "example": "100" + "format": "int64", + "example": "1" + }, + "bids": { + "type": "array", + "items": { + "$ref": "#/definitions/SimpleOrder" + } + } + }, + "title": "OrderBookOrders", + "required": [ + "code", + "total_asks", + "asks", + "total_bids", + "bids" + ] + }, + "OrderBookStats": { + "type": "object", + "properties": { + "symbol": { + "type": "string", + "example": "ETH" }, "last_trade_price": { "type": "number", @@ -4576,67 +4894,23 @@ "format": "double", "example": "93566.25" }, - "daily_price_low": { - "type": "number", - "format": "double", - "example": "3014.66" - }, - "daily_price_high": { - "type": "number", - "format": "double", - "example": "3024.66" - }, - "daily_price_change": { + "daily_price_change": { "type": "number", "format": "double", "example": "3.66" - }, - "open_interest": { - "type": "number", - "format": "double", - "example": "93.0" - }, - "daily_chart": { - "type": "object", - "example": "{1640995200:3024.66}", - "additionalProperties": { - "type": "number", - "format": "double" - } } }, - "title": "OrderBookDetail", + "title": "OrderBookStats", "required": [ "symbol", - "market_id", - "status", - "taker_fee", - "maker_fee", - "liquidation_fee", - "min_base_amount", - "min_quote_amount", - "supported_size_decimals", - "supported_price_decimals", - "supported_quote_decimals", - "size_decimals", - "price_decimals", - "quote_multiplier", - "default_initial_margin_fraction", - "min_initial_margin_fraction", - "maintenance_margin_fraction", - "closeout_margin_fraction", "last_trade_price", "daily_trades_count", "daily_base_token_volume", "daily_quote_token_volume", - "daily_price_low", - "daily_price_high", - "daily_price_change", - "open_interest", - "daily_chart" + "daily_price_change" ] }, - "OrderBookDetails": { + "OrderBooks": { "type": "object", "properties": { "code": { @@ -4647,20 +4921,20 @@ "message": { "type": "string" }, - "order_book_details": { + "order_books": { "type": "array", "items": { - "$ref": "#/definitions/OrderBookDetail" + "$ref": "#/definitions/OrderBook" } } }, - "title": "OrderBookDetails", + "title": "OrderBooks", "required": [ "code", - "order_book_details" + "order_books" ] }, - "OrderBookOrders": { + "Orders": { "type": "object", "properties": { "code": { @@ -4671,54 +4945,74 @@ "message": { "type": "string" }, - "total_asks": { - "type": "integer", - "format": "int64", - "example": "1" - }, - "asks": { - "type": "array", - "items": { - "$ref": "#/definitions/SimpleOrder" - } - }, - "total_bids": { - "type": "integer", - "format": "int64", - "example": "1" + "next_cursor": { + "type": "string" }, - "bids": { + "orders": { "type": "array", "items": { - "$ref": "#/definitions/SimpleOrder" + "$ref": "#/definitions/Order" } } }, - "title": "OrderBookOrders", + "title": "Orders", "required": [ "code", - "total_asks", - "asks", - "total_bids", - "bids" + "orders" ] }, - "OrderBookStats": { + "PerpsMarketStats": { "type": "object", "properties": { "symbol": { "type": "string", "example": "ETH" }, + "market_id": { + "type": "integer", + "format": "int16", + "example": "1" + }, + "index_price": { + "type": "string", + "example": "3024.66" + }, + "mark_price": { + "type": "string", + "example": "3024.66" + }, + "open_interest": { + "type": "string", + "example": "235.25" + }, + "open_interest_limit": { + "type": "string", + "example": "235.25" + }, + "funding_clamp_small": { + "type": "string", + "example": "0.005" + }, + "funding_clamp_big": { + "type": "string", + "example": "0.4" + }, "last_trade_price": { - "type": "number", - "format": "double", + "type": "string", "example": "3024.66" }, - "daily_trades_count": { + "current_funding_rate": { + "type": "string", + "example": "0.0001" + }, + "funding_rate": { + "type": "string", + "example": "0.0001" + }, + "funding_timestamp": { "type": "integer", "format": "int64", - "example": "68" + "example": "1640995200" }, "daily_base_token_volume": { "type": "number", @@ -4730,71 +5024,241 @@ "format": "double", "example": "93566.25" }, + "daily_price_low": { + "type": "number", + "format": "double", + "example": "3014.66" + }, + "daily_price_high": { + "type": "number", + "format": "double", + "example": "3024.66" + }, "daily_price_change": { "type": "number", "format": "double", "example": "3.66" } }, - "title": "OrderBookStats", + "title": "PerpsMarketStats", "required": [ "symbol", + "market_id", + "index_price", + "mark_price", + "open_interest", + "open_interest_limit", + "funding_clamp_small", + "funding_clamp_big", "last_trade_price", - "daily_trades_count", + "current_funding_rate", + "funding_rate", + "funding_timestamp", "daily_base_token_volume", "daily_quote_token_volume", + "daily_price_low", + "daily_price_high", "daily_price_change" ] }, - "OrderBooks": { + "PerpsOrderBookDetail": { "type": "object", "properties": { - "code": { + "symbol": { + "type": "string", + "example": "ETH" + }, + "market_id": { "type": "integer", - "format": "int32", - "example": "200" + "format": "int16", + "example": "1" }, - "message": { - "type": "string" + "market_type": { + "type": "string", + "example": "perp", + "enum": [ + "perp", + "spot" + ] }, - "order_books": { - "type": "array", - "items": { - "$ref": "#/definitions/OrderBook" - } - } - }, - "title": "OrderBooks", - "required": [ - "code", - "order_books" - ] - }, - "Orders": { - "type": "object", - "properties": { - "code": { + "base_asset_id": { "type": "integer", - "format": "int32", - "example": "200" + "format": "int16", + "example": "1" }, - "message": { - "type": "string" + "quote_asset_id": { + "type": "integer", + "format": "int16", + "example": "2" }, - "next_cursor": { - "type": "string" + "status": { + "type": "string", + "example": "active", + "enum": [ + "inactive", + "active" + ] }, - "orders": { - "type": "array", - "items": { - "$ref": "#/definitions/Order" + "taker_fee": { + "type": "string", + "example": "0.0001" + }, + "maker_fee": { + "type": "string", + "example": "0.0000" + }, + "liquidation_fee": { + "type": "string", + "example": "0.01" + }, + "min_base_amount": { + "type": "string", + "example": "0.01" + }, + "min_quote_amount": { + "type": "string", + "example": "0.1" + }, + "order_quote_limit": { + "type": "string", + "example": "235.25" + }, + "supported_size_decimals": { + "type": "integer", + "format": "uint8", + "example": "4" + }, + "supported_price_decimals": { + "type": "integer", + "format": "uint8", + "example": "4" + }, + "supported_quote_decimals": { + "type": "integer", + "format": "uint8", + "example": "4" + }, + "size_decimals": { + "type": "integer", + "format": "uint8", + "example": "4" + }, + "price_decimals": { + "type": "integer", + "format": "uint8", + "example": "4" + }, + "quote_multiplier": { + "type": "integer", + "format": "int64", + "example": "10000" + }, + "default_initial_margin_fraction": { + "type": "integer", + "format": "uin16", + "example": "100" + }, + "min_initial_margin_fraction": { + "type": "integer", + "format": "uin16", + "example": "100" + }, + "maintenance_margin_fraction": { + "type": "integer", + "format": "uin16", + "example": "50" + }, + "closeout_margin_fraction": { + "type": "integer", + "format": "uin16", + "example": "100" + }, + "last_trade_price": { + "type": "number", + "format": "double", + "example": "3024.66" + }, + "daily_trades_count": { + "type": "integer", + "format": "int64", + "example": "68" + }, + "daily_base_token_volume": { + "type": "number", + "format": "double", + "example": "235.25" + }, + "daily_quote_token_volume": { + "type": "number", + "format": "double", + "example": "93566.25" + }, + "daily_price_low": { + "type": "number", + "format": "double", + "example": "3014.66" + }, + "daily_price_high": { + "type": "number", + "format": "double", + "example": "3024.66" + }, + "daily_price_change": { + "type": "number", + "format": "double", + "example": "3.66" + }, + "open_interest": { + "type": "number", + "format": "double", + "example": "93.0" + }, + "daily_chart": { + "type": "object", + "example": "{1640995200:3024.66}", + "additionalProperties": { + "type": "number", + "format": "double" } + }, + "market_config": { + "$ref": "#/definitions/MarketConfig" } }, - "title": "Orders", + "title": "PerpsOrderBookDetail", "required": [ - "code", - "orders" + "symbol", + "market_id", + "market_type", + "base_asset_id", + "quote_asset_id", + "status", + "taker_fee", + "maker_fee", + "liquidation_fee", + "min_base_amount", + "min_quote_amount", + "order_quote_limit", + "supported_size_decimals", + "supported_price_decimals", + "supported_quote_decimals", + "size_decimals", + "price_decimals", + "quote_multiplier", + "default_initial_margin_fraction", + "min_initial_margin_fraction", + "maintenance_margin_fraction", + "closeout_margin_fraction", + "last_trade_price", + "daily_trades_count", + "daily_base_token_volume", + "daily_quote_token_volume", + "daily_price_low", + "daily_price_high", + "daily_price_change", + "open_interest", + "daily_chart", + "market_config" ] }, "PnLEntry": { @@ -4810,6 +5274,11 @@ "format": "double", "example": "12.0" }, + "trade_spot_pnl": { + "type": "number", + "format": "double", + "example": "12.0" + }, "inflow": { "type": "number", "format": "double", @@ -4820,6 +5289,16 @@ "format": "double", "example": "12.0" }, + "spot_outflow": { + "type": "number", + "format": "double", + "example": "12.0" + }, + "spot_inflow": { + "type": "number", + "format": "double", + "example": "12.0" + }, "pool_pnl": { "type": "number", "format": "double", @@ -4845,8 +5324,11 @@ "required": [ "timestamp", "trade_pnl", + "trade_spot_pnl", "inflow", "outflow", + "spot_outflow", + "spot_inflow", "pool_pnl", "pool_inflow", "pool_outflow", @@ -4863,7 +5345,7 @@ }, "market_id": { "type": "integer", - "format": "uint8", + "format": "int16", "example": "1" }, "funding_id": { @@ -4908,159 +5390,44 @@ "properties": { "code": { "type": "integer", - "format": "int32", - "example": "200" - }, - "message": { - "type": "string" - }, - "position_fundings": { - "type": "array", - "items": { - "$ref": "#/definitions/PositionFunding" - } - }, - "next_cursor": { - "type": "string" - } - }, - "title": "PositionFundings", - "required": [ - "code", - "position_fundings" - ] - }, - "PriceLevel": { - "type": "object", - "properties": { - "price": { - "type": "string", - "example": "3024.66" - }, - "size": { - "type": "string", - "example": "0.1" - } - }, - "title": "PriceLevel", - "required": [ - "price", - "size" - ] - }, - "PublicPool": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32", - "example": "200" - }, - "message": { - "type": "string" - }, - "account_type": { - "type": "integer", - "format": "uint8", - "example": "1" - }, - "index": { - "type": "integer", - "format": "int64", - "example": "1" - }, - "l1_address": { - "type": "string", - "example": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" - }, - "cancel_all_time": { - "type": "integer", - "format": "int64", - "example": "1640995200" - }, - "total_order_count": { - "type": "integer", - "format": "int64", - "example": "100" - }, - "total_isolated_order_count": { - "type": "integer", - "format": "int64", - "example": "100" - }, - "pending_order_count": { - "type": "integer", - "format": "int64", - "example": "100" - }, - "available_balance": { - "type": "string", - "example": "19995" - }, - "status": { - "type": "integer", - "format": "uint8", - "example": "1" - }, - "collateral": { - "type": "string", - "example": "46342" - }, - "account_index": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" + "format": "int32", + "example": "200" }, - "description": { + "message": { "type": "string" }, - "can_invite": { - "type": "boolean", - "format": "boolean", - "description": " Remove After FE uses L1 meta endpoint" - }, - "referral_points_percentage": { - "type": "string", - "description": " Remove After FE uses L1 meta endpoint" + "position_fundings": { + "type": "array", + "items": { + "$ref": "#/definitions/PositionFunding" + } }, - "total_asset_value": { + "next_cursor": { + "type": "string" + } + }, + "title": "PositionFundings", + "required": [ + "code", + "position_fundings" + ] + }, + "PriceLevel": { + "type": "object", + "properties": { + "price": { "type": "string", - "example": "19995" + "example": "3024.66" }, - "cross_asset_value": { + "size": { "type": "string", - "example": "19995" - }, - "pool_info": { - "$ref": "#/definitions/PublicPoolInfo" - }, - "account_share": { - "$ref": "#/definitions/PublicPoolShare" + "example": "0.1" } }, - "title": "PublicPool", + "title": "PriceLevel", "required": [ - "code", - "account_type", - "index", - "l1_address", - "cancel_all_time", - "total_order_count", - "total_isolated_order_count", - "pending_order_count", - "available_balance", - "status", - "collateral", - "account_index", - "name", - "description", - "can_invite", - "referral_points_percentage", - "total_asset_value", - "cross_asset_value", - "pool_info" + "price", + "size" ] }, "PublicPoolInfo": { @@ -5094,6 +5461,11 @@ "format": "double", "example": "20.5000" }, + "sharpe_ratio": { + "type": "number", + "format": "double", + "example": "1.5" + }, "daily_returns": { "type": "array", "items": { @@ -5115,6 +5487,7 @@ "total_shares", "operator_shares", "annual_percentage_yield", + "sharpe_ratio", "daily_returns", "share_prices" ] @@ -5135,6 +5508,15 @@ "format": "int64", "example": "3" }, + "created_at": { + "type": "integer", + "format": "int64" + }, + "master_account_index": { + "type": "integer", + "format": "int64", + "example": "61" + }, "account_type": { "type": "integer", "format": "uint8", @@ -5152,6 +5534,11 @@ "format": "double", "example": "20.5000" }, + "sharpe_ratio": { + "type": "number", + "format": "double", + "example": "1.5" + }, "status": { "type": "integer", "format": "uint8", @@ -5178,10 +5565,13 @@ "required": [ "code", "account_index", + "created_at", + "master_account_index", "account_type", "name", "l1_address", "annual_percentage_yield", + "sharpe_ratio", "status", "operator_fee", "total_asset_value", @@ -5213,120 +5603,6 @@ "entry_usdc" ] }, - "PublicPools": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32", - "example": "200" - }, - "message": { - "type": "string" - }, - "total": { - "type": "integer", - "format": "int64" - }, - "public_pools": { - "type": "array", - "items": { - "$ref": "#/definitions/PublicPool" - } - } - }, - "title": "PublicPools", - "required": [ - "code", - "total", - "public_pools" - ] - }, - "ReferralPointEntry": { - "type": "object", - "properties": { - "l1_address": { - "type": "string" - }, - "total_points": { - "type": "integer", - "format": "int64", - "example": "1000" - }, - "week_points": { - "type": "integer", - "format": "int64", - "example": "1000" - }, - "total_reward_points": { - "type": "integer", - "format": "int64", - "example": "200" - }, - "week_reward_points": { - "type": "integer", - "format": "int64", - "example": "200" - }, - "reward_point_multiplier": { - "type": "string", - "example": "0.1" - } - }, - "title": "ReferralPointEntry", - "required": [ - "l1_address", - "total_points", - "week_points", - "total_reward_points", - "week_reward_points", - "reward_point_multiplier" - ] - }, - "ReferralPoints": { - "type": "object", - "properties": { - "referrals": { - "type": "array", - "items": { - "$ref": "#/definitions/ReferralPointEntry" - } - }, - "user_total_points": { - "type": "integer", - "format": "int64", - "example": "1000" - }, - "user_last_week_points": { - "type": "integer", - "format": "int64", - "example": "1000" - }, - "user_total_referral_reward_points": { - "type": "integer", - "format": "int64", - "example": "1000" - }, - "user_last_week_referral_reward_points": { - "type": "integer", - "format": "int64", - "example": "1000" - }, - "reward_point_multiplier": { - "type": "string", - "example": "0.1" - } - }, - "title": "ReferralPoints", - "required": [ - "referrals", - "user_total_points", - "user_last_week_points", - "user_total_referral_reward_points", - "user_last_week_referral_reward_points", - "reward_point_multiplier" - ] - }, "ReqAckNotif": { "type": "object", "properties": { @@ -5370,11 +5646,30 @@ "new_tier" ] }, + "ReqDoFaucet": { + "type": "object", + "properties": { + "l1_address": { + "type": "string" + }, + "do_l1_transfer": { + "type": "boolean", + "format": "boolean", + "default": "false" + } + }, + "title": "ReqDoFaucet", + "required": [ + "l1_address", + "do_l1_transfer" + ] + }, "ReqExportData": { "type": "object", "properties": { "auth": { - "type": "string" + "type": "string", + "description": " made optional to support header auth clients" }, "account_index": { "type": "integer", @@ -5383,7 +5678,7 @@ }, "market_id": { "type": "integer", - "format": "uint8", + "format": "int16", "default": "255" }, "type": { @@ -5399,6 +5694,26 @@ "type" ] }, + "ReqFastwithdraw": { + "type": "object", + "properties": { + "tx_info": { + "type": "string" + }, + "to_address": { + "type": "string" + }, + "auth": { + "type": "string", + "description": " made optional to support header auth clients" + } + }, + "title": "ReqFastwithdraw", + "required": [ + "tx_info", + "to_address" + ] + }, "ReqGetAccount": { "type": "object", "properties": { @@ -5422,17 +5737,17 @@ "ReqGetAccountActiveOrders": { "type": "object", "properties": { + "auth": { + "type": "string", + "description": " made optional to support header auth clients" + }, "account_index": { "type": "integer", "format": "int64" }, "market_id": { "type": "integer", - "format": "uint8" - }, - "auth": { - "type": "string", - "description": " made optional to support header auth clients" + "format": "int16" } }, "title": "ReqGetAccountActiveOrders", @@ -5484,7 +5799,7 @@ }, "market_id": { "type": "integer", - "format": "uint8", + "format": "int16", "default": "255" }, "ask_filter": { @@ -5555,7 +5870,8 @@ "type": "object", "properties": { "auth": { - "type": "string" + "type": "string", + "description": " made optional to support header auth clients" }, "by": { "type": "string", @@ -5629,19 +5945,44 @@ "value": { "type": "string" }, + "auth": { + "type": "string", + "description": " made optional to support header auth clients" + }, "types": { "type": "array", "items": { "type": "integer", "format": "uint8" } - }, - "auth": { - "type": "string" } }, "title": "ReqGetAccountTxs" }, + "ReqGetApiTokens": { + "type": "object", + "properties": { + "account_index": { + "type": "integer", + "format": "int64" + } + }, + "title": "ReqGetApiTokens", + "required": [ + "account_index" + ] + }, + "ReqGetAssetDetails": { + "type": "object", + "properties": { + "asset_id": { + "type": "integer", + "format": "int16", + "default": "0" + } + }, + "title": "ReqGetAssetDetails" + }, "ReqGetBlock": { "type": "object", "properties": { @@ -5682,6 +6023,18 @@ "value" ] }, + "ReqGetBridgesByL1Addr": { + "type": "object", + "properties": { + "l1_address": { + "type": "string" + } + }, + "title": "ReqGetBridgesByL1Addr", + "required": [ + "l1_address" + ] + }, "ReqGetByAccount": { "type": "object", "properties": { @@ -5701,12 +6054,12 @@ "value" ] }, - "ReqGetCandlesticks": { + "ReqGetCandles": { "type": "object", "properties": { "market_id": { "type": "integer", - "format": "uint8" + "format": "int16" }, "resolution": { "type": "string", @@ -5714,9 +6067,12 @@ "1m", "5m", "15m", + "30m", "1h", "4h", - "1d" + "12h", + "1d", + "1w" ] }, "start_timestamp": { @@ -5739,7 +6095,7 @@ "default": "false" } }, - "title": "ReqGetCandlesticks", + "title": "ReqGetCandles", "required": [ "market_id", "resolution", @@ -5751,14 +6107,14 @@ "ReqGetDepositHistory": { "type": "object", "properties": { - "account_index": { - "type": "integer", - "format": "int64" - }, "auth": { "type": "string", "description": " made optional to support header auth clients" }, + "account_index": { + "type": "integer", + "format": "int64" + }, "l1_address": { "type": "string" }, @@ -5787,13 +6143,13 @@ "ReqGetFastWithdrawInfo": { "type": "object", "properties": { - "account_index": { - "type": "integer", - "format": "int64" - }, "auth": { "type": "string", "description": " made optional to support header auth clients" + }, + "account_index": { + "type": "integer", + "format": "int64" } }, "title": "ReqGetFastWithdrawInfo", @@ -5806,7 +6162,7 @@ "properties": { "market_id": { "type": "integer", - "format": "uint8" + "format": "int16" }, "resolution": { "type": "string", @@ -5839,6 +6195,14 @@ "count_back" ] }, + "ReqGetGeckoContracts": { + "type": "object", + "title": "ReqGetGeckoContracts" + }, + "ReqGetGeckoTickers": { + "type": "object", + "title": "ReqGetGeckoTickers" + }, "ReqGetL1Metadata": { "type": "object", "properties": { @@ -5892,7 +6256,7 @@ }, "market_id": { "type": "integer", - "format": "uint8", + "format": "int16", "default": "255" }, "cursor": { @@ -5934,8 +6298,17 @@ "properties": { "market_id": { "type": "integer", - "format": "uint8", + "format": "int16", "default": "255" + }, + "filter": { + "type": "string", + "enum": [ + "all", + "spot", + "perp" + ], + "default": "all" } }, "title": "ReqGetOrderBookDetails" @@ -5945,12 +6318,12 @@ "properties": { "market_id": { "type": "integer", - "format": "uint8" + "format": "int16" }, "limit": { "type": "integer", "format": "int64", - "maximum": 100, + "maximum": 250, "minimum": 1 } }, @@ -5965,8 +6338,17 @@ "properties": { "market_id": { "type": "integer", - "format": "uint8", + "format": "int16", "default": "255" + }, + "filter": { + "type": "string", + "enum": [ + "all", + "spot", + "perp" + ], + "default": "all" } }, "title": "ReqGetOrderBooks" @@ -5975,7 +6357,8 @@ "type": "object", "properties": { "auth": { - "type": "string" + "type": "string", + "description": " made optional to support header auth clients" }, "account_index": { "type": "integer", @@ -5983,7 +6366,7 @@ }, "market_id": { "type": "integer", - "format": "uint8", + "format": "int16", "default": "255" }, "cursor": { @@ -6011,47 +6394,12 @@ "limit" ] }, - "ReqGetPublicPools": { - "type": "object", - "properties": { - "auth": { - "type": "string" - }, - "filter": { - "type": "string", - "enum": [ - "all", - "user", - "protocol", - "account_index" - ] - }, - "index": { - "type": "integer", - "format": "int64" - }, - "limit": { - "type": "integer", - "format": "int64", - "maximum": 100, - "minimum": 1 - }, - "account_index": { - "type": "integer", - "format": "int64" - } - }, - "title": "ReqGetPublicPools", - "required": [ - "index", - "limit" - ] - }, "ReqGetPublicPoolsMetadata": { "type": "object", "properties": { "auth": { - "type": "string" + "type": "string", + "description": " made optional to support header auth clients" }, "filter": { "type": "string", @@ -6149,7 +6497,7 @@ "properties": { "market_id": { "type": "integer", - "format": "uint8" + "format": "int16" }, "limit": { "type": "integer", @@ -6164,32 +6512,16 @@ "limit" ] }, - "ReqGetReferralPoints": { + "ReqGetTrades": { "type": "object", "properties": { "auth": { "type": "string", "description": " made optional to support header auth clients" }, - "account_index": { - "type": "integer", - "format": "int64" - } - }, - "title": "ReqGetReferralPoints", - "required": [ - "account_index" - ] - }, - "ReqGetTrades": { - "type": "object", - "properties": { - "auth": { - "type": "string" - }, "market_id": { "type": "integer", - "format": "uint8", + "format": "int16", "default": "255" }, "account_index": { @@ -6229,11 +6561,36 @@ "format": "int8", "default": "-1" }, + "role": { + "type": "string", + "enum": [ + "all", + "maker", + "taker" + ], + "default": "all" + }, + "type": { + "type": "string", + "enum": [ + "all", + "trade", + "liquidation", + "deleverage", + "market-settlement" + ], + "default": "all" + }, "limit": { "type": "integer", "format": "int64", "maximum": 100, "minimum": 1 + }, + "aggregate": { + "type": "boolean", + "format": "boolean", + "default": "false" } }, "title": "ReqGetTrades", @@ -6246,7 +6603,8 @@ "type": "object", "properties": { "auth": { - "type": "string" + "type": "string", + "description": " made optional to support header auth clients" }, "account_index": { "type": "integer", @@ -6266,14 +6624,14 @@ "ReqGetTransferHistory": { "type": "object", "properties": { - "account_index": { - "type": "integer", - "format": "int64" - }, "auth": { "type": "string", "description": " made optional to support header auth clients" }, + "account_index": { + "type": "integer", + "format": "int64" + }, "cursor": { "type": "string" } @@ -6303,73 +6661,239 @@ "value" ] }, - "ReqGetWithdrawHistory": { + "ReqGetWithdrawHistory": { + "type": "object", + "properties": { + "auth": { + "type": "string", + "description": " made optional to support header auth clients" + }, + "account_index": { + "type": "integer", + "format": "int64" + }, + "cursor": { + "type": "string" + }, + "filter": { + "type": "string", + "enum": [ + "all", + "pending", + "claimable" + ] + } + }, + "title": "ReqGetWithdrawHistory", + "required": [ + "account_index" + ] + }, + "ReqPostApiToken": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "account_index": { + "type": "integer", + "format": "int64" + }, + "expiry": { + "type": "integer", + "format": "int64" + }, + "sub_account_access": { + "type": "boolean", + "format": "boolean" + }, + "scopes": { + "type": "string", + "example": "read.*", + "default": "read.*" + } + }, + "title": "ReqPostApiToken", + "required": [ + "name", + "account_index", + "expiry", + "sub_account_access" + ] + }, + "ReqRevokeApiToken": { + "type": "object", + "properties": { + "token_id": { + "type": "integer", + "format": "int64" + }, + "account_index": { + "type": "integer", + "format": "int64" + } + }, + "title": "ReqRevokeApiToken", + "required": [ + "token_id", + "account_index" + ] + }, + "ReqSendTx": { + "type": "object", + "properties": { + "tx_type": { + "type": "integer", + "format": "uint8" + }, + "tx_info": { + "type": "string" + }, + "price_protection": { + "type": "boolean", + "format": "boolean", + "default": "true" + } + }, + "title": "ReqSendTx", + "required": [ + "tx_type", + "tx_info" + ] + }, + "ReqSendTxBatch": { + "type": "object", + "properties": { + "tx_types": { + "type": "string" + }, + "tx_infos": { + "type": "string" + } + }, + "title": "ReqSendTxBatch", + "required": [ + "tx_types", + "tx_infos" + ] + }, + "RespChangeAccountTier": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32", + "example": "200" + }, + "message": { + "type": "string" + } + }, + "title": "RespChangeAccountTier", + "required": [ + "code" + ] + }, + "RespGetApiTokens": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32", + "example": "200" + }, + "message": { + "type": "string" + }, + "api_tokens": { + "type": "array", + "items": { + "$ref": "#/definitions/ApiToken" + } + } + }, + "title": "RespGetApiTokens", + "required": [ + "code", + "api_tokens" + ] + }, + "RespGetBridgesByL1Addr": { "type": "object", "properties": { - "account_index": { + "code": { "type": "integer", - "format": "int64" - }, - "auth": { - "type": "string", - "description": " made optional to support header auth clients" + "format": "int32", + "example": "200" }, - "cursor": { + "message": { "type": "string" }, - "filter": { - "type": "string", - "enum": [ - "all", - "pending", - "claimable" - ] + "bridges": { + "type": "array", + "items": { + "$ref": "#/definitions/Bridge" + } } }, - "title": "ReqGetWithdrawHistory", + "title": "RespGetBridgesByL1Addr", "required": [ - "account_index" + "code", + "bridges" ] }, - "ReqSendTx": { + "RespGetFastBridgeInfo": { "type": "object", "properties": { - "tx_type": { + "code": { "type": "integer", - "format": "uint8" + "format": "int32", + "example": "200" }, - "tx_info": { + "message": { "type": "string" }, - "price_protection": { - "type": "boolean", - "format": "boolean", - "default": "true" + "fast_bridge_limit": { + "type": "string" } }, - "title": "ReqSendTx", + "title": "RespGetFastBridgeInfo", "required": [ - "tx_type", - "tx_info" + "code", + "fast_bridge_limit" ] }, - "ReqSendTxBatch": { + "RespGetFastwithdrawalInfo": { "type": "object", "properties": { - "tx_types": { + "code": { + "type": "integer", + "format": "int32", + "example": "200" + }, + "message": { "type": "string" }, - "tx_infos": { + "to_account_index": { + "type": "integer", + "format": "int64" + }, + "withdraw_limit": { + "type": "string" + }, + "max_withdrawal_amount": { "type": "string" } }, - "title": "ReqSendTxBatch", + "title": "RespGetFastwithdrawalInfo", "required": [ - "tx_types", - "tx_infos" + "code", + "to_account_index", + "withdraw_limit", + "max_withdrawal_amount" ] }, - "RespChangeAccountTier": { + "RespGetIsNextBridgeFast": { "type": "object", "properties": { "code": { @@ -6379,14 +6903,19 @@ }, "message": { "type": "string" + }, + "is_next_bridge_fast": { + "type": "boolean", + "format": "boolean" } }, - "title": "RespChangeAccountTier", + "title": "RespGetIsNextBridgeFast", "required": [ - "code" + "code", + "is_next_bridge_fast" ] }, - "RespGetFastBridgeInfo": { + "RespPostApiToken": { "type": "object", "properties": { "code": { @@ -6397,14 +6926,47 @@ "message": { "type": "string" }, - "fast_bridge_limit": { + "token_id": { + "type": "integer", + "format": "int64" + }, + "api_token": { + "type": "string" + }, + "name": { + "type": "string" + }, + "account_index": { + "type": "integer", + "format": "int64" + }, + "expiry": { + "type": "integer", + "format": "int64" + }, + "sub_account_access": { + "type": "boolean", + "format": "boolean" + }, + "revoked": { + "type": "boolean", + "format": "boolean" + }, + "scopes": { "type": "string" } }, - "title": "RespGetFastBridgeInfo", + "title": "RespPostApiToken", "required": [ "code", - "fast_bridge_limit" + "token_id", + "api_token", + "name", + "account_index", + "expiry", + "sub_account_access", + "revoked", + "scopes" ] }, "RespPublicPoolsMetadata": { @@ -6431,6 +6993,33 @@ "public_pools" ] }, + "RespRevokeApiToken": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32", + "example": "200" + }, + "message": { + "type": "string" + }, + "token_id": { + "type": "integer", + "format": "int64" + }, + "revoked": { + "type": "boolean", + "format": "boolean" + } + }, + "title": "RespRevokeApiToken", + "required": [ + "code", + "token_id", + "revoked" + ] + }, "RespSendTx": { "type": "object", "properties": { @@ -6450,13 +7039,18 @@ "type": "integer", "format": "int64", "example": "1751465474" + }, + "volume_quota_remaining": { + "type": "integer", + "format": "int64" } }, "title": "RespSendTx", "required": [ "code", "tx_hash", - "predicted_execution_time_ms" + "predicted_execution_time_ms", + "volume_quota_remaining" ] }, "RespSendTxBatch": { @@ -6480,13 +7074,18 @@ "type": "integer", "format": "int64", "example": "1751465474" + }, + "volume_quota_remaining": { + "type": "integer", + "format": "int64" } }, "title": "RespSendTxBatch", "required": [ "code", "tx_hash", - "predicted_execution_time_ms" + "predicted_execution_time_ms", + "volume_quota_remaining" ] }, "RespWithdrawalDelay": { @@ -6544,7 +7143,7 @@ "properties": { "market_id": { "type": "integer", - "format": "uint8" + "format": "int16" }, "collateral": { "type": "string" @@ -6600,42 +7199,272 @@ "format": "int64", "example": "1" }, - "order_id": { + "order_id": { + "type": "string", + "example": "1" + }, + "owner_account_index": { + "type": "integer", + "format": "int64", + "example": "1" + }, + "initial_base_amount": { + "type": "string", + "example": "0.1" + }, + "remaining_base_amount": { + "type": "string", + "example": "0.1" + }, + "price": { + "type": "string", + "example": "3024.66" + }, + "order_expiry": { + "type": "integer", + "format": "int64", + "example": "1640995200" + }, + "transaction_time": { + "type": "integer", + "format": "int64", + "example": "1257894000000000" + } + }, + "title": "SimpleOrder", + "required": [ + "order_index", + "order_id", + "owner_account_index", + "initial_base_amount", + "remaining_base_amount", + "price", + "order_expiry", + "transaction_time" + ] + }, + "SpotMarketStats": { + "type": "object", + "properties": { + "symbol": { + "type": "string", + "example": "ETH/USDC" + }, + "market_id": { + "type": "integer", + "format": "int16", + "example": "1" + }, + "index_price": { + "type": "string", + "example": "3024.66" + }, + "mid_price": { + "type": "string", + "example": "3024.66" + }, + "last_trade_price": { + "type": "string", + "example": "3024.66" + }, + "daily_base_token_volume": { + "type": "number", + "format": "double", + "example": "235.25" + }, + "daily_quote_token_volume": { + "type": "number", + "format": "double", + "example": "93566.25" + }, + "daily_price_low": { + "type": "number", + "format": "double", + "example": "3014.66" + }, + "daily_price_high": { + "type": "number", + "format": "double", + "example": "3024.66" + }, + "daily_price_change": { + "type": "number", + "format": "double", + "example": "3.66" + } + }, + "title": "SpotMarketStats", + "required": [ + "symbol", + "market_id", + "index_price", + "mid_price", + "last_trade_price", + "daily_base_token_volume", + "daily_quote_token_volume", + "daily_price_low", + "daily_price_high", + "daily_price_change" + ] + }, + "SpotOrderBookDetail": { + "type": "object", + "properties": { + "symbol": { + "type": "string", + "example": "ETH" + }, + "market_id": { + "type": "integer", + "format": "int16", + "example": "1" + }, + "market_type": { + "type": "string", + "example": "perp", + "enum": [ + "perp", + "spot" + ] + }, + "base_asset_id": { + "type": "integer", + "format": "int16", + "example": "1" + }, + "quote_asset_id": { + "type": "integer", + "format": "int16", + "example": "2" + }, + "status": { + "type": "string", + "example": "active", + "enum": [ + "inactive", + "active" + ] + }, + "taker_fee": { + "type": "string", + "example": "0.0001" + }, + "maker_fee": { "type": "string", - "example": "1" + "example": "0.0000" }, - "owner_account_index": { - "type": "integer", - "format": "int64", - "example": "1" + "liquidation_fee": { + "type": "string", + "example": "0.01" }, - "initial_base_amount": { + "min_base_amount": { "type": "string", - "example": "0.1" + "example": "0.01" }, - "remaining_base_amount": { + "min_quote_amount": { "type": "string", "example": "0.1" }, - "price": { + "order_quote_limit": { "type": "string", + "example": "235.25" + }, + "supported_size_decimals": { + "type": "integer", + "format": "uint8", + "example": "4" + }, + "supported_price_decimals": { + "type": "integer", + "format": "uint8", + "example": "4" + }, + "supported_quote_decimals": { + "type": "integer", + "format": "uint8", + "example": "4" + }, + "size_decimals": { + "type": "integer", + "format": "uint8", + "example": "4" + }, + "price_decimals": { + "type": "integer", + "format": "uint8", + "example": "4" + }, + "last_trade_price": { + "type": "number", + "format": "double", "example": "3024.66" }, - "order_expiry": { + "daily_trades_count": { "type": "integer", "format": "int64", - "example": "1640995200" + "example": "68" + }, + "daily_base_token_volume": { + "type": "number", + "format": "double", + "example": "235.25" + }, + "daily_quote_token_volume": { + "type": "number", + "format": "double", + "example": "93566.25" + }, + "daily_price_low": { + "type": "number", + "format": "double", + "example": "3014.66" + }, + "daily_price_high": { + "type": "number", + "format": "double", + "example": "3024.66" + }, + "daily_price_change": { + "type": "number", + "format": "double", + "example": "3.66" + }, + "daily_chart": { + "type": "object", + "example": "{1640995200:3024.66}", + "additionalProperties": { + "type": "number", + "format": "double" + } } }, - "title": "SimpleOrder", + "title": "SpotOrderBookDetail", "required": [ - "order_index", - "order_id", - "owner_account_index", - "initial_base_amount", - "remaining_base_amount", - "price", - "order_expiry" + "symbol", + "market_id", + "market_type", + "base_asset_id", + "quote_asset_id", + "status", + "taker_fee", + "maker_fee", + "liquidation_fee", + "min_base_amount", + "min_quote_amount", + "order_quote_limit", + "supported_size_decimals", + "supported_price_decimals", + "supported_quote_decimals", + "size_decimals", + "price_decimals", + "last_trade_price", + "daily_trades_count", + "daily_base_token_volume", + "daily_quote_token_volume", + "daily_price_low", + "daily_price_high", + "daily_price_change", + "daily_chart" ] }, "Status": { @@ -6733,12 +7562,13 @@ "enum": [ "trade", "liquidation", - "deleverage" + "deleverage", + "market-settlement" ] }, "market_id": { "type": "integer", - "format": "uint8", + "format": "int16", "example": "1" }, "size": { @@ -6763,6 +7593,16 @@ "format": "int64", "example": "245" }, + "ask_client_id": { + "type": "integer", + "format": "int64", + "example": "145" + }, + "bid_client_id": { + "type": "integer", + "format": "int64", + "example": "245" + }, "ask_account_id": { "type": "integer", "format": "int64", @@ -6833,6 +7673,11 @@ "type": "boolean", "format": "boolean", "example": "true" + }, + "transaction_time": { + "type": "integer", + "format": "int64", + "example": "1257894000000000" } }, "title": "Trade", @@ -6846,6 +7691,8 @@ "usd_amount", "ask_id", "bid_id", + "ask_client_id", + "bid_client_id", "ask_account_id", "bid_account_id", "is_maker_ask", @@ -6860,7 +7707,8 @@ "maker_position_size_before", "maker_entry_quote_before", "maker_initial_margin_fraction_before", - "maker_position_sign_changed" + "maker_position_sign_changed", + "transaction_time" ] }, "Trades": { @@ -6946,10 +7794,19 @@ "id": { "type": "string" }, + "asset_id": { + "type": "integer", + "format": "int16", + "example": "1" + }, "amount": { "type": "string", "example": "0.1" }, + "fee": { + "type": "string", + "example": "3" + }, "timestamp": { "type": "integer", "format": "int64", @@ -6959,7 +7816,12 @@ "type": "string", "enum": [ "L2TransferInflow", - "L2TransferOutflow" + "L2TransferOutflow", + "L2BurnSharesInflow", + "L2BurnSharesOutflow", + "L2MintSharesInflow", + "L2MintSharesOutflow", + "L2SelfTransfer" ] }, "from_l1_address": { @@ -6980,6 +7842,20 @@ "format": "int64", "example": "1" }, + "from_route": { + "type": "string", + "enum": [ + "spot", + "perps" + ] + }, + "to_route": { + "type": "string", + "enum": [ + "spot", + "perps" + ] + }, "tx_hash": { "type": "string", "example": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" @@ -6988,111 +7864,20 @@ "title": "TransferHistoryItem", "required": [ "id", + "asset_id", "amount", + "fee", "timestamp", "type", "from_l1_address", "to_l1_address", "from_account_index", "to_account_index", + "from_route", + "to_route", "tx_hash" ] }, - "Tx": { - "type": "object", - "properties": { - "hash": { - "type": "string", - "example": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" - }, - "type": { - "type": "integer", - "format": "uint8", - "example": "1", - "maximum": 64, - "minimum": 1 - }, - "info": { - "type": "string", - "example": "{}" - }, - "event_info": { - "type": "string", - "example": "{}" - }, - "status": { - "type": "integer", - "format": "int64", - "example": "1" - }, - "transaction_index": { - "type": "integer", - "format": "int64", - "example": "8761" - }, - "l1_address": { - "type": "string", - "example": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" - }, - "account_index": { - "type": "integer", - "format": "int64", - "example": "1" - }, - "nonce": { - "type": "integer", - "format": "int64", - "example": "722" - }, - "expire_at": { - "type": "integer", - "format": "int64", - "example": "1640995200" - }, - "block_height": { - "type": "integer", - "format": "int64", - "example": "45434" - }, - "queued_at": { - "type": "integer", - "format": "int64", - "example": "1640995200" - }, - "executed_at": { - "type": "integer", - "format": "int64", - "example": "1640995200" - }, - "sequence_index": { - "type": "integer", - "format": "int64", - "example": "8761" - }, - "parent_hash": { - "type": "string", - "example": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" - } - }, - "title": "Tx", - "required": [ - "hash", - "type", - "info", - "event_info", - "status", - "transaction_index", - "l1_address", - "account_index", - "nonce", - "expire_at", - "block_height", - "queued_at", - "executed_at", - "sequence_index", - "parent_hash" - ] - }, "TxHash": { "type": "object", "properties": { @@ -7139,30 +7924,6 @@ "tx_hash" ] }, - "Txs": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32", - "example": "200" - }, - "message": { - "type": "string" - }, - "txs": { - "type": "array", - "items": { - "$ref": "#/definitions/Tx" - } - } - }, - "title": "Txs", - "required": [ - "code", - "txs" - ] - }, "ValidatorInfo": { "type": "object", "properties": { @@ -7216,6 +7977,11 @@ "id": { "type": "string" }, + "asset_id": { + "type": "integer", + "format": "int16", + "example": "1" + }, "amount": { "type": "string", "example": "0.1" @@ -7250,6 +8016,7 @@ "title": "WithdrawHistoryItem", "required": [ "id", + "asset_id", "amount", "timestamp", "status", @@ -7279,4 +8046,4 @@ "in": "header" } } -} +} \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 352334a..065285b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "lighter-sdk" -version = "0.1.4" +version = "1.0.3" description = "Python client for Lighter" authors = ["elliot"] license = "NoLicense" diff --git a/setup.py b/setup.py index 26548d7..2965670 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools NAME = "lighter-sdk" -VERSION = "0.1.4" +VERSION = "1.0.3" PYTHON_REQUIRES = ">=3.7" REQUIRES = [ "urllib3 >= 1.25.3, < 2.1.0",