├── .gitignore ├── .gitmodules ├── LICENSE ├── README.md ├── build ├── build.ts ├── package-meta.json └── package.json ├── examples ├── async.py ├── sync.py └── websockets.py ├── hyperliquid ├── __init__.py └── ccxt │ ├── __init__.py │ ├── abstract │ └── hyperliquid.py │ ├── async_support │ ├── __init__.py │ ├── base │ │ ├── __init__.py │ │ ├── exchange.py │ │ ├── throttler.py │ │ └── ws │ │ │ ├── __init__.py │ │ │ ├── aiohttp_client.py │ │ │ ├── cache.py │ │ │ ├── client.py │ │ │ ├── fast_client.py │ │ │ ├── functions.py │ │ │ ├── future.py │ │ │ ├── order_book.py │ │ │ └── order_book_side.py │ └── hyperliquid.py │ ├── base │ ├── __init__.py │ ├── decimal_to_precision.py │ ├── errors.py │ ├── exchange.py │ ├── precise.py │ └── types.py │ ├── hyperliquid.py │ ├── pro │ ├── __init__.py │ └── hyperliquid.py │ └── static_dependencies │ ├── README.md │ ├── __init__.py │ ├── ecdsa │ ├── __init__.py │ ├── _version.py │ ├── curves.py │ ├── der.py │ ├── ecdsa.py │ ├── ellipticcurve.py │ ├── keys.py │ ├── numbertheory.py │ ├── rfc6979.py │ └── util.py │ ├── ethereum │ ├── __init__.py │ ├── abi │ │ ├── __init__.py │ │ ├── abi.py │ │ ├── base.py │ │ ├── codec.py │ │ ├── constants.py │ │ ├── decoding.py │ │ ├── encoding.py │ │ ├── exceptions.py │ │ ├── grammar.py │ │ ├── packed.py │ │ ├── py.typed │ │ ├── registry.py │ │ ├── tools │ │ │ ├── __init__.py │ │ │ └── _strategies.py │ │ └── utils │ │ │ ├── __init__.py │ │ │ ├── numeric.py │ │ │ ├── padding.py │ │ │ └── string.py │ ├── account │ │ ├── __init__.py │ │ ├── encode_typed_data │ │ │ ├── __init__.py │ │ │ ├── encoding_and_hashing.py │ │ │ └── helpers.py │ │ ├── messages.py │ │ └── py.typed │ ├── hexbytes │ │ ├── __init__.py │ │ ├── _utils.py │ │ ├── main.py │ │ └── py.typed │ ├── typing │ │ ├── __init__.py │ │ ├── abi.py │ │ ├── bls.py │ │ ├── discovery.py │ │ ├── encoding.py │ │ ├── enums.py │ │ ├── ethpm.py │ │ ├── evm.py │ │ ├── networks.py │ │ └── py.typed │ └── utils │ │ ├── __init__.py │ │ ├── abi.py │ │ ├── address.py │ │ ├── applicators.py │ │ ├── conversions.py │ │ ├── currency.py │ │ ├── curried │ │ └── __init__.py │ │ ├── debug.py │ │ ├── decorators.py │ │ ├── encoding.py │ │ ├── exceptions.py │ │ ├── functional.py │ │ ├── hexadecimal.py │ │ ├── humanize.py │ │ ├── logging.py │ │ ├── module_loading.py │ │ ├── numeric.py │ │ ├── py.typed │ │ ├── toolz.py │ │ ├── types.py │ │ ├── typing │ │ ├── __init__.py │ │ └── misc.py │ │ └── units.py │ ├── keccak │ ├── __init__.py │ └── keccak.py │ ├── lark │ ├── __init__.py │ ├── __pyinstaller │ │ ├── __init__.py │ │ └── hook-lark.py │ ├── ast_utils.py │ ├── common.py │ ├── exceptions.py │ ├── grammar.py │ ├── grammars │ │ ├── __init__.py │ │ ├── common.lark │ │ ├── lark.lark │ │ ├── python.lark │ │ └── unicode.lark │ ├── indenter.py │ ├── lark.py │ ├── lexer.py │ ├── load_grammar.py │ ├── parse_tree_builder.py │ ├── parser_frontends.py │ ├── parsers │ │ ├── __init__.py │ │ ├── cyk.py │ │ ├── earley.py │ │ ├── earley_common.py │ │ ├── earley_forest.py │ │ ├── grammar_analysis.py │ │ ├── lalr_analysis.py │ │ ├── lalr_interactive_parser.py │ │ ├── lalr_parser.py │ │ ├── lalr_parser_state.py │ │ └── xearley.py │ ├── py.typed │ ├── reconstruct.py │ ├── tools │ │ ├── __init__.py │ │ ├── nearley.py │ │ ├── serialize.py │ │ └── standalone.py │ ├── tree.py │ ├── tree_matcher.py │ ├── tree_templates.py │ ├── utils.py │ └── visitors.py │ ├── marshmallow │ ├── __init__.py │ ├── base.py │ ├── class_registry.py │ ├── decorators.py │ ├── error_store.py │ ├── exceptions.py │ ├── fields.py │ ├── orderedset.py │ ├── py.typed │ ├── schema.py │ ├── types.py │ ├── utils.py │ ├── validate.py │ └── warnings.py │ ├── marshmallow_dataclass │ ├── __init__.py │ ├── collection_field.py │ ├── lazy_class_attribute.py │ ├── mypy.py │ ├── py.typed │ ├── typing.py │ └── union_field.py │ ├── marshmallow_oneofschema │ ├── __init__.py │ ├── one_of_schema.py │ └── py.typed │ ├── msgpack │ ├── __init__.py │ ├── _cmsgpack.pyx │ ├── _packer.pyx │ ├── _unpacker.pyx │ ├── buff_converter.h │ ├── exceptions.py │ ├── ext.py │ ├── fallback.py │ ├── pack.h │ ├── pack_template.h │ ├── sysdep.h │ ├── unpack.h │ ├── unpack_define.h │ └── unpack_template.h │ ├── parsimonious │ ├── __init__.py │ ├── exceptions.py │ ├── expressions.py │ ├── grammar.py │ ├── nodes.py │ └── utils.py │ ├── starknet │ ├── __init__.py │ ├── abi │ │ ├── v0 │ │ │ ├── __init__.py │ │ │ ├── model.py │ │ │ ├── parser.py │ │ │ ├── schemas.py │ │ │ └── shape.py │ │ ├── v1 │ │ │ ├── __init__.py │ │ │ ├── core_structures.json │ │ │ ├── model.py │ │ │ ├── parser.py │ │ │ ├── parser_transformer.py │ │ │ ├── schemas.py │ │ │ └── shape.py │ │ └── v2 │ │ │ ├── __init__.py │ │ │ ├── model.py │ │ │ ├── parser.py │ │ │ ├── parser_transformer.py │ │ │ ├── schemas.py │ │ │ └── shape.py │ ├── cairo │ │ ├── __init__.py │ │ ├── data_types.py │ │ ├── deprecated_parse │ │ │ ├── __init__.py │ │ │ ├── cairo_types.py │ │ │ ├── parser.py │ │ │ └── parser_transformer.py │ │ ├── felt.py │ │ ├── type_parser.py │ │ ├── v1 │ │ │ ├── __init__.py │ │ │ └── type_parser.py │ │ └── v2 │ │ │ ├── __init__.py │ │ │ └── type_parser.py │ ├── ccxt_utils.py │ ├── common.py │ ├── constants.py │ ├── hash │ │ ├── __init__.py │ │ ├── address.py │ │ ├── compiled_class_hash_objects.py │ │ ├── selector.py │ │ ├── storage.py │ │ └── utils.py │ ├── models │ │ ├── __init__.py │ │ └── typed_data.py │ ├── serialization │ │ ├── __init__.py │ │ ├── _calldata_reader.py │ │ ├── _context.py │ │ ├── data_serializers │ │ │ ├── __init__.py │ │ │ ├── _common.py │ │ │ ├── array_serializer.py │ │ │ ├── bool_serializer.py │ │ │ ├── byte_array_serializer.py │ │ │ ├── cairo_data_serializer.py │ │ │ ├── enum_serializer.py │ │ │ ├── felt_serializer.py │ │ │ ├── named_tuple_serializer.py │ │ │ ├── option_serializer.py │ │ │ ├── output_serializer.py │ │ │ ├── payload_serializer.py │ │ │ ├── struct_serializer.py │ │ │ ├── tuple_serializer.py │ │ │ ├── uint256_serializer.py │ │ │ ├── uint_serializer.py │ │ │ └── unit_serializer.py │ │ ├── errors.py │ │ ├── factory.py │ │ ├── function_serialization_adapter.py │ │ └── tuple_dataclass.py │ └── utils │ │ ├── __init__.py │ │ ├── constructor_args_translator.py │ │ ├── iterable.py │ │ ├── schema.py │ │ └── typed_data.py │ ├── starkware │ ├── __init__.py │ └── crypto │ │ ├── __init__.py │ │ ├── fast_pedersen_hash.py │ │ ├── math_utils.py │ │ ├── signature.py │ │ └── utils.py │ ├── sympy │ ├── __init__.py │ ├── core │ │ ├── __init__.py │ │ └── intfunc.py │ └── external │ │ ├── __init__.py │ │ ├── gmpy.py │ │ ├── importtools.py │ │ ├── ntheory.py │ │ └── pythonmpq.py │ ├── toolz │ ├── __init__.py │ ├── _signatures.py │ ├── _version.py │ ├── compatibility.py │ ├── curried │ │ ├── __init__.py │ │ ├── exceptions.py │ │ └── operator.py │ ├── dicttoolz.py │ ├── functoolz.py │ ├── itertoolz.py │ ├── recipes.py │ └── utils.py │ └── typing_inspect │ ├── __init__.py │ └── typing_inspect.py ├── requirements.txt └── setup.py /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "ccxt_source"] 2 | path = ccxt_source 3 | url = https://github.com/ccxt/ccxt.git 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 ccxt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /build/package-meta.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hyperliquid", 3 | "version": "4.4.66", 4 | "description": "A Python cryptocurrency trading library for hyperliquid", 5 | "repository": { 6 | "type": "git", 7 | "url": "https://github.com/ccxt/python-hyperliquid.git" 8 | }, 9 | "readme": "README.md", 10 | "author": { 11 | "name": "Igor Kroitor", 12 | "email": "igor.kroitor@gmail.com", 13 | "url": "https://github.com/kroitor" 14 | }, 15 | "license": "MIT", 16 | "bugs": { 17 | "url": "https://github.com/ccxt/ccxt/issues" 18 | }, 19 | "homepage": "https://ccxt.com", 20 | "keywords": [ 21 | "hyperliquid", 22 | "cryptocurrency", 23 | "trading", 24 | "library", 25 | "api", 26 | "rest", 27 | "websocket", 28 | "exchange", 29 | "ccxt" 30 | ], 31 | "collective": { 32 | "type": "opencollective", 33 | "url": "https://opencollective.com/ccxt", 34 | "logo": "https://opencollective.com/ccxt/logo.txt" 35 | }, 36 | "ethereum": "0x26a3CB49578F07000575405a57888681249c35Fd" 37 | } -------------------------------------------------------------------------------- /build/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "build", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "build": "tsx build.ts" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "extract-zip": "^2.0.1", 14 | "fs": "^0.0.1-security", 15 | "path": "^0.12.7" 16 | }, 17 | "devDependencies": { 18 | "tsx": "^4.19.3" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /examples/async.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import asyncio 4 | 5 | root = os.path.dirname(os.path.dirname((os.path.abspath(__file__)))) 6 | sys.path.append(root + '/') 7 | 8 | from hyperliquid import HyperliquidAsync 9 | 10 | # ********** on Windows, uncomment below ********** 11 | # if sys.platform == 'win32': 12 | # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) 13 | 14 | async def main(): 15 | instance = HyperliquidAsync({}) 16 | await instance.load_markets() 17 | symbol = "BTC/USDC:USDC" 18 | 19 | # fetch ticker 20 | # 21 | ticker = await instance.fetch_ticker(symbol) 22 | print(ticker) 23 | 24 | # fetch ohlcv 25 | # 26 | ohlcv = await instance.fetch_ohlcv(symbol, "1m") 27 | print(ohlcv) 28 | 29 | # close after you finish 30 | await instance.close() 31 | 32 | asyncio.run(main()) 33 | 34 | -------------------------------------------------------------------------------- /examples/sync.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | root = os.path.dirname(os.path.dirname((os.path.abspath(__file__)))) 5 | sys.path.append(root + '/') 6 | 7 | from hyperliquid import HyperliquidSync 8 | 9 | 10 | def main(): 11 | instance = HyperliquidSync({}) 12 | instance.load_markets() 13 | symbol = "BTC/USDC:USDC" 14 | 15 | # fetch ticker 16 | # 17 | ticker = instance.fetch_ticker(symbol) 18 | print(ticker) 19 | 20 | # fetch ohlcv 21 | # 22 | ohlcv = instance.fetch_ohlcv(symbol, "1m") 23 | print(ohlcv) 24 | 25 | 26 | main() 27 | 28 | -------------------------------------------------------------------------------- /examples/websockets.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import asyncio 4 | 5 | root = os.path.dirname(os.path.dirname((os.path.abspath(__file__)))) 6 | sys.path.append(root + '/') 7 | 8 | from hyperliquid import HyperliquidWs 9 | 10 | # ********** on Windows, uncomment below ********** 11 | # if sys.platform == 'win32': 12 | # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) 13 | 14 | 15 | async def my_watch_ticker_my(exchange, symbol): 16 | while (True): 17 | result = await exchange.watch_ticker(symbol) 18 | print(result) 19 | 20 | 21 | async def my_watch_orderbook(exchange, symbol): 22 | while (True): 23 | result = await exchange.watch_order_book(symbol) 24 | print(result) 25 | 26 | 27 | 28 | 29 | async def main(): 30 | instance = HyperliquidWs({}) 31 | await instance.load_markets() 32 | symbol = "BTC/USDC:USDC" 33 | 34 | # fetch ticker 35 | ticker = my_watch_ticker_my(instance, symbol) 36 | 37 | # fetch orderbook 38 | ob = my_watch_orderbook(instance, symbol) 39 | 40 | await asyncio.gather(ticker, ob) 41 | 42 | # close after you finish 43 | await instance.close() 44 | 45 | 46 | 47 | 48 | asyncio.run(main()) 49 | 50 | -------------------------------------------------------------------------------- /hyperliquid/__init__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import hyperliquid.ccxt as ccxt_module 3 | sys.modules['ccxt'] = ccxt_module 4 | 5 | from hyperliquid.ccxt import hyperliquid as HyperliquidSync 6 | from hyperliquid.ccxt.async_support.hyperliquid import hyperliquid as HyperliquidAsync 7 | from hyperliquid.ccxt.pro.hyperliquid import hyperliquid as HyperliquidWs 8 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/abstract/hyperliquid.py: -------------------------------------------------------------------------------- 1 | from ccxt.base.types import Entry 2 | 3 | 4 | class ImplicitAPI: 5 | public_post_info = publicPostInfo = Entry('info', 'public', 'POST', {'cost': 20, 'byType': {'l2Book': 2, 'allMids': 2, 'clearinghouseState': 2, 'orderStatus': 2, 'spotClearinghouseState': 2, 'exchangeStatus': 2}}) 6 | private_post_exchange = privatePostExchange = Entry('exchange', 'private', 'POST', {'cost': 1}) 7 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/async_support/base/__init__.py: -------------------------------------------------------------------------------- 1 | # this file is a stub so that files inside of ccxt/rest are loaded 2 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/async_support/base/throttler.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import collections 3 | from time import time 4 | 5 | 6 | class Throttler: 7 | def __init__(self, config, loop=None): 8 | self.loop = loop 9 | self.config = { 10 | 'refillRate': 1.0, 11 | 'delay': 0.001, 12 | 'cost': 1.0, 13 | 'tokens': 0, 14 | 'maxCapacity': 2000, 15 | 'capacity': 1.0, 16 | } 17 | self.config.update(config) 18 | self.queue = collections.deque() 19 | self.running = False 20 | 21 | async def looper(self): 22 | last_timestamp = time() * 1000 23 | while self.running: 24 | future, cost = self.queue[0] 25 | cost = self.config['cost'] if cost is None else cost 26 | if self.config['tokens'] >= 0: 27 | self.config['tokens'] -= cost 28 | if not future.done(): 29 | future.set_result(None) 30 | self.queue.popleft() 31 | # context switch 32 | await asyncio.sleep(0) 33 | if len(self.queue) == 0: 34 | self.running = False 35 | else: 36 | await asyncio.sleep(self.config['delay']) 37 | now = time() * 1000 38 | elapsed = now - last_timestamp 39 | last_timestamp = now 40 | self.config['tokens'] = min(self.config['tokens'] + elapsed * self.config['refillRate'], self.config['capacity']) 41 | 42 | def __call__(self, cost=None): 43 | future = asyncio.Future() 44 | if len(self.queue) > self.config['maxCapacity']: 45 | raise RuntimeError('throttle queue is over maxCapacity (' + str(int(self.config['maxCapacity'])) + '), see https://github.com/ccxt/ccxt/issues/11645#issuecomment-1195695526') 46 | self.queue.append((future, cost)) 47 | if not self.running: 48 | self.running = True 49 | asyncio.ensure_future(self.looper(), loop=self.loop) 50 | return future 51 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/async_support/base/ws/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from ccxt.base import errors 4 | 5 | # ----------------------------------------------------------------------------- 6 | 7 | from ccxt.base import decimal_to_precision 8 | 9 | from ccxt import BaseError # noqa: F401 10 | from ccxt import ExchangeError # noqa: F401 11 | from ccxt import NotSupported # noqa: F401 12 | from ccxt import AuthenticationError # noqa: F401 13 | from ccxt import PermissionDenied # noqa: F401 14 | from ccxt import AccountSuspended # noqa: F401 15 | from ccxt import InvalidNonce # noqa: F401 16 | from ccxt import InsufficientFunds # noqa: F401 17 | from ccxt import InvalidOrder # noqa: F401 18 | from ccxt import OrderNotFound # noqa: F401 19 | from ccxt import OrderNotCached # noqa: F401 20 | from ccxt import DuplicateOrderId # noqa: F401 21 | from ccxt import CancelPending # noqa: F401 22 | from ccxt import NetworkError # noqa: F401 23 | from ccxt import DDoSProtection # noqa: F401 24 | from ccxt import RateLimitExceeded # noqa: F401 25 | from ccxt import RequestTimeout # noqa: F401 26 | from ccxt import ExchangeNotAvailable # noqa: F401 27 | from ccxt import OnMaintenance # noqa: F401 28 | from ccxt import InvalidAddress # noqa: F401 29 | from ccxt import AddressPending # noqa: F401 30 | from ccxt import ArgumentsRequired # noqa: F401 31 | from ccxt import BadRequest # noqa: F401 32 | from ccxt import BadResponse # noqa: F401 33 | from ccxt import NullResponse # noqa: F401 34 | from ccxt import OrderImmediatelyFillable # noqa: F401 35 | from ccxt import OrderNotFillable # noqa: F401 36 | 37 | 38 | __all__ = decimal_to_precision.__all__ + errors.__all__ # noqa: F405 39 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/async_support/base/ws/functions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from zlib import decompress, MAX_WBITS 4 | from base64 import b64decode 5 | from gzip import GzipFile 6 | from io import BytesIO 7 | import time 8 | import datetime 9 | 10 | 11 | def inflate(data): 12 | return decompress(data, -MAX_WBITS) 13 | 14 | 15 | def inflate64(data): 16 | return inflate(b64decode(data)) 17 | 18 | 19 | def gunzip(data): 20 | return GzipFile('', 'rb', 9, BytesIO(data)).read().decode('utf-8') 21 | 22 | 23 | # Tmp : added methods below to avoid circular imports between exchange.py and aiohttp.py 24 | 25 | def milliseconds(): 26 | return int(time.time() * 1000) 27 | 28 | 29 | def iso8601(timestamp=None): 30 | if timestamp is None: 31 | return timestamp 32 | if not isinstance(timestamp, int): 33 | return None 34 | if int(timestamp) < 0: 35 | return None 36 | try: 37 | utc = datetime.datetime.fromtimestamp(timestamp // 1000, datetime.timezone.utc) 38 | return utc.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-6] + "{:03d}".format(int(timestamp) % 1000) + 'Z' 39 | except (TypeError, OverflowError, OSError): 40 | return None 41 | 42 | 43 | def is_json_encoded_object(input): 44 | return (isinstance(input, str) and 45 | (len(input) >= 2) and 46 | ((input[0] == '{') or (input[0] == '['))) 47 | 48 | 49 | def deep_extend(*args): 50 | result = None 51 | for arg in args: 52 | if isinstance(arg, dict): 53 | if not isinstance(result, dict): 54 | result = {} 55 | for key in arg: 56 | result[key] = deep_extend(result[key] if key in result else None, arg[key]) 57 | else: 58 | result = arg 59 | return result 60 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/async_support/base/ws/future.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from ccxt import ExchangeClosedByUser 3 | 4 | class Future(asyncio.Future): 5 | 6 | is_race_future = False 7 | 8 | def resolve(self, result=None): 9 | if not self.done(): 10 | try: 11 | self.set_result(result) 12 | except BaseException as e: 13 | print("Error in Future.resolve") 14 | raise e 15 | 16 | def reject(self, error=None): 17 | if not self.done(): 18 | # If not an exception, wrap it in a generic Exception 19 | if not isinstance(error, BaseException): 20 | error = Exception(error) 21 | try: 22 | self.set_exception(error) 23 | except BaseException as e: 24 | print("Error in Future.reject") 25 | raise e 26 | 27 | @classmethod 28 | def race(cls, futures): 29 | future = Future() 30 | for f in futures: 31 | f.is_race_future = True 32 | coro = asyncio.wait(futures, return_when=asyncio.FIRST_COMPLETED) 33 | task = asyncio.create_task(coro) 34 | 35 | def callback(done): 36 | try: 37 | complete, pending = done.result() 38 | # check for exceptions 39 | for i, f in enumerate(complete): 40 | try: 41 | f.result() 42 | except ExchangeClosedByUser as e: 43 | if len(pending) == 0 and i == len(complete) - 1: 44 | future.reject(e) 45 | # wait for all the sub promises to be reject before rejecting future 46 | continue 47 | except asyncio.CancelledError as e: 48 | continue 49 | except Exception as e: 50 | future.reject(e) 51 | return 52 | # no exceptions return first result 53 | futures_list = list(complete) 54 | 55 | are_all_canceled = all([f.cancelled() for f in futures_list]) 56 | if are_all_canceled: 57 | future.reject(ExchangeClosedByUser('Connection closed by the user')) 58 | return 59 | 60 | first = futures_list[0] 61 | 62 | first_result = first.result() 63 | future.resolve(first_result) 64 | except asyncio.CancelledError as e: 65 | future.reject(e) 66 | except Exception as e: 67 | future.reject(e) 68 | task.add_done_callback(callback) 69 | return future 70 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/async_support/base/ws/order_book.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from ccxt.async_support.base.ws import order_book_side 4 | from ccxt import Exchange 5 | import sys 6 | 7 | 8 | class OrderBook(dict): 9 | def __init__(self, snapshot={}, depth=None): 10 | self.cache = [] 11 | depth = depth or sys.maxsize 12 | defaults = { 13 | 'bids': [], 14 | 'asks': [], 15 | 'timestamp': None, 16 | 'datetime': None, 17 | 'nonce': None, 18 | 'symbol': None, 19 | } 20 | # do not mutate snapshot 21 | defaults.update(snapshot) 22 | if not isinstance(defaults['asks'], order_book_side.OrderBookSide): 23 | defaults['asks'] = order_book_side.Asks(defaults['asks'], depth) 24 | if not isinstance(defaults['bids'], order_book_side.OrderBookSide): 25 | defaults['bids'] = order_book_side.Bids(defaults['bids'], depth) 26 | defaults['datetime'] = Exchange.iso8601(defaults.get('timestamp')) 27 | # merge to self 28 | super(OrderBook, self).__init__(defaults) 29 | 30 | def limit(self): 31 | self['asks'].limit() 32 | self['bids'].limit() 33 | return self 34 | 35 | def reset(self, snapshot={}): 36 | self['asks']._index.clear() 37 | self['asks'].clear() 38 | for ask in snapshot.get('asks', []): 39 | self['asks'].storeArray(ask) 40 | self['bids']._index.clear() 41 | self['bids'].clear() 42 | for bid in snapshot.get('bids', []): 43 | self['bids'].storeArray(bid) 44 | self['nonce'] = snapshot.get('nonce') 45 | self['timestamp'] = snapshot.get('timestamp') 46 | self['datetime'] = Exchange.iso8601(self['timestamp']) 47 | self['symbol'] = snapshot.get('symbol') 48 | 49 | def update(self, snapshot): 50 | nonce = snapshot.get('nonce') 51 | if nonce is not None and self['nonce'] is not None and nonce < self['nonce']: 52 | return self 53 | self.reset(snapshot) 54 | 55 | # ----------------------------------------------------------------------------- 56 | # overwrites absolute volumes at price levels 57 | # or deletes price levels based on order counts (3rd value in a bidask delta) 58 | 59 | 60 | class CountedOrderBook(OrderBook): 61 | def __init__(self, snapshot={}, depth=None): 62 | copy = Exchange.extend(snapshot, { 63 | 'asks': order_book_side.CountedAsks(snapshot.get('asks', []), depth), 64 | 'bids': order_book_side.CountedBids(snapshot.get('bids', []), depth), 65 | }) 66 | super(CountedOrderBook, self).__init__(copy, depth) 67 | 68 | # ----------------------------------------------------------------------------- 69 | # indexed by order ids (3rd value in a bidask delta) 70 | 71 | 72 | class IndexedOrderBook(OrderBook): 73 | def __init__(self, snapshot={}, depth=None): 74 | copy = Exchange.extend(snapshot, { 75 | 'asks': order_book_side.IndexedAsks(snapshot.get('asks', []), depth), 76 | 'bids': order_book_side.IndexedBids(snapshot.get('bids', []), depth), 77 | }) 78 | super(IndexedOrderBook, self).__init__(copy, depth) 79 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/base/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # MIT License 4 | # Copyright (c) 2017 Igor Kroitor 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | 23 | from ccxt.base import errors 24 | from ccxt.base import exchange 25 | from ccxt.base import decimal_to_precision 26 | 27 | __all__ = exchange.__all__ + decimal_to_precision.__all__ + errors.__all__ # noqa: F405 28 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/pro/__init__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import hyperliquid.ccxt as ccxt_module 3 | sys.modules['ccxt'] = ccxt_module 4 | 5 | # -*- coding: utf-8 -*- 6 | 7 | """CCXT: CryptoCurrency eXchange Trading Library (Async)""" 8 | 9 | # ---------------------------------------------------------------------------- 10 | 11 | __version__ = '4.4.66' 12 | 13 | # ---------------------------------------------------------------------------- 14 | 15 | from ccxt.async_support.base.exchange import Exchange # noqa: F401 16 | 17 | # CCXT Pro exchanges (now this is mainly used for importing exchanges in WS tests) 18 | 19 | from ccxt.pro.hyperliquid import hyperliquid # noqa: F401 20 | 21 | exchanges = [ 'hyperliquid',] 22 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/README.md: -------------------------------------------------------------------------------- 1 | // TODO: add web3 2 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/__init__.py: -------------------------------------------------------------------------------- 1 | __all__ = ['ecdsa', 'keccak', 'aiohttp_socks', 'ethereum', 'parsimonious', 'toolz', 'starknet', 'marshmallow', 'marshmallow_oneofschema', 'lark', 'starkware', 'sympy'] 2 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ecdsa/__init__.py: -------------------------------------------------------------------------------- 1 | from .keys import SigningKey, VerifyingKey, BadSignatureError, BadDigestError 2 | from .curves import NIST192p, NIST224p, NIST256p, NIST384p, NIST521p, SECP256k1 3 | 4 | # This code comes from http://github.com/warner/python-ecdsa 5 | #from ._version import get_versions 6 | __version__ = 'ccxt' # custom ccxt version 7 | #del get_versions 8 | 9 | __all__ = ["curves", "der", "ecdsa", "ellipticcurve", "keys", "numbertheory", 10 | "util"] 11 | 12 | _hush_pyflakes = [SigningKey, VerifyingKey, BadSignatureError, BadDigestError, 13 | NIST192p, NIST224p, NIST256p, NIST384p, NIST521p, SECP256k1] 14 | del _hush_pyflakes 15 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ecdsa/curves.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | 3 | from . import der, ecdsa 4 | 5 | 6 | class UnknownCurveError(Exception): 7 | pass 8 | 9 | 10 | def orderlen(order): 11 | return (1+len("%x" % order))//2 # bytes 12 | 13 | 14 | # the NIST curves 15 | class Curve: 16 | def __init__(self, name, curve, generator, oid, openssl_name=None): 17 | self.name = name 18 | self.openssl_name = openssl_name # maybe None 19 | self.curve = curve 20 | self.generator = generator 21 | self.order = generator.order() 22 | self.baselen = orderlen(self.order) 23 | self.verifying_key_length = 2*self.baselen 24 | self.signature_length = 2*self.baselen 25 | self.oid = oid 26 | self.encoded_oid = der.encode_oid(*oid) 27 | 28 | NIST192p = Curve("NIST192p", ecdsa.curve_192, 29 | ecdsa.generator_192, 30 | (1, 2, 840, 10045, 3, 1, 1), "prime192v1") 31 | NIST224p = Curve("NIST224p", ecdsa.curve_224, 32 | ecdsa.generator_224, 33 | (1, 3, 132, 0, 33), "secp224r1") 34 | NIST256p = Curve("NIST256p", ecdsa.curve_256, 35 | ecdsa.generator_256, 36 | (1, 2, 840, 10045, 3, 1, 7), "prime256v1") 37 | NIST384p = Curve("NIST384p", ecdsa.curve_384, 38 | ecdsa.generator_384, 39 | (1, 3, 132, 0, 34), "secp384r1") 40 | NIST521p = Curve("NIST521p", ecdsa.curve_521, 41 | ecdsa.generator_521, 42 | (1, 3, 132, 0, 35), "secp521r1") 43 | SECP256k1 = Curve("SECP256k1", ecdsa.curve_secp256k1, 44 | ecdsa.generator_secp256k1, 45 | (1, 3, 132, 0, 10), "secp256k1") 46 | 47 | curves = [NIST192p, NIST224p, NIST256p, NIST384p, NIST521p, SECP256k1] 48 | 49 | 50 | def find_curve(oid_curve): 51 | for c in curves: 52 | if c.oid == oid_curve: 53 | return c 54 | raise UnknownCurveError("I don't know about the curve with oid %s." 55 | "I only know about these: %s" % 56 | (oid_curve, [c.name for c in curves])) 57 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ecdsa/rfc6979.py: -------------------------------------------------------------------------------- 1 | ''' 2 | RFC 6979: 3 | Deterministic Usage of the Digital Signature Algorithm (DSA) and 4 | Elliptic Curve Digital Signature Algorithm (ECDSA) 5 | 6 | http://tools.ietf.org/html/rfc6979 7 | 8 | Many thanks to Coda Hale for his implementation in Go language: 9 | https://github.com/codahale/rfc6979 10 | ''' 11 | 12 | import hmac 13 | from binascii import hexlify 14 | from .util import number_to_string, number_to_string_crop 15 | 16 | 17 | def bit_length(num): 18 | # http://docs.python.org/dev/library/stdtypes.html#int.bit_length 19 | s = bin(num) # binary representation: bin(-37) --> '-0b100101' 20 | s = s.lstrip('-0b') # remove leading zeros and minus sign 21 | return len(s) # len('100101') --> 6 22 | 23 | 24 | def bits2int(data, qlen): 25 | x = int(hexlify(data), 16) 26 | l = len(data) * 8 27 | 28 | if l > qlen: 29 | return x >> (l - qlen) 30 | return x 31 | 32 | 33 | def bits2octets(data, order): 34 | z1 = bits2int(data, bit_length(order)) 35 | z2 = z1 - order 36 | 37 | if z2 < 0: 38 | z2 = z1 39 | 40 | return number_to_string_crop(z2, order) 41 | 42 | 43 | # https://tools.ietf.org/html/rfc6979#section-3.2 44 | def generate_k(order, secexp, hash_func, data, retry_gen=0, extra_entropy=b''): 45 | ''' 46 | order - order of the DSA generator used in the signature 47 | secexp - secure exponent (private key) in numeric form 48 | hash_func - reference to the same hash function used for generating hash 49 | data - hash in binary form of the signing data 50 | retry_gen - int - how many good 'k' values to skip before returning 51 | extra_entropy - extra added data in binary form as per section-3.6 of 52 | rfc6979 53 | ''' 54 | 55 | qlen = bit_length(order) 56 | holen = hash_func().digest_size 57 | rolen = (qlen + 7) / 8 58 | bx = number_to_string(secexp, order) + bits2octets(data, order) + \ 59 | extra_entropy 60 | 61 | # Step B 62 | v = b'\x01' * holen 63 | 64 | # Step C 65 | k = b'\x00' * holen 66 | 67 | # Step D 68 | 69 | k = hmac.new(k, v + b'\x00' + bx, hash_func).digest() 70 | 71 | # Step E 72 | v = hmac.new(k, v, hash_func).digest() 73 | 74 | # Step F 75 | k = hmac.new(k, v + b'\x01' + bx, hash_func).digest() 76 | 77 | # Step G 78 | v = hmac.new(k, v, hash_func).digest() 79 | 80 | # Step H 81 | while True: 82 | # Step H1 83 | t = b'' 84 | 85 | # Step H2 86 | while len(t) < rolen: 87 | v = hmac.new(k, v, hash_func).digest() 88 | t += v 89 | 90 | # Step H3 91 | secret = bits2int(t, qlen) 92 | 93 | if secret >= 1 and secret < order: 94 | if retry_gen <= 0: 95 | return secret 96 | else: 97 | retry_gen -= 1 98 | 99 | k = hmac.new(k, v + b'\x00', hash_func).digest() 100 | v = hmac.new(k, v, hash_func).digest() 101 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/__init__.py: -------------------------------------------------------------------------------- 1 | from .abi import * 2 | from .account import * 3 | from .typing import * 4 | from .utils import * 5 | from .hexbytes import * 6 | 7 | __all__ = [ 'account', 'typing', 'utils', 'abi', 'hexbytes' ] -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/abi/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | from .abi import ( 3 | decode, 4 | decode_abi, 5 | decode_single, 6 | encode, 7 | encode_abi, 8 | encode_single, 9 | is_encodable, 10 | is_encodable_type, 11 | ) 12 | 13 | # This code from: https://github.com/ethereum/eth-abi/tree/v3.0.1 14 | __version__ = 'ccxt' 15 | 16 | __all__ = ['decode','encode'] 17 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/abi/abi.py: -------------------------------------------------------------------------------- 1 | from .codec import ( 2 | ABICodec, 3 | ) 4 | from .registry import ( 5 | registry, 6 | ) 7 | 8 | default_codec = ABICodec(registry) 9 | 10 | encode = default_codec.encode 11 | encode_abi = default_codec.encode_abi # deprecated 12 | encode_single = default_codec.encode_single # deprecated 13 | 14 | decode = default_codec.decode 15 | decode_abi = default_codec.decode_abi # deprecated 16 | decode_single = default_codec.decode_single # deprecated 17 | 18 | is_encodable = default_codec.is_encodable 19 | is_encodable_type = default_codec.is_encodable_type 20 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/abi/constants.py: -------------------------------------------------------------------------------- 1 | TT256 = 2**256 2 | TT256M1 = 2**256 - 1 3 | TT255 = 2**255 4 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/abi/packed.py: -------------------------------------------------------------------------------- 1 | from .codec import ( 2 | ABIEncoder, 3 | ) 4 | from .registry import ( 5 | registry_packed, 6 | ) 7 | 8 | default_encoder_packed = ABIEncoder(registry_packed) 9 | 10 | encode_packed = default_encoder_packed.encode 11 | is_encodable_packed = default_encoder_packed.is_encodable 12 | encode_single_packed = default_encoder_packed.encode_single # deprecated 13 | encode_abi_packed = default_encoder_packed.encode_abi # deprecated 14 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/abi/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/ethereum/abi/py.typed -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/abi/tools/__init__.py: -------------------------------------------------------------------------------- 1 | from ._strategies import ( # noqa: F401 2 | get_abi_strategy, 3 | ) 4 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/abi/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/ethereum/abi/utils/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/abi/utils/numeric.py: -------------------------------------------------------------------------------- 1 | import decimal 2 | from typing import ( 3 | Callable, 4 | Tuple, 5 | ) 6 | 7 | ABI_DECIMAL_PREC = 999 8 | 9 | abi_decimal_context = decimal.Context(prec=ABI_DECIMAL_PREC) 10 | 11 | ZERO = decimal.Decimal(0) 12 | TEN = decimal.Decimal(10) 13 | 14 | 15 | def ceil32(x: int) -> int: 16 | return x if x % 32 == 0 else x + 32 - (x % 32) 17 | 18 | 19 | def compute_unsigned_integer_bounds(num_bits: int) -> Tuple[int, int]: 20 | return ( 21 | 0, 22 | 2**num_bits - 1, 23 | ) 24 | 25 | 26 | def compute_signed_integer_bounds(num_bits: int) -> Tuple[int, int]: 27 | return ( 28 | -1 * 2 ** (num_bits - 1), 29 | 2 ** (num_bits - 1) - 1, 30 | ) 31 | 32 | 33 | def compute_unsigned_fixed_bounds( 34 | num_bits: int, 35 | frac_places: int, 36 | ) -> Tuple[decimal.Decimal, decimal.Decimal]: 37 | int_upper = compute_unsigned_integer_bounds(num_bits)[1] 38 | 39 | with decimal.localcontext(abi_decimal_context): 40 | upper = decimal.Decimal(int_upper) * TEN**-frac_places 41 | 42 | return ZERO, upper 43 | 44 | 45 | def compute_signed_fixed_bounds( 46 | num_bits: int, 47 | frac_places: int, 48 | ) -> Tuple[decimal.Decimal, decimal.Decimal]: 49 | int_lower, int_upper = compute_signed_integer_bounds(num_bits) 50 | 51 | with decimal.localcontext(abi_decimal_context): 52 | exp = TEN**-frac_places 53 | lower = decimal.Decimal(int_lower) * exp 54 | upper = decimal.Decimal(int_upper) * exp 55 | 56 | return lower, upper 57 | 58 | 59 | def scale_places(places: int) -> Callable[[decimal.Decimal], decimal.Decimal]: 60 | """ 61 | Returns a function that shifts the decimal point of decimal values to the 62 | right by ``places`` places. 63 | """ 64 | if not isinstance(places, int): 65 | raise ValueError( 66 | f"Argument `places` must be int. Got value {places} " 67 | f"of type {type(places)}.", 68 | ) 69 | 70 | with decimal.localcontext(abi_decimal_context): 71 | scaling_factor = TEN**-places 72 | 73 | def f(x: decimal.Decimal) -> decimal.Decimal: 74 | with decimal.localcontext(abi_decimal_context): 75 | return x * scaling_factor 76 | 77 | places_repr = f"Eneg{places}" if places > 0 else f"Epos{-places}" 78 | func_name = f"scale_by_{places_repr}" 79 | 80 | f.__name__ = func_name 81 | f.__qualname__ = func_name 82 | 83 | return f 84 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/abi/utils/padding.py: -------------------------------------------------------------------------------- 1 | from ...utils.toolz import ( 2 | curry, 3 | ) 4 | 5 | 6 | @curry 7 | def zpad(value: bytes, length: int) -> bytes: 8 | return value.rjust(length, b"\x00") 9 | 10 | 11 | zpad32 = zpad(length=32) 12 | 13 | 14 | @curry 15 | def zpad_right(value: bytes, length: int) -> bytes: 16 | return value.ljust(length, b"\x00") 17 | 18 | 19 | zpad32_right = zpad_right(length=32) 20 | 21 | 22 | @curry 23 | def fpad(value: bytes, length: int) -> bytes: 24 | return value.rjust(length, b"\xff") 25 | 26 | 27 | fpad32 = fpad(length=32) 28 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/abi/utils/string.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | Any, 3 | ) 4 | 5 | 6 | def abbr(value: Any, limit: int = 79) -> str: 7 | """ 8 | Converts a value into its string representation and abbreviates that 9 | representation based on the given length `limit` if necessary. 10 | """ 11 | rep = repr(value) 12 | 13 | if len(rep) > limit: 14 | if limit < 3: 15 | raise ValueError("Abbreviation limit may not be less than 3") 16 | 17 | rep = rep[: limit - 3] + "..." 18 | 19 | return rep 20 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/account/__init__.py: -------------------------------------------------------------------------------- 1 | from .messages import * 2 | 3 | __all__ = ["messages"] 4 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/account/encode_typed_data/__init__.py: -------------------------------------------------------------------------------- 1 | from .encoding_and_hashing import ( 2 | hash_domain, 3 | hash_eip712_message, 4 | ) 5 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/account/encode_typed_data/helpers.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | Any, 3 | ) 4 | 5 | from ...utils import ( 6 | is_hexstr, 7 | ) 8 | 9 | 10 | def _get_eip712_solidity_types(): 11 | types = ["bool", "address", "string", "bytes", "uint", "int"] 12 | ints = [f"int{(x + 1) * 8}" for x in range(32)] 13 | uints = [f"uint{(x + 1) * 8}" for x in range(32)] 14 | bytes_ = [f"bytes{x + 1}" for x in range(32)] 15 | return types + ints + uints + bytes_ 16 | 17 | 18 | EIP712_SOLIDITY_TYPES = _get_eip712_solidity_types() 19 | 20 | 21 | def is_array_type(type_: str) -> bool: 22 | return type_.endswith("]") 23 | 24 | 25 | def is_0x_prefixed_hexstr(value: Any) -> bool: 26 | return is_hexstr(value) and value.startswith("0x") 27 | 28 | 29 | # strip all brackets: Person[][] -> Person 30 | def parse_core_array_type(type_: str) -> str: 31 | if is_array_type(type_): 32 | type_ = type_[: type_.index("[")] 33 | return type_ 34 | 35 | 36 | # strip only last set of brackets: Person[3][1] -> Person[3] 37 | def parse_parent_array_type(type_: str) -> str: 38 | if is_array_type(type_): 39 | type_ = type_[: type_.rindex("[")] 40 | return type_ 41 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/account/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/ethereum/account/py.typed -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/hexbytes/__init__.py: -------------------------------------------------------------------------------- 1 | from .main import ( 2 | HexBytes, 3 | ) 4 | 5 | __all__ = ["HexBytes"] 6 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/hexbytes/_utils.py: -------------------------------------------------------------------------------- 1 | import binascii 2 | from typing import ( 3 | Union, 4 | ) 5 | 6 | 7 | def to_bytes(val: Union[bool, bytearray, bytes, int, str, memoryview]) -> bytes: 8 | """ 9 | Equivalent to: `eth_utils.hexstr_if_str(eth_utils.to_bytes, val)` . 10 | 11 | Convert a hex string, integer, or bool, to a bytes representation. 12 | Alternatively, pass through bytes or bytearray as a bytes value. 13 | """ 14 | if isinstance(val, bytes): 15 | return val 16 | elif isinstance(val, str): 17 | return hexstr_to_bytes(val) 18 | elif isinstance(val, bytearray): 19 | return bytes(val) 20 | elif isinstance(val, bool): 21 | return b"\x01" if val else b"\x00" 22 | elif isinstance(val, int): 23 | # Note that this int check must come after the bool check, because 24 | # isinstance(True, int) is True 25 | if val < 0: 26 | raise ValueError(f"Cannot convert negative integer {val} to bytes") 27 | else: 28 | return to_bytes(hex(val)) 29 | elif isinstance(val, memoryview): 30 | return bytes(val) 31 | else: 32 | raise TypeError(f"Cannot convert {val!r} of type {type(val)} to bytes") 33 | 34 | 35 | def hexstr_to_bytes(hexstr: str) -> bytes: 36 | if hexstr.startswith(("0x", "0X")): 37 | non_prefixed_hex = hexstr[2:] 38 | else: 39 | non_prefixed_hex = hexstr 40 | 41 | # if the hex string is odd-length, then left-pad it to an even length 42 | if len(hexstr) % 2: 43 | padded_hex = "0" + non_prefixed_hex 44 | else: 45 | padded_hex = non_prefixed_hex 46 | 47 | try: 48 | ascii_hex = padded_hex.encode("ascii") 49 | except UnicodeDecodeError: 50 | raise ValueError( 51 | f"hex string {padded_hex} may only contain [0-9a-fA-F] characters" 52 | ) 53 | else: 54 | return binascii.unhexlify(ascii_hex) 55 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/hexbytes/main.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from typing import ( 3 | TYPE_CHECKING, 4 | Type, 5 | Union, 6 | cast, 7 | overload, 8 | ) 9 | 10 | from ._utils import ( 11 | to_bytes, 12 | ) 13 | 14 | if TYPE_CHECKING: 15 | from typing import ( 16 | SupportsIndex, 17 | ) 18 | 19 | BytesLike = Union[bool, bytearray, bytes, int, str, memoryview] 20 | 21 | 22 | class HexBytes(bytes): 23 | """ 24 | HexBytes is a *very* thin wrapper around the python built-in :class:`bytes` class. 25 | 26 | It has these three changes: 27 | 1. Accepts more initializing values, like hex strings, non-negative integers, 28 | and booleans 29 | 2. Returns hex with prefix '0x' from :meth:`HexBytes.hex` 30 | 3. The representation at console is in hex 31 | """ 32 | 33 | def __new__(cls: Type[bytes], val: BytesLike) -> "HexBytes": 34 | bytesval = to_bytes(val) 35 | return cast(HexBytes, super().__new__(cls, bytesval)) # type: ignore # https://github.com/python/typeshed/issues/2630 # noqa: E501 36 | 37 | def hex( 38 | self, sep: Union[str, bytes] = None, bytes_per_sep: "SupportsIndex" = 1 39 | ) -> str: 40 | """ 41 | Output hex-encoded bytes, with an "0x" prefix. 42 | 43 | Everything following the "0x" is output exactly like :meth:`bytes.hex`. 44 | """ 45 | return "0x" + super().hex() 46 | 47 | @overload 48 | def __getitem__(self, key: "SupportsIndex") -> int: # noqa: F811 49 | ... 50 | 51 | @overload # noqa: F811 52 | def __getitem__(self, key: slice) -> "HexBytes": # noqa: F811 53 | ... 54 | 55 | def __getitem__( # noqa: F811 56 | self, key: Union["SupportsIndex", slice] 57 | ) -> Union[int, bytes, "HexBytes"]: 58 | result = super().__getitem__(key) 59 | if hasattr(result, "hex"): 60 | return type(self)(result) 61 | else: 62 | return result 63 | 64 | def __repr__(self) -> str: 65 | return f"HexBytes({self.hex()!r})" 66 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/hexbytes/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/ethereum/hexbytes/py.typed -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/typing/__init__.py: -------------------------------------------------------------------------------- 1 | from importlib.metadata import ( 2 | version as __version, 3 | ) 4 | 5 | from .abi import ( 6 | Decodable, 7 | TypeStr, 8 | ) 9 | from .bls import ( 10 | BLSPrivateKey, 11 | BLSPubkey, 12 | BLSSignature, 13 | ) 14 | from .discovery import ( 15 | NodeID, 16 | ) 17 | from .encoding import ( 18 | HexStr, 19 | Primitives, 20 | ) 21 | from .enums import ( 22 | ForkName, 23 | ) 24 | from .ethpm import ( 25 | URI, 26 | ContractName, 27 | Manifest, 28 | ) 29 | from .evm import ( 30 | Address, 31 | AnyAddress, 32 | BlockIdentifier, 33 | BlockNumber, 34 | ChecksumAddress, 35 | Hash32, 36 | HexAddress, 37 | ) 38 | from .networks import ( 39 | ChainId, 40 | ) 41 | 42 | __all__ = ( 43 | "Decodable", 44 | "TypeStr", 45 | "BLSPrivateKey", 46 | "BLSPubkey", 47 | "BLSSignature", 48 | "NodeID", 49 | "HexStr", 50 | "Primitives", 51 | "ForkName", 52 | "ChainId", 53 | "URI", 54 | "ContractName", 55 | "Manifest", 56 | "Address", 57 | "AnyAddress", 58 | "BlockIdentifier", 59 | "BlockNumber", 60 | "ChecksumAddress", 61 | "Hash32", 62 | "HexAddress", 63 | ) 64 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/typing/abi.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | Union, 3 | ) 4 | 5 | TypeStr = str 6 | Decodable = Union[bytes, bytearray] 7 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/typing/bls.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | NewType, 3 | ) 4 | 5 | BLSPubkey = NewType("BLSPubkey", bytes) # bytes48 6 | BLSPrivateKey = NewType("BLSPrivateKey", int) 7 | BLSSignature = NewType("BLSSignature", bytes) # bytes96 8 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/typing/discovery.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | NewType, 3 | ) 4 | 5 | NodeID = NewType("NodeID", bytes) 6 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/typing/encoding.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | NewType, 3 | Union, 4 | ) 5 | 6 | HexStr = NewType("HexStr", str) 7 | Primitives = Union[bytes, int, bool] 8 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/typing/enums.py: -------------------------------------------------------------------------------- 1 | class ForkName: 2 | Frontier = "Frontier" 3 | Homestead = "Homestead" 4 | EIP150 = "EIP150" 5 | EIP158 = "EIP158" 6 | Byzantium = "Byzantium" 7 | Constantinople = "Constantinople" 8 | Metropolis = "Metropolis" 9 | ConstantinopleFix = "ConstantinopleFix" 10 | Istanbul = "Istanbul" 11 | Berlin = "Berlin" 12 | London = "London" 13 | ArrowGlacier = "ArrowGlacier" 14 | GrayGlacier = "GrayGlacier" 15 | Paris = "Paris" 16 | Shanghai = "Shanghai" 17 | Cancun = "Cancun" 18 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/typing/ethpm.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | Any, 3 | Dict, 4 | NewType, 5 | ) 6 | 7 | ContractName = NewType("ContractName", str) 8 | Manifest = NewType("Manifest", Dict[str, Any]) 9 | URI = NewType("URI", str) 10 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/typing/evm.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | Literal, 3 | NewType, 4 | TypeVar, 5 | Union, 6 | ) 7 | 8 | from .encoding import ( 9 | HexStr, 10 | ) 11 | 12 | Hash32 = NewType("Hash32", bytes) 13 | BlockNumber = NewType("BlockNumber", int) 14 | BlockParams = Literal["latest", "earliest", "pending", "safe", "finalized"] 15 | BlockIdentifier = Union[BlockParams, BlockNumber, Hash32, HexStr, int] 16 | 17 | Address = NewType("Address", bytes) 18 | HexAddress = NewType("HexAddress", HexStr) 19 | ChecksumAddress = NewType("ChecksumAddress", HexAddress) 20 | AnyAddress = TypeVar("AnyAddress", Address, HexAddress, ChecksumAddress) 21 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/typing/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/ethereum/typing/py.typed -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from importlib.metadata import ( 2 | version as __version, 3 | ) 4 | 5 | # from .abi import ( 6 | # event_abi_to_log_topic, 7 | # event_signature_to_log_topic, 8 | # function_abi_to_4byte_selector, 9 | # function_signature_to_4byte_selector, 10 | # ) 11 | from .address import ( 12 | is_address, 13 | is_binary_address, 14 | is_canonical_address, 15 | is_checksum_address, 16 | is_checksum_formatted_address, 17 | is_hex_address, 18 | is_normalized_address, 19 | is_same_address, 20 | to_canonical_address, 21 | to_checksum_address, 22 | to_normalized_address, 23 | ) 24 | from .applicators import ( 25 | apply_formatter_at_index, 26 | apply_formatter_if, 27 | apply_formatter_to_array, 28 | apply_formatters_to_dict, 29 | apply_formatters_to_sequence, 30 | apply_key_map, 31 | apply_one_of_formatters, 32 | combine_argument_formatters, 33 | ) 34 | from .conversions import ( 35 | hexstr_if_str, 36 | text_if_str, 37 | to_bytes, 38 | to_hex, 39 | to_int, 40 | to_text, 41 | ) 42 | from .currency import ( 43 | denoms, 44 | from_wei, 45 | to_wei, 46 | ) 47 | from .decorators import ( 48 | combomethod, 49 | replace_exceptions, 50 | ) 51 | from .encoding import ( 52 | big_endian_to_int, 53 | int_to_big_endian, 54 | ) 55 | from .exceptions import ( 56 | ValidationError, 57 | ) 58 | from .functional import ( 59 | apply_to_return_value, 60 | flatten_return, 61 | reversed_return, 62 | sort_return, 63 | to_dict, 64 | to_list, 65 | to_ordered_dict, 66 | to_set, 67 | to_tuple, 68 | ) 69 | from .hexadecimal import ( 70 | add_0x_prefix, 71 | decode_hex, 72 | encode_hex, 73 | is_0x_prefixed, 74 | is_hex, 75 | is_hexstr, 76 | remove_0x_prefix, 77 | ) 78 | from .humanize import ( 79 | humanize_bytes, 80 | humanize_hash, 81 | humanize_integer_sequence, 82 | humanize_ipfs_uri, 83 | humanize_seconds, 84 | humanize_wei, 85 | ) 86 | from .logging import ( 87 | DEBUG2_LEVEL_NUM, 88 | ExtendedDebugLogger, 89 | HasExtendedDebugLogger, 90 | HasExtendedDebugLoggerMeta, 91 | HasLogger, 92 | HasLoggerMeta, 93 | get_extended_debug_logger, 94 | get_logger, 95 | setup_DEBUG2_logging, 96 | ) 97 | from .module_loading import ( 98 | import_string, 99 | ) 100 | from .numeric import ( 101 | clamp, 102 | ) 103 | from .types import ( 104 | is_boolean, 105 | is_bytes, 106 | is_dict, 107 | is_integer, 108 | is_list, 109 | is_list_like, 110 | is_null, 111 | is_number, 112 | is_string, 113 | is_text, 114 | is_tuple, 115 | ) 116 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/abi.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | Any, 3 | Dict, 4 | ) 5 | 6 | from .conversions import ( 7 | to_bytes 8 | ) 9 | 10 | from ...keccak import ( 11 | SHA3 as keccak, 12 | ) 13 | 14 | 15 | def collapse_if_tuple(abi: Dict[str, Any]) -> str: 16 | """ 17 | Converts a tuple from a dict to a parenthesized list of its types. 18 | 19 | >>> from eth_utils.abi import collapse_if_tuple 20 | >>> collapse_if_tuple( 21 | ... { 22 | ... 'components': [ 23 | ... {'name': 'anAddress', 'type': 'address'}, 24 | ... {'name': 'anInt', 'type': 'uint256'}, 25 | ... {'name': 'someBytes', 'type': 'bytes'}, 26 | ... ], 27 | ... 'type': 'tuple', 28 | ... } 29 | ... ) 30 | '(address,uint256,bytes)' 31 | """ 32 | typ = abi["type"] 33 | if not isinstance(typ, str): 34 | raise TypeError( 35 | f"The 'type' must be a string, but got {repr(typ)} of type {type(typ)}" 36 | ) 37 | elif not typ.startswith("tuple"): 38 | return typ 39 | 40 | delimited = ",".join(collapse_if_tuple(c) for c in abi["components"]) 41 | # Whatever comes after "tuple" is the array dims. The ABI spec states that 42 | # this will have the form "", "[]", or "[k]". 43 | array_dim = typ[5:] 44 | collapsed = f"({delimited}){array_dim}" 45 | 46 | return collapsed 47 | 48 | 49 | def _abi_to_signature(abi: Dict[str, Any]) -> str: 50 | fn_input_types = ",".join( 51 | [collapse_if_tuple(abi_input) for abi_input in abi.get("inputs", [])] 52 | ) 53 | function_signature = f"{abi['name']}({fn_input_types})" 54 | return function_signature 55 | 56 | 57 | def function_signature_to_4byte_selector(event_signature: str) -> bytes: 58 | return keccak(to_bytes(text=event_signature.replace(" ", "")))[:4] 59 | 60 | 61 | def function_abi_to_4byte_selector(function_abi: Dict[str, Any]) -> bytes: 62 | function_signature = _abi_to_signature(function_abi) 63 | return function_signature_to_4byte_selector(function_signature) 64 | 65 | 66 | def event_signature_to_log_topic(event_signature: str) -> bytes: 67 | return keccak(to_bytes(text=event_signature.replace(" ", ""))) 68 | 69 | 70 | def event_abi_to_log_topic(event_abi: Dict[str, Any]) -> bytes: 71 | event_signature = _abi_to_signature(event_abi) 72 | return event_signature_to_log_topic(event_signature) 73 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/debug.py: -------------------------------------------------------------------------------- 1 | import platform 2 | import subprocess 3 | import sys 4 | 5 | 6 | def pip_freeze() -> str: 7 | result = subprocess.run("python -m pip freeze".split(), stdout=subprocess.PIPE) 8 | return f"python -m pip freeze result:\n{result.stdout.decode()}" 9 | 10 | 11 | def python_version() -> str: 12 | return f"Python version:\n{sys.version}" 13 | 14 | 15 | def platform_info() -> str: 16 | return f"Operating System: {platform.platform()}" 17 | 18 | 19 | def get_environment_summary() -> str: 20 | return "\n\n".join([python_version(), platform_info(), pip_freeze()]) 21 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/encoding.py: -------------------------------------------------------------------------------- 1 | def int_to_big_endian(value: int) -> bytes: 2 | return value.to_bytes((value.bit_length() + 7) // 8 or 1, "big") 3 | 4 | 5 | def big_endian_to_int(value: bytes) -> int: 6 | return int.from_bytes(value, "big") 7 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/exceptions.py: -------------------------------------------------------------------------------- 1 | class ValidationError(Exception): 2 | """ 3 | Raised when something does not pass a validation check. 4 | """ 5 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/functional.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import functools 3 | import itertools 4 | from typing import ( # noqa: F401 5 | Any, 6 | Callable, 7 | Dict, 8 | Iterable, 9 | List, 10 | Mapping, 11 | Set, 12 | Tuple, 13 | TypeVar, 14 | Union, 15 | ) 16 | 17 | from .toolz import ( 18 | compose as _compose, 19 | ) 20 | 21 | T = TypeVar("T") 22 | 23 | 24 | def identity(value: T) -> T: 25 | return value 26 | 27 | 28 | TGIn = TypeVar("TGIn") 29 | TGOut = TypeVar("TGOut") 30 | TFOut = TypeVar("TFOut") 31 | 32 | 33 | def combine( 34 | f: Callable[[TGOut], TFOut], g: Callable[[TGIn], TGOut] 35 | ) -> Callable[[TGIn], TFOut]: 36 | return lambda x: f(g(x)) 37 | 38 | 39 | def apply_to_return_value( 40 | callback: Callable[..., T] 41 | ) -> Callable[..., Callable[..., T]]: 42 | def outer(fn: Callable[..., T]) -> Callable[..., T]: 43 | # We would need to type annotate *args and **kwargs but doing so segfaults 44 | # the PyPy builds. We ignore instead. 45 | @functools.wraps(fn) 46 | def inner(*args, **kwargs) -> T: # type: ignore 47 | return callback(fn(*args, **kwargs)) 48 | 49 | return inner 50 | 51 | return outer 52 | 53 | 54 | TVal = TypeVar("TVal") 55 | TKey = TypeVar("TKey") 56 | to_tuple = apply_to_return_value( 57 | tuple 58 | ) # type: Callable[[Callable[..., Iterable[TVal]]], Callable[..., Tuple[TVal, ...]]] # noqa: E501 59 | to_list = apply_to_return_value( 60 | list 61 | ) # type: Callable[[Callable[..., Iterable[TVal]]], Callable[..., List[TVal]]] # noqa: E501 62 | to_set = apply_to_return_value( 63 | set 64 | ) # type: Callable[[Callable[..., Iterable[TVal]]], Callable[..., Set[TVal]]] # noqa: E501 65 | to_dict = apply_to_return_value( 66 | dict 67 | ) # type: Callable[[Callable[..., Iterable[Union[Mapping[TKey, TVal], Tuple[TKey, TVal]]]]], Callable[..., Dict[TKey, TVal]]] # noqa: E501 68 | to_ordered_dict = apply_to_return_value( 69 | collections.OrderedDict 70 | ) # type: Callable[[Callable[..., Iterable[Union[Mapping[TKey, TVal], Tuple[TKey, TVal]]]]], Callable[..., collections.OrderedDict[TKey, TVal]]] # noqa: E501 71 | sort_return = _compose(to_tuple, apply_to_return_value(sorted)) 72 | flatten_return = _compose( 73 | to_tuple, apply_to_return_value(itertools.chain.from_iterable) 74 | ) 75 | reversed_return = _compose(to_tuple, apply_to_return_value(reversed), to_tuple) 76 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/hexadecimal.py: -------------------------------------------------------------------------------- 1 | # String encodings and numeric representations 2 | 3 | import binascii 4 | import re 5 | from typing import ( 6 | Any, 7 | AnyStr, 8 | ) 9 | 10 | from ..typing import ( 11 | HexStr, 12 | ) 13 | 14 | from .types import ( 15 | is_string, 16 | is_text, 17 | ) 18 | 19 | _HEX_REGEXP = re.compile("(0[xX])?[0-9a-fA-F]*") 20 | 21 | 22 | def decode_hex(value: str) -> bytes: 23 | if not is_text(value): 24 | raise TypeError("Value must be an instance of str") 25 | non_prefixed = remove_0x_prefix(HexStr(value)) 26 | # unhexlify will only accept bytes type someday 27 | ascii_hex = non_prefixed.encode("ascii") 28 | return binascii.unhexlify(ascii_hex) 29 | 30 | 31 | def encode_hex(value: AnyStr) -> HexStr: 32 | if not is_string(value): 33 | raise TypeError("Value must be an instance of str or unicode") 34 | elif isinstance(value, (bytes, bytearray)): 35 | ascii_bytes = value 36 | else: 37 | ascii_bytes = value.encode("ascii") 38 | 39 | binary_hex = binascii.hexlify(ascii_bytes) 40 | return add_0x_prefix(HexStr(binary_hex.decode("ascii"))) 41 | 42 | 43 | def is_0x_prefixed(value: str) -> bool: 44 | if not is_text(value): 45 | raise TypeError( 46 | f"is_0x_prefixed requires text typed arguments. Got: {repr(value)}" 47 | ) 48 | return value.startswith(("0x", "0X")) 49 | 50 | 51 | def remove_0x_prefix(value: HexStr) -> HexStr: 52 | if is_0x_prefixed(value): 53 | return HexStr(value[2:]) 54 | return value 55 | 56 | 57 | def add_0x_prefix(value: HexStr) -> HexStr: 58 | if is_0x_prefixed(value): 59 | return value 60 | return HexStr("0x" + value) 61 | 62 | 63 | def is_hexstr(value: Any) -> bool: 64 | if not is_text(value) or not value: 65 | return False 66 | return _HEX_REGEXP.fullmatch(value) is not None 67 | 68 | 69 | def is_hex(value: Any) -> bool: 70 | if not is_text(value): 71 | raise TypeError(f"is_hex requires text typed arguments. Got: {repr(value)}") 72 | if not value: 73 | return False 74 | return _HEX_REGEXP.fullmatch(value) is not None 75 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/module_loading.py: -------------------------------------------------------------------------------- 1 | from importlib import ( 2 | import_module, 3 | ) 4 | from typing import ( 5 | Any, 6 | ) 7 | 8 | 9 | def import_string(dotted_path: str) -> Any: 10 | """ 11 | Import a variable using its path and name. 12 | 13 | :param dotted_path: dotted module path and variable/class name 14 | :return: the attribute/class designated by the last name in the path 15 | :raise: ImportError, if the import failed 16 | 17 | Source: django.utils.module_loading 18 | """ 19 | try: 20 | module_path, class_name = dotted_path.rsplit(".", 1) 21 | except ValueError: 22 | msg = f"{dotted_path} doesn't look like a module path" 23 | raise ImportError(msg) 24 | 25 | module = import_module(module_path) 26 | 27 | try: 28 | return getattr(module, class_name) 29 | except AttributeError: 30 | msg = f'Module "{module_path}" does not define a "{class_name}" attribute/class' 31 | raise ImportError(msg) 32 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/numeric.py: -------------------------------------------------------------------------------- 1 | from abc import ( 2 | ABC, 3 | abstractmethod, 4 | ) 5 | import decimal 6 | import numbers 7 | from typing import ( 8 | Any, 9 | TypeVar, 10 | Union, 11 | ) 12 | 13 | 14 | class Comparable(ABC): 15 | @abstractmethod 16 | def __lt__(self, other: Any) -> bool: 17 | ... 18 | 19 | @abstractmethod 20 | def __gt__(self, other: Any) -> bool: 21 | ... 22 | 23 | 24 | TComparable = Union[Comparable, numbers.Real, int, float, decimal.Decimal] 25 | 26 | 27 | TValue = TypeVar("TValue", bound=TComparable) 28 | 29 | 30 | def clamp(lower_bound: TValue, upper_bound: TValue, value: TValue) -> TValue: 31 | # The `mypy` ignore statements here are due to doing a comparison of 32 | # `Union` types which isn't allowed. (per cburgdorf). This approach was 33 | # chosen over using `typing.overload` to define multiple signatures for 34 | # each comparison type here since the added value of "proper" typing 35 | # doesn't seem to justify the complexity of having a bunch of different 36 | # signatures defined. The external library perspective on this function 37 | # should still be adequate under this approach 38 | if value < lower_bound: # type: ignore 39 | return lower_bound 40 | elif value > upper_bound: # type: ignore 41 | return upper_bound 42 | else: 43 | return value 44 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/ethereum/utils/py.typed -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/toolz.py: -------------------------------------------------------------------------------- 1 | from ...toolz import ( # noqa: F401 2 | accumulate, 3 | assoc, 4 | assoc_in, 5 | comp, 6 | complement, 7 | compose, 8 | concat, 9 | concatv, 10 | cons, 11 | count, 12 | countby, 13 | curried, 14 | curry, 15 | dicttoolz, 16 | diff, 17 | dissoc, 18 | do, 19 | drop, 20 | excepts, 21 | filter, 22 | first, 23 | flip, 24 | frequencies, 25 | functoolz, 26 | get, 27 | get_in, 28 | groupby, 29 | identity, 30 | interleave, 31 | interpose, 32 | isdistinct, 33 | isiterable, 34 | itemfilter, 35 | itemmap, 36 | iterate, 37 | itertoolz, 38 | join, 39 | juxt, 40 | keyfilter, 41 | keymap, 42 | last, 43 | map, 44 | mapcat, 45 | memoize, 46 | merge, 47 | merge_sorted, 48 | merge_with, 49 | nth, 50 | partial, 51 | partition, 52 | partition_all, 53 | partitionby, 54 | peek, 55 | pipe, 56 | pluck, 57 | random_sample, 58 | recipes, 59 | reduce, 60 | reduceby, 61 | remove, 62 | second, 63 | sliding_window, 64 | sorted, 65 | tail, 66 | take, 67 | take_nth, 68 | thread_first, 69 | thread_last, 70 | topk, 71 | unique, 72 | update_in, 73 | utils, 74 | valfilter, 75 | valmap, 76 | ) 77 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/types.py: -------------------------------------------------------------------------------- 1 | import collections.abc 2 | import numbers 3 | from typing import ( 4 | Any, 5 | ) 6 | 7 | bytes_types = (bytes, bytearray) 8 | integer_types = (int,) 9 | text_types = (str,) 10 | string_types = (bytes, str, bytearray) 11 | 12 | 13 | def is_integer(value: Any) -> bool: 14 | return isinstance(value, integer_types) and not isinstance(value, bool) 15 | 16 | 17 | def is_bytes(value: Any) -> bool: 18 | return isinstance(value, bytes_types) 19 | 20 | 21 | def is_text(value: Any) -> bool: 22 | return isinstance(value, text_types) 23 | 24 | 25 | def is_string(value: Any) -> bool: 26 | return isinstance(value, string_types) 27 | 28 | 29 | def is_boolean(value: Any) -> bool: 30 | return isinstance(value, bool) 31 | 32 | 33 | def is_dict(obj: Any) -> bool: 34 | return isinstance(obj, collections.abc.Mapping) 35 | 36 | 37 | def is_list_like(obj: Any) -> bool: 38 | return not is_string(obj) and isinstance(obj, collections.abc.Sequence) 39 | 40 | 41 | def is_list(obj: Any) -> bool: 42 | return isinstance(obj, list) 43 | 44 | 45 | def is_tuple(obj: Any) -> bool: 46 | return isinstance(obj, tuple) 47 | 48 | 49 | def is_null(obj: Any) -> bool: 50 | return obj is None 51 | 52 | 53 | def is_number(obj: Any) -> bool: 54 | return isinstance(obj, numbers.Number) 55 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/typing/__init__.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | 3 | from .misc import ( 4 | Address, 5 | AnyAddress, 6 | ChecksumAddress, 7 | HexAddress, 8 | HexStr, 9 | Primitives, 10 | T, 11 | ) 12 | 13 | warnings.warn( 14 | "The eth_utils.typing module will be deprecated in favor " 15 | "of eth-typing in the next major version bump.", 16 | category=DeprecationWarning, 17 | stacklevel=2, 18 | ) 19 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/typing/misc.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | TypeVar, 3 | ) 4 | 5 | from ...typing import ( # noqa: F401 6 | Address, 7 | AnyAddress, 8 | ChecksumAddress, 9 | HexAddress, 10 | HexStr, 11 | Primitives, 12 | ) 13 | 14 | T = TypeVar("T") 15 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/ethereum/utils/units.py: -------------------------------------------------------------------------------- 1 | import decimal 2 | 3 | # Units are in their own module here, so that they can keep this 4 | # formatting, as this module is excluded from black in pyproject.toml 5 | # fmt: off 6 | units = { 7 | 'wei': decimal.Decimal('1'), # noqa: E241 8 | 'kwei': decimal.Decimal('1000'), # noqa: E241 9 | 'babbage': decimal.Decimal('1000'), # noqa: E241 10 | 'femtoether': decimal.Decimal('1000'), # noqa: E241 11 | 'mwei': decimal.Decimal('1000000'), # noqa: E241 12 | 'lovelace': decimal.Decimal('1000000'), # noqa: E241 13 | 'picoether': decimal.Decimal('1000000'), # noqa: E241 14 | 'gwei': decimal.Decimal('1000000000'), # noqa: E241 15 | 'shannon': decimal.Decimal('1000000000'), # noqa: E241 16 | 'nanoether': decimal.Decimal('1000000000'), # noqa: E241 17 | 'nano': decimal.Decimal('1000000000'), # noqa: E241 18 | 'szabo': decimal.Decimal('1000000000000'), # noqa: E241 19 | 'microether': decimal.Decimal('1000000000000'), # noqa: E241 20 | 'micro': decimal.Decimal('1000000000000'), # noqa: E241 21 | 'finney': decimal.Decimal('1000000000000000'), # noqa: E241 22 | 'milliether': decimal.Decimal('1000000000000000'), # noqa: E241 23 | 'milli': decimal.Decimal('1000000000000000'), # noqa: E241 24 | 'ether': decimal.Decimal('1000000000000000000'), # noqa: E241 25 | 'kether': decimal.Decimal('1000000000000000000000'), # noqa: E241 26 | 'grand': decimal.Decimal('1000000000000000000000'), # noqa: E241 27 | 'mether': decimal.Decimal('1000000000000000000000000'), # noqa: E241 28 | 'gether': decimal.Decimal('1000000000000000000000000000'), # noqa: E241 29 | 'tether': decimal.Decimal('1000000000000000000000000000000'), # noqa: E241 30 | } 31 | # fmt: on 32 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/keccak/__init__.py: -------------------------------------------------------------------------------- 1 | from .keccak import SHA3 2 | 3 | __all__ = ['SHA3'] 4 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/lark/__init__.py: -------------------------------------------------------------------------------- 1 | from .exceptions import ( 2 | GrammarError, 3 | LarkError, 4 | LexError, 5 | ParseError, 6 | UnexpectedCharacters, 7 | UnexpectedEOF, 8 | UnexpectedInput, 9 | UnexpectedToken, 10 | ) 11 | from .lark import Lark 12 | from .lexer import Token 13 | from .tree import ParseTree, Tree 14 | from .utils import logger 15 | from .visitors import Discard, Transformer, Transformer_NonRecursive, Visitor, v_args 16 | 17 | __version__: str = "1.2.0" 18 | 19 | __all__ = ( 20 | "GrammarError", 21 | "LarkError", 22 | "LexError", 23 | "ParseError", 24 | "UnexpectedCharacters", 25 | "UnexpectedEOF", 26 | "UnexpectedInput", 27 | "UnexpectedToken", 28 | "Lark", 29 | "Token", 30 | "ParseTree", 31 | "Tree", 32 | "logger", 33 | "Discard", 34 | "Transformer", 35 | "Transformer_NonRecursive", 36 | "Visitor", 37 | "v_args", 38 | ) 39 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/lark/__pyinstaller/__init__.py: -------------------------------------------------------------------------------- 1 | # For usage of lark with PyInstaller. See https://pyinstaller-sample-hook.readthedocs.io/en/latest/index.html 2 | 3 | import os 4 | 5 | def get_hook_dirs(): 6 | return [os.path.dirname(__file__)] 7 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/lark/__pyinstaller/hook-lark.py: -------------------------------------------------------------------------------- 1 | #----------------------------------------------------------------------------- 2 | # Copyright (c) 2017-2020, PyInstaller Development Team. 3 | # 4 | # Distributed under the terms of the GNU General Public License (version 2 5 | # or later) with exception for distributing the bootloader. 6 | # 7 | # The full license is in the file COPYING.txt, distributed with this software. 8 | # 9 | # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception) 10 | #----------------------------------------------------------------------------- 11 | 12 | from PyInstaller.utils.hooks import collect_data_files 13 | 14 | datas = collect_data_files('lark') 15 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/lark/ast_utils.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module of utilities for transforming a lark.Tree into a custom Abstract Syntax Tree (AST defined in classes) 3 | """ 4 | 5 | import inspect, re 6 | import types 7 | from typing import Optional, Callable 8 | 9 | from lark import Transformer, v_args 10 | 11 | class Ast: 12 | """Abstract class 13 | 14 | Subclasses will be collected by `create_transformer()` 15 | """ 16 | pass 17 | 18 | class AsList: 19 | """Abstract class 20 | 21 | Subclasses will be instantiated with the parse results as a single list, instead of as arguments. 22 | """ 23 | 24 | class WithMeta: 25 | """Abstract class 26 | 27 | Subclasses will be instantiated with the Meta instance of the tree. (see ``v_args`` for more detail) 28 | """ 29 | pass 30 | 31 | def camel_to_snake(name): 32 | return re.sub(r'(? Transformer: 37 | """Collects `Ast` subclasses from the given module, and creates a Lark transformer that builds the AST. 38 | 39 | For each class, we create a corresponding rule in the transformer, with a matching name. 40 | CamelCase names will be converted into snake_case. Example: "CodeBlock" -> "code_block". 41 | 42 | Classes starting with an underscore (`_`) will be skipped. 43 | 44 | Parameters: 45 | ast_module: A Python module containing all the subclasses of ``ast_utils.Ast`` 46 | transformer (Optional[Transformer]): An initial transformer. Its attributes may be overwritten. 47 | decorator_factory (Callable): An optional callable accepting two booleans, inline, and meta, 48 | and returning a decorator for the methods of ``transformer``. (default: ``v_args``). 49 | """ 50 | t = transformer or Transformer() 51 | 52 | for name, obj in inspect.getmembers(ast_module): 53 | if not name.startswith('_') and inspect.isclass(obj): 54 | if issubclass(obj, Ast): 55 | wrapper = decorator_factory(inline=not issubclass(obj, AsList), meta=issubclass(obj, WithMeta)) 56 | obj = wrapper(obj).__get__(t) 57 | setattr(t, camel_to_snake(name), obj) 58 | 59 | return t 60 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/lark/common.py: -------------------------------------------------------------------------------- 1 | from copy import deepcopy 2 | import sys 3 | from types import ModuleType 4 | from typing import Callable, Collection, Dict, Optional, TYPE_CHECKING, List 5 | 6 | if TYPE_CHECKING: 7 | from .lark import PostLex 8 | from .lexer import Lexer 9 | from .grammar import Rule 10 | from typing import Union, Type 11 | from typing import Literal 12 | if sys.version_info >= (3, 10): 13 | from typing import TypeAlias 14 | else: 15 | from typing_extensions import TypeAlias 16 | 17 | from .utils import Serialize 18 | from .lexer import TerminalDef, Token 19 | 20 | ###{standalone 21 | 22 | _ParserArgType: 'TypeAlias' = 'Literal["earley", "lalr", "cyk", "auto"]' 23 | _LexerArgType: 'TypeAlias' = 'Union[Literal["auto", "basic", "contextual", "dynamic", "dynamic_complete"], Type[Lexer]]' 24 | _LexerCallback = Callable[[Token], Token] 25 | ParserCallbacks = Dict[str, Callable] 26 | 27 | class LexerConf(Serialize): 28 | __serialize_fields__ = 'terminals', 'ignore', 'g_regex_flags', 'use_bytes', 'lexer_type' 29 | __serialize_namespace__ = TerminalDef, 30 | 31 | terminals: Collection[TerminalDef] 32 | re_module: ModuleType 33 | ignore: Collection[str] 34 | postlex: 'Optional[PostLex]' 35 | callbacks: Dict[str, _LexerCallback] 36 | g_regex_flags: int 37 | skip_validation: bool 38 | use_bytes: bool 39 | lexer_type: Optional[_LexerArgType] 40 | strict: bool 41 | 42 | def __init__(self, terminals: Collection[TerminalDef], re_module: ModuleType, ignore: Collection[str]=(), postlex: 'Optional[PostLex]'=None, 43 | callbacks: Optional[Dict[str, _LexerCallback]]=None, g_regex_flags: int=0, skip_validation: bool=False, use_bytes: bool=False, strict: bool=False): 44 | self.terminals = terminals 45 | self.terminals_by_name = {t.name: t for t in self.terminals} 46 | assert len(self.terminals) == len(self.terminals_by_name) 47 | self.ignore = ignore 48 | self.postlex = postlex 49 | self.callbacks = callbacks or {} 50 | self.g_regex_flags = g_regex_flags 51 | self.re_module = re_module 52 | self.skip_validation = skip_validation 53 | self.use_bytes = use_bytes 54 | self.strict = strict 55 | self.lexer_type = None 56 | 57 | def _deserialize(self): 58 | self.terminals_by_name = {t.name: t for t in self.terminals} 59 | 60 | def __deepcopy__(self, memo=None): 61 | return type(self)( 62 | deepcopy(self.terminals, memo), 63 | self.re_module, 64 | deepcopy(self.ignore, memo), 65 | deepcopy(self.postlex, memo), 66 | deepcopy(self.callbacks, memo), 67 | deepcopy(self.g_regex_flags, memo), 68 | deepcopy(self.skip_validation, memo), 69 | deepcopy(self.use_bytes, memo), 70 | ) 71 | 72 | class ParserConf(Serialize): 73 | __serialize_fields__ = 'rules', 'start', 'parser_type' 74 | 75 | rules: List['Rule'] 76 | callbacks: ParserCallbacks 77 | start: List[str] 78 | parser_type: _ParserArgType 79 | 80 | def __init__(self, rules: List['Rule'], callbacks: ParserCallbacks, start: List[str]): 81 | assert isinstance(start, list) 82 | self.rules = rules 83 | self.callbacks = callbacks 84 | self.start = start 85 | 86 | ###} 87 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/lark/grammars/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/lark/grammars/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/lark/grammars/common.lark: -------------------------------------------------------------------------------- 1 | // Basic terminals for common use 2 | 3 | 4 | // 5 | // Numbers 6 | // 7 | 8 | DIGIT: "0".."9" 9 | HEXDIGIT: "a".."f"|"A".."F"|DIGIT 10 | 11 | INT: DIGIT+ 12 | SIGNED_INT: ["+"|"-"] INT 13 | DECIMAL: INT "." INT? | "." INT 14 | 15 | // float = /-?\d+(\.\d+)?([eE][+-]?\d+)?/ 16 | _EXP: ("e"|"E") SIGNED_INT 17 | FLOAT: INT _EXP | DECIMAL _EXP? 18 | SIGNED_FLOAT: ["+"|"-"] FLOAT 19 | 20 | NUMBER: FLOAT | INT 21 | SIGNED_NUMBER: ["+"|"-"] NUMBER 22 | 23 | // 24 | // Strings 25 | // 26 | _STRING_INNER: /.*?/ 27 | _STRING_ESC_INNER: _STRING_INNER /(? ignore 19 | | "%import" import_path ["->" name] -> import 20 | | "%import" import_path name_list -> multi_import 21 | | "%override" rule -> override_rule 22 | | "%declare" name+ -> declare 23 | 24 | !import_path: "."? name ("." name)* 25 | name_list: "(" name ("," name)* ")" 26 | 27 | ?expansions: alias (_VBAR alias)* 28 | 29 | ?alias: expansion ["->" RULE] 30 | 31 | ?expansion: expr* 32 | 33 | ?expr: atom [OP | "~" NUMBER [".." NUMBER]] 34 | 35 | ?atom: "(" expansions ")" 36 | | "[" expansions "]" -> maybe 37 | | value 38 | 39 | ?value: STRING ".." STRING -> literal_range 40 | | name 41 | | (REGEXP | STRING) -> literal 42 | | name "{" value ("," value)* "}" -> template_usage 43 | 44 | name: RULE 45 | | TOKEN 46 | 47 | _VBAR: _NL? "|" 48 | OP: /[+*]|[?](?![a-z])/ 49 | RULE: /!?[_?]?[a-z][_a-z0-9]*/ 50 | TOKEN: /_?[A-Z][_A-Z0-9]*/ 51 | STRING: _STRING "i"? 52 | REGEXP: /\/(?!\/)(\\\/|\\\\|[^\/])*?\/[imslux]*/ 53 | _NL: /(\r?\n)+\s*/ 54 | 55 | %import common.ESCAPED_STRING -> _STRING 56 | %import common.SIGNED_INT -> NUMBER 57 | %import common.WS_INLINE 58 | 59 | COMMENT: /\s*/ "//" /[^\n]/* | /\s*/ "#" /[^\n]/* 60 | 61 | %ignore WS_INLINE 62 | %ignore COMMENT 63 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/lark/grammars/unicode.lark: -------------------------------------------------------------------------------- 1 | // TODO: LETTER, WORD, etc. 2 | 3 | // 4 | // Whitespace 5 | // 6 | WS_INLINE: /[ \t\xa0]/+ 7 | WS: /[ \t\xa0\f\r\n]/+ 8 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/lark/parsers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/lark/parsers/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/lark/parsers/earley_common.py: -------------------------------------------------------------------------------- 1 | """This module implements useful building blocks for the Earley parser 2 | """ 3 | 4 | 5 | class Item: 6 | "An Earley Item, the atom of the algorithm." 7 | 8 | __slots__ = ('s', 'rule', 'ptr', 'start', 'is_complete', 'expect', 'previous', 'node', '_hash') 9 | def __init__(self, rule, ptr, start): 10 | self.is_complete = len(rule.expansion) == ptr 11 | self.rule = rule # rule 12 | self.ptr = ptr # ptr 13 | self.start = start # j 14 | self.node = None # w 15 | if self.is_complete: 16 | self.s = rule.origin 17 | self.expect = None 18 | self.previous = rule.expansion[ptr - 1] if ptr > 0 and len(rule.expansion) else None 19 | else: 20 | self.s = (rule, ptr) 21 | self.expect = rule.expansion[ptr] 22 | self.previous = rule.expansion[ptr - 1] if ptr > 0 and len(rule.expansion) else None 23 | self._hash = hash((self.s, self.start, self.rule)) 24 | 25 | def advance(self): 26 | return Item(self.rule, self.ptr + 1, self.start) 27 | 28 | def __eq__(self, other): 29 | return self is other or (self.s == other.s and self.start == other.start and self.rule == other.rule) 30 | 31 | def __hash__(self): 32 | return self._hash 33 | 34 | def __repr__(self): 35 | before = ( expansion.name for expansion in self.rule.expansion[:self.ptr] ) 36 | after = ( expansion.name for expansion in self.rule.expansion[self.ptr:] ) 37 | symbol = "{} ::= {}* {}".format(self.rule.origin.name, ' '.join(before), ' '.join(after)) 38 | return '%s (%d)' % (symbol, self.start) 39 | 40 | 41 | # class TransitiveItem(Item): 42 | # ... # removed at commit 4c1cfb2faf24e8f8bff7112627a00b94d261b420 43 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/lark/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/lark/py.typed -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/lark/tools/__init__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from argparse import ArgumentParser, FileType 3 | from textwrap import indent 4 | from logging import DEBUG, INFO, WARN, ERROR 5 | from typing import Optional 6 | import warnings 7 | 8 | from lark import Lark, logger 9 | try: 10 | from interegular import logger as interegular_logger 11 | has_interegular = True 12 | except ImportError: 13 | has_interegular = False 14 | 15 | lalr_argparser = ArgumentParser(add_help=False, epilog='Look at the Lark documentation for more info on the options') 16 | 17 | flags = [ 18 | ('d', 'debug'), 19 | 'keep_all_tokens', 20 | 'regex', 21 | 'propagate_positions', 22 | 'maybe_placeholders', 23 | 'use_bytes' 24 | ] 25 | 26 | options = ['start', 'lexer'] 27 | 28 | lalr_argparser.add_argument('-v', '--verbose', action='count', default=0, help="Increase Logger output level, up to three times") 29 | lalr_argparser.add_argument('-s', '--start', action='append', default=[]) 30 | lalr_argparser.add_argument('-l', '--lexer', default='contextual', choices=('basic', 'contextual')) 31 | lalr_argparser.add_argument('-o', '--out', type=FileType('w', encoding='utf-8'), default=sys.stdout, help='the output file (default=stdout)') 32 | lalr_argparser.add_argument('grammar_file', type=FileType('r', encoding='utf-8'), help='A valid .lark file') 33 | 34 | for flag in flags: 35 | if isinstance(flag, tuple): 36 | options.append(flag[1]) 37 | lalr_argparser.add_argument('-' + flag[0], '--' + flag[1], action='store_true') 38 | elif isinstance(flag, str): 39 | options.append(flag) 40 | lalr_argparser.add_argument('--' + flag, action='store_true') 41 | else: 42 | raise NotImplementedError("flags must only contain strings or tuples of strings") 43 | 44 | 45 | def build_lalr(namespace): 46 | logger.setLevel((ERROR, WARN, INFO, DEBUG)[min(namespace.verbose, 3)]) 47 | if has_interegular: 48 | interegular_logger.setLevel(logger.getEffectiveLevel()) 49 | if len(namespace.start) == 0: 50 | namespace.start.append('start') 51 | kwargs = {n: getattr(namespace, n) for n in options} 52 | return Lark(namespace.grammar_file, parser='lalr', **kwargs), namespace.out 53 | 54 | 55 | def showwarning_as_comment(message, category, filename, lineno, file=None, line=None): 56 | # Based on warnings._showwarnmsg_impl 57 | text = warnings.formatwarning(message, category, filename, lineno, line) 58 | text = indent(text, '# ') 59 | if file is None: 60 | file = sys.stderr 61 | if file is None: 62 | return 63 | try: 64 | file.write(text) 65 | except OSError: 66 | pass 67 | 68 | 69 | def make_warnings_comments(): 70 | warnings.showwarning = showwarning_as_comment 71 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/lark/tools/serialize.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import json 3 | 4 | from lark.grammar import Rule 5 | from lark.lexer import TerminalDef 6 | from lark.tools import lalr_argparser, build_lalr 7 | 8 | import argparse 9 | 10 | argparser = argparse.ArgumentParser(prog='python -m lark.tools.serialize', parents=[lalr_argparser], 11 | description="Lark Serialization Tool - Stores Lark's internal state & LALR analysis as a JSON file", 12 | epilog='Look at the Lark documentation for more info on the options') 13 | 14 | 15 | def serialize(lark_inst, outfile): 16 | data, memo = lark_inst.memo_serialize([TerminalDef, Rule]) 17 | outfile.write('{\n') 18 | outfile.write(' "data": %s,\n' % json.dumps(data)) 19 | outfile.write(' "memo": %s\n' % json.dumps(memo)) 20 | outfile.write('}\n') 21 | 22 | 23 | def main(): 24 | if len(sys.argv)==1: 25 | argparser.print_help(sys.stderr) 26 | sys.exit(1) 27 | ns = argparser.parse_args() 28 | serialize(*build_lalr(ns)) 29 | 30 | 31 | if __name__ == '__main__': 32 | main() 33 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import importlib.metadata 4 | import typing 5 | 6 | # from packaging.version import Version 7 | 8 | from .decorators import ( 9 | post_dump, 10 | post_load, 11 | pre_dump, 12 | pre_load, 13 | validates, 14 | validates_schema, 15 | ) 16 | from .exceptions import ValidationError 17 | from .schema import Schema, SchemaOpts 18 | from .utils import EXCLUDE, INCLUDE, RAISE, missing, pprint 19 | 20 | from . import fields 21 | 22 | 23 | def __getattr__(name: str) -> typing.Any: 24 | import warnings 25 | 26 | if name == "__version__": 27 | warnings.warn( 28 | "The '__version__' attribute is deprecated and will be removed in" 29 | " in a future version. Use feature detection or" 30 | " 'importlib.metadata.version(\"marshmallow\")' instead.", 31 | DeprecationWarning, 32 | stacklevel=2, 33 | ) 34 | return importlib.metadata.version("marshmallow") 35 | 36 | # if name == "__parsed_version__": 37 | # warnings.warn( 38 | # "The '__parsed_version__' attribute is deprecated and will be removed in" 39 | # " in a future version. Use feature detection or" 40 | # " 'packaging.Version(importlib.metadata.version(\"marshmallow\"))' instead.", 41 | # DeprecationWarning, 42 | # stacklevel=2, 43 | # ) 44 | # return Version(importlib.metadata.version("marshmallow")) 45 | 46 | if name == "__version_info__": 47 | warnings.warn( 48 | "The '__version_info__' attribute is deprecated and will be removed in" 49 | " in a future version. Use feature detection or" 50 | " 'packaging.Version(importlib.metadata.version(\"marshmallow\")).release' instead.", 51 | DeprecationWarning, 52 | stacklevel=2, 53 | ) 54 | # __parsed_version__ = Version(importlib.metadata.version("marshmallow")) 55 | __version_info__: tuple[int, int, int] | tuple[int, int, int, str, int] = ( 56 | __parsed_version__.release # type: ignore[assignment] 57 | ) 58 | if __parsed_version__.pre: 59 | __version_info__ += __parsed_version__.pre # type: ignore[assignment] 60 | return __version_info__ 61 | 62 | raise AttributeError(name) 63 | 64 | 65 | __all__ = [ 66 | "EXCLUDE", 67 | "INCLUDE", 68 | "RAISE", 69 | "Schema", 70 | "SchemaOpts", 71 | "fields", 72 | "validates", 73 | "validates_schema", 74 | "pre_dump", 75 | "post_dump", 76 | "pre_load", 77 | "post_load", 78 | "pprint", 79 | "ValidationError", 80 | "missing", 81 | ] 82 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow/base.py: -------------------------------------------------------------------------------- 1 | """Abstract base classes. 2 | 3 | These are necessary to avoid circular imports between schema.py and fields.py. 4 | 5 | .. warning:: 6 | 7 | This module is treated as private API. 8 | Users should not need to use this module directly. 9 | """ 10 | 11 | from __future__ import annotations 12 | 13 | from abc import ABC, abstractmethod 14 | 15 | 16 | class FieldABC(ABC): 17 | """Abstract base class from which all Field classes inherit.""" 18 | 19 | parent = None 20 | name = None 21 | root = None 22 | 23 | @abstractmethod 24 | def serialize(self, attr, obj, accessor=None): 25 | pass 26 | 27 | @abstractmethod 28 | def deserialize(self, value): 29 | pass 30 | 31 | @abstractmethod 32 | def _serialize(self, value, attr, obj, **kwargs): 33 | pass 34 | 35 | @abstractmethod 36 | def _deserialize(self, value, attr, data, **kwargs): 37 | pass 38 | 39 | 40 | class SchemaABC(ABC): 41 | """Abstract base class from which all Schemas inherit.""" 42 | 43 | @abstractmethod 44 | def dump(self, obj, *, many: bool | None = None): 45 | pass 46 | 47 | @abstractmethod 48 | def dumps(self, obj, *, many: bool | None = None): 49 | pass 50 | 51 | @abstractmethod 52 | def load(self, data, *, many: bool | None = None, partial=None, unknown=None): 53 | pass 54 | 55 | @abstractmethod 56 | def loads( 57 | self, 58 | json_data, 59 | *, 60 | many: bool | None = None, 61 | partial=None, 62 | unknown=None, 63 | **kwargs, 64 | ): 65 | pass 66 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow/class_registry.py: -------------------------------------------------------------------------------- 1 | """A registry of :class:`Schema ` classes. This allows for string 2 | lookup of schemas, which may be used with 3 | class:`fields.Nested `. 4 | 5 | .. warning:: 6 | 7 | This module is treated as private API. 8 | Users should not need to use this module directly. 9 | """ 10 | 11 | from __future__ import annotations 12 | 13 | import typing 14 | 15 | from .exceptions import RegistryError 16 | 17 | if typing.TYPE_CHECKING: 18 | from . import Schema 19 | 20 | SchemaType = typing.Type[Schema] 21 | 22 | # { 23 | # : 24 | # : 25 | # } 26 | _registry = {} # type: dict[str, list[SchemaType]] 27 | 28 | 29 | def register(classname: str, cls: SchemaType) -> None: 30 | """Add a class to the registry of serializer classes. When a class is 31 | registered, an entry for both its classname and its full, module-qualified 32 | path are added to the registry. 33 | 34 | Example: :: 35 | 36 | class MyClass: 37 | pass 38 | 39 | 40 | register("MyClass", MyClass) 41 | # Registry: 42 | # { 43 | # 'MyClass': [path.to.MyClass], 44 | # 'path.to.MyClass': [path.to.MyClass], 45 | # } 46 | 47 | """ 48 | # Module where the class is located 49 | module = cls.__module__ 50 | # Full module path to the class 51 | # e.g. user.schemas.UserSchema 52 | fullpath = ".".join([module, classname]) 53 | # If the class is already registered; need to check if the entries are 54 | # in the same module as cls to avoid having multiple instances of the same 55 | # class in the registry 56 | if classname in _registry and not any( 57 | each.__module__ == module for each in _registry[classname] 58 | ): 59 | _registry[classname].append(cls) 60 | elif classname not in _registry: 61 | _registry[classname] = [cls] 62 | 63 | # Also register the full path 64 | if fullpath not in _registry: 65 | _registry.setdefault(fullpath, []).append(cls) 66 | else: 67 | # If fullpath does exist, replace existing entry 68 | _registry[fullpath] = [cls] 69 | return None 70 | 71 | 72 | def get_class(classname: str, all: bool = False) -> list[SchemaType] | SchemaType: 73 | """Retrieve a class from the registry. 74 | 75 | :raises: marshmallow.exceptions.RegistryError if the class cannot be found 76 | or if there are multiple entries for the given class name. 77 | """ 78 | try: 79 | classes = _registry[classname] 80 | except KeyError as error: 81 | raise RegistryError( 82 | f"Class with name {classname!r} was not found. You may need " 83 | "to import the class." 84 | ) from error 85 | if len(classes) > 1: 86 | if all: 87 | return _registry[classname] 88 | raise RegistryError( 89 | f"Multiple classes with name {classname!r} " 90 | "were found. Please use the full, " 91 | "module-qualified path." 92 | ) 93 | else: 94 | return _registry[classname][0] 95 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow/error_store.py: -------------------------------------------------------------------------------- 1 | """Utilities for storing collections of error messages. 2 | 3 | .. warning:: 4 | 5 | This module is treated as private API. 6 | Users should not need to use this module directly. 7 | """ 8 | 9 | from .exceptions import SCHEMA 10 | 11 | 12 | class ErrorStore: 13 | def __init__(self): 14 | #: Dictionary of errors stored during serialization 15 | self.errors = {} 16 | 17 | def store_error(self, messages, field_name=SCHEMA, index=None): 18 | # field error -> store/merge error messages under field name key 19 | # schema error -> if string or list, store/merge under _schema key 20 | # -> if dict, store/merge with other top-level keys 21 | if field_name != SCHEMA or not isinstance(messages, dict): 22 | messages = {field_name: messages} 23 | if index is not None: 24 | messages = {index: messages} 25 | self.errors = merge_errors(self.errors, messages) 26 | 27 | 28 | def merge_errors(errors1, errors2): 29 | """Deeply merge two error messages. 30 | 31 | The format of ``errors1`` and ``errors2`` matches the ``message`` 32 | parameter of :exc:`marshmallow.exceptions.ValidationError`. 33 | """ 34 | if not errors1: 35 | return errors2 36 | if not errors2: 37 | return errors1 38 | if isinstance(errors1, list): 39 | if isinstance(errors2, list): 40 | return errors1 + errors2 41 | if isinstance(errors2, dict): 42 | return dict(errors2, **{SCHEMA: merge_errors(errors1, errors2.get(SCHEMA))}) 43 | return errors1 + [errors2] 44 | if isinstance(errors1, dict): 45 | if isinstance(errors2, list): 46 | return dict(errors1, **{SCHEMA: merge_errors(errors1.get(SCHEMA), errors2)}) 47 | if isinstance(errors2, dict): 48 | errors = dict(errors1) 49 | for key, val in errors2.items(): 50 | if key in errors: 51 | errors[key] = merge_errors(errors[key], val) 52 | else: 53 | errors[key] = val 54 | return errors 55 | return dict(errors1, **{SCHEMA: merge_errors(errors1.get(SCHEMA), errors2)}) 56 | if isinstance(errors2, list): 57 | return [errors1] + errors2 58 | if isinstance(errors2, dict): 59 | return dict(errors2, **{SCHEMA: merge_errors(errors1, errors2.get(SCHEMA))}) 60 | return [errors1, errors2] 61 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow/exceptions.py: -------------------------------------------------------------------------------- 1 | """Exception classes for marshmallow-related errors.""" 2 | 3 | from __future__ import annotations 4 | 5 | import typing 6 | 7 | # Key used for schema-level validation errors 8 | SCHEMA = "_schema" 9 | 10 | 11 | class MarshmallowError(Exception): 12 | """Base class for all marshmallow-related errors.""" 13 | 14 | 15 | class ValidationError(MarshmallowError): 16 | """Raised when validation fails on a field or schema. 17 | 18 | Validators and custom fields should raise this exception. 19 | 20 | :param message: An error message, list of error messages, or dict of 21 | error messages. If a dict, the keys are subitems and the values are error messages. 22 | :param field_name: Field name to store the error on. 23 | If `None`, the error is stored as schema-level error. 24 | :param data: Raw input data. 25 | :param valid_data: Valid (de)serialized data. 26 | """ 27 | 28 | def __init__( 29 | self, 30 | message: str | list | dict, 31 | field_name: str = SCHEMA, 32 | data: typing.Mapping[str, typing.Any] 33 | | typing.Iterable[typing.Mapping[str, typing.Any]] 34 | | None = None, 35 | valid_data: list[dict[str, typing.Any]] | dict[str, typing.Any] | None = None, 36 | **kwargs, 37 | ): 38 | self.messages = [message] if isinstance(message, (str, bytes)) else message 39 | self.field_name = field_name 40 | self.data = data 41 | self.valid_data = valid_data 42 | self.kwargs = kwargs 43 | super().__init__(message) 44 | 45 | def normalized_messages(self): 46 | if self.field_name == SCHEMA and isinstance(self.messages, dict): 47 | return self.messages 48 | return {self.field_name: self.messages} 49 | 50 | @property 51 | def messages_dict(self) -> dict[str, typing.Any]: 52 | if not isinstance(self.messages, dict): 53 | raise TypeError( 54 | "cannot access 'messages_dict' when 'messages' is of type " 55 | + type(self.messages).__name__ 56 | ) 57 | return self.messages 58 | 59 | 60 | class RegistryError(NameError): 61 | """Raised when an invalid operation is performed on the serializer 62 | class registry. 63 | """ 64 | 65 | 66 | class StringNotCollectionError(MarshmallowError, TypeError): 67 | """Raised when a string is passed when a list of strings is expected.""" 68 | 69 | 70 | class FieldInstanceResolutionError(MarshmallowError, TypeError): 71 | """Raised when schema to instantiate is neither a Schema class nor an instance.""" 72 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow/orderedset.py: -------------------------------------------------------------------------------- 1 | # OrderedSet 2 | # Copyright (c) 2009 Raymond Hettinger 3 | # 4 | # Permission is hereby granted, free of charge, to any person 5 | # obtaining a copy of this software and associated documentation files 6 | # (the "Software"), to deal in the Software without restriction, 7 | # including without limitation the rights to use, copy, modify, merge, 8 | # publish, distribute, sublicense, and/or sell copies of the Software, 9 | # and to permit persons to whom the Software is furnished to do so, 10 | # subject to the following conditions: 11 | # 12 | # The above copyright notice and this permission notice shall be 13 | # included in all copies or substantial portions of the Software. 14 | # 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 17 | # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 19 | # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 20 | # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 21 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | # OTHER DEALINGS IN THE SOFTWARE. 23 | from collections.abc import MutableSet 24 | 25 | 26 | class OrderedSet(MutableSet): 27 | def __init__(self, iterable=None): 28 | self.end = end = [] 29 | end += [None, end, end] # sentinel node for doubly linked list 30 | self.map = {} # key --> [key, prev, next] 31 | if iterable is not None: 32 | self |= iterable 33 | 34 | def __len__(self): 35 | return len(self.map) 36 | 37 | def __contains__(self, key): 38 | return key in self.map 39 | 40 | def add(self, key): 41 | if key not in self.map: 42 | end = self.end 43 | curr = end[1] 44 | curr[2] = end[1] = self.map[key] = [key, curr, end] 45 | 46 | def discard(self, key): 47 | if key in self.map: 48 | key, prev, next = self.map.pop(key) 49 | prev[2] = next 50 | next[1] = prev 51 | 52 | def __iter__(self): 53 | end = self.end 54 | curr = end[2] 55 | while curr is not end: 56 | yield curr[0] 57 | curr = curr[2] 58 | 59 | def __reversed__(self): 60 | end = self.end 61 | curr = end[1] 62 | while curr is not end: 63 | yield curr[0] 64 | curr = curr[1] 65 | 66 | def pop(self, last=True): 67 | if not self: 68 | raise KeyError("set is empty") 69 | key = self.end[1][0] if last else self.end[2][0] 70 | self.discard(key) 71 | return key 72 | 73 | def __repr__(self): 74 | if not self: 75 | return f"{self.__class__.__name__}()" 76 | return f"{self.__class__.__name__}({list(self)!r})" 77 | 78 | def __eq__(self, other): 79 | if isinstance(other, OrderedSet): 80 | return len(self) == len(other) and list(self) == list(other) 81 | return set(self) == set(other) 82 | 83 | 84 | if __name__ == "__main__": 85 | s = OrderedSet("abracadaba") 86 | t = OrderedSet("simsalabim") 87 | print(s | t) 88 | print(s & t) 89 | print(s - t) 90 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/marshmallow/py.typed -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow/types.py: -------------------------------------------------------------------------------- 1 | """Type aliases. 2 | 3 | .. warning:: 4 | 5 | This module is provisional. Types may be modified, added, and removed between minor releases. 6 | """ 7 | 8 | import typing 9 | 10 | StrSequenceOrSet = typing.Union[typing.Sequence[str], typing.AbstractSet[str]] 11 | Tag = typing.Union[str, typing.Tuple[str, bool]] 12 | Validator = typing.Callable[[typing.Any], typing.Any] 13 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow/warnings.py: -------------------------------------------------------------------------------- 1 | class RemovedInMarshmallow4Warning(DeprecationWarning): 2 | pass 3 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow_dataclass/collection_field.py: -------------------------------------------------------------------------------- 1 | import typing 2 | 3 | import marshmallow 4 | 5 | 6 | class Sequence(marshmallow.fields.List): 7 | """ 8 | A sequence field, basically an immutable version of the list field. 9 | """ 10 | 11 | def _deserialize( # type: ignore[override] 12 | self, 13 | value: typing.Any, 14 | attr: typing.Any, 15 | data: typing.Any, 16 | **kwargs: typing.Any, 17 | ) -> typing.Optional[typing.Sequence[typing.Any]]: 18 | optional_list = super()._deserialize(value, attr, data, **kwargs) 19 | return None if optional_list is None else tuple(optional_list) 20 | 21 | 22 | class Set(marshmallow.fields.List): 23 | """ 24 | A set field. A set is an unordered/mutable collection of unique elements, same for frozenset 25 | except it's immutable. 26 | 27 | Notes: 28 | Beware the a Set guarantees uniqueness in the resulting list but in return the item's order 29 | will be random. So if the order matters, use a List or Sequence ! 30 | """ 31 | 32 | def __init__( 33 | self, 34 | cls_or_instance: typing.Union[marshmallow.fields.Field, type], 35 | frozen: bool = False, 36 | **kwargs, 37 | ): 38 | super().__init__(cls_or_instance, **kwargs) 39 | self.set_type: typing.Type[typing.Union[frozenset, set]] = ( 40 | frozenset if frozen else set 41 | ) 42 | 43 | def _deserialize( # type: ignore[override] 44 | self, 45 | value: typing.Any, 46 | attr: typing.Any, 47 | data: typing.Any, 48 | **kwargs: typing.Any, 49 | ) -> typing.Union[typing.Set[typing.Any], typing.FrozenSet[typing.Any], None]: 50 | optional_list = super()._deserialize(value, attr, data, **kwargs) 51 | return None if optional_list is None else self.set_type(optional_list) 52 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow_dataclass/lazy_class_attribute.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Callable, Optional 2 | 3 | 4 | __all__ = ("lazy_class_attribute",) 5 | 6 | 7 | class LazyClassAttribute: 8 | """Descriptor decorator implementing a class-level, read-only 9 | property, which caches its results on the class(es) on which it 10 | operates. 11 | """ 12 | 13 | __slots__ = ("func", "name", "called", "forward_value") 14 | 15 | def __init__( 16 | self, 17 | func: Callable[..., Any], 18 | name: Optional[str] = None, 19 | forward_value: Any = None, 20 | ): 21 | self.func = func 22 | self.name = name 23 | self.called = False 24 | self.forward_value = forward_value 25 | 26 | def __get__(self, instance, cls=None): 27 | if not cls: 28 | cls = type(instance) 29 | 30 | # avoid recursion 31 | if self.called: 32 | return self.forward_value 33 | 34 | self.called = True 35 | 36 | setattr(cls, self.name, self.func()) 37 | 38 | # "getattr" is used to handle bounded methods 39 | return getattr(cls, self.name) 40 | 41 | def __set_name__(self, owner, name): 42 | self.name = self.name or name 43 | 44 | 45 | lazy_class_attribute = LazyClassAttribute 46 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow_dataclass/mypy.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | from typing import Callable, Optional, Type 3 | 4 | from mypy import nodes 5 | from mypy.plugin import DynamicClassDefContext, Plugin 6 | from mypy.plugins import dataclasses 7 | 8 | import marshmallow_dataclass 9 | 10 | _NEW_TYPE_SIG = inspect.signature(marshmallow_dataclass.NewType) 11 | 12 | 13 | def plugin(version: str) -> Type[Plugin]: 14 | return MarshmallowDataclassPlugin 15 | 16 | 17 | class MarshmallowDataclassPlugin(Plugin): 18 | def get_dynamic_class_hook( 19 | self, fullname: str 20 | ) -> Optional[Callable[[DynamicClassDefContext], None]]: 21 | if fullname == "marshmallow_dataclass.NewType": 22 | return new_type_hook 23 | return None 24 | 25 | def get_class_decorator_hook(self, fullname: str): 26 | if fullname == "marshmallow_dataclass.dataclass": 27 | return dataclasses.dataclass_class_maker_callback 28 | return None 29 | 30 | 31 | def new_type_hook(ctx: DynamicClassDefContext) -> None: 32 | """ 33 | Dynamic class hook for :func:`marshmallow_dataclass.NewType`. 34 | 35 | Uses the type of the ``typ`` argument. 36 | """ 37 | typ = _get_arg_by_name(ctx.call, "typ", _NEW_TYPE_SIG) 38 | if not isinstance(typ, nodes.RefExpr): 39 | return 40 | info = typ.node 41 | if not isinstance(info, nodes.TypeInfo): 42 | return 43 | ctx.api.add_symbol_table_node(ctx.name, nodes.SymbolTableNode(nodes.GDEF, info)) 44 | 45 | 46 | def _get_arg_by_name( 47 | call: nodes.CallExpr, name: str, sig: inspect.Signature 48 | ) -> Optional[nodes.Expression]: 49 | """ 50 | Get value of argument from a call. 51 | 52 | :return: The argument value, or ``None`` if it cannot be found. 53 | 54 | .. warning:: 55 | This probably doesn't yet work for calls with ``*args`` and/or ``*kwargs``. 56 | """ 57 | args = [] 58 | kwargs = {} 59 | for arg_name, arg_value in zip(call.arg_names, call.args): 60 | if arg_name is None: 61 | args.append(arg_value) 62 | else: 63 | kwargs[arg_name] = arg_value 64 | try: 65 | bound_args = sig.bind(*args, **kwargs) 66 | except TypeError: 67 | return None 68 | try: 69 | return bound_args.arguments[name] 70 | except KeyError: 71 | return None 72 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow_dataclass/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/marshmallow_dataclass/py.typed -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow_dataclass/typing.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | import marshmallow.fields 4 | 5 | if sys.version_info >= (3, 9): 6 | from typing import Annotated 7 | else: 8 | from typing_extensions import Annotated 9 | 10 | Url = Annotated[str, marshmallow.fields.Url] 11 | Email = Annotated[str, marshmallow.fields.Email] 12 | 13 | # Aliases 14 | URL = Url 15 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow_dataclass/union_field.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import inspect 3 | from typing import List, Tuple, Any, Optional 4 | 5 | import typeguard 6 | from marshmallow import fields, Schema, ValidationError 7 | 8 | try: 9 | from typeguard import TypeCheckError # type: ignore[attr-defined] 10 | except ImportError: 11 | # typeguard < 3 12 | TypeCheckError = TypeError # type: ignore[misc, assignment] 13 | 14 | if "argname" not in inspect.signature(typeguard.check_type).parameters: 15 | 16 | def _check_type(value, expected_type, argname: str): 17 | return typeguard.check_type(value=value, expected_type=expected_type) 18 | 19 | else: 20 | # typeguard < 3.0.0rc2 21 | def _check_type(value, expected_type, argname: str): 22 | return typeguard.check_type( # type: ignore[call-overload] 23 | value=value, expected_type=expected_type, argname=argname 24 | ) 25 | 26 | 27 | class Union(fields.Field): 28 | """A union field, composed other `Field` classes or instances. 29 | This field serializes elements based on their type, with one of its child fields. 30 | 31 | Example: :: 32 | 33 | number_or_string = UnionField([ 34 | (float, fields.Float()), 35 | (str, fields.Str()) 36 | ]) 37 | 38 | :param union_fields: A list of types and their associated field instance. 39 | :param kwargs: The same keyword arguments that :class:`Field` receives. 40 | """ 41 | 42 | def __init__(self, union_fields: List[Tuple[type, fields.Field]], **kwargs): 43 | super().__init__(**kwargs) 44 | self.union_fields = union_fields 45 | 46 | def _bind_to_schema(self, field_name: str, schema: Schema) -> None: 47 | super()._bind_to_schema(field_name, schema) 48 | new_union_fields = [] 49 | for typ, field in self.union_fields: 50 | field = copy.deepcopy(field) 51 | field._bind_to_schema(field_name, self) 52 | new_union_fields.append((typ, field)) 53 | 54 | self.union_fields = new_union_fields 55 | 56 | def _serialize(self, value: Any, attr: Optional[str], obj, **kwargs) -> Any: 57 | errors = [] 58 | if value is None: 59 | return value 60 | for typ, field in self.union_fields: 61 | try: 62 | _check_type(value=value, expected_type=typ, argname=attr or "anonymous") 63 | return field._serialize(value, attr, obj, **kwargs) 64 | except TypeCheckError as e: 65 | errors.append(e) 66 | raise TypeError( 67 | f"Unable to serialize value with any of the fields in the union: {errors}" 68 | ) 69 | 70 | def _deserialize(self, value: Any, attr: Optional[str], data, **kwargs) -> Any: 71 | errors = [] 72 | for typ, field in self.union_fields: 73 | try: 74 | result = field.deserialize(value, **kwargs) 75 | _check_type( 76 | value=result, expected_type=typ, argname=attr or "anonymous" 77 | ) 78 | return result 79 | except (TypeCheckError, ValidationError) as e: 80 | errors.append(e) 81 | 82 | raise ValidationError(errors) 83 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow_oneofschema/__init__.py: -------------------------------------------------------------------------------- 1 | from .one_of_schema import OneOfSchema # noqa 2 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/marshmallow_oneofschema/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/marshmallow_oneofschema/py.typed -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/msgpack/__init__.py: -------------------------------------------------------------------------------- 1 | from .exceptions import * 2 | from .ext import ExtType, Timestamp 3 | 4 | import os 5 | 6 | 7 | version = (1, 0, 7) 8 | __version__ = "1.0.7" 9 | 10 | 11 | if os.environ.get("MSGPACK_PUREPYTHON"): 12 | from .fallback import Packer, unpackb, Unpacker 13 | else: 14 | try: 15 | from ._cmsgpack import Packer, unpackb, Unpacker 16 | except ImportError: 17 | from .fallback import Packer, unpackb, Unpacker 18 | 19 | 20 | def pack(o, stream, **kwargs): 21 | """ 22 | Pack object `o` and write it to `stream` 23 | 24 | See :class:`Packer` for options. 25 | """ 26 | packer = Packer(**kwargs) 27 | stream.write(packer.pack(o)) 28 | 29 | 30 | def packb(o, **kwargs): 31 | """ 32 | Pack object `o` and return packed bytes 33 | 34 | See :class:`Packer` for options. 35 | """ 36 | return Packer(**kwargs).pack(o) 37 | 38 | 39 | def unpack(stream, **kwargs): 40 | """ 41 | Unpack an object from `stream`. 42 | 43 | Raises `ExtraData` when `stream` contains extra bytes. 44 | See :class:`Unpacker` for options. 45 | """ 46 | data = stream.read() 47 | return unpackb(data, **kwargs) 48 | 49 | 50 | # alias for compatibility to simplejson/marshal/pickle. 51 | load = unpack 52 | loads = unpackb 53 | 54 | dump = pack 55 | dumps = packb 56 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/msgpack/_cmsgpack.pyx: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | #cython: embedsignature=True, c_string_encoding=ascii, language_level=3 3 | from cpython.datetime cimport import_datetime, datetime_new 4 | import_datetime() 5 | 6 | import datetime 7 | cdef object utc = datetime.timezone.utc 8 | cdef object epoch = datetime_new(1970, 1, 1, 0, 0, 0, 0, tz=utc) 9 | 10 | include "_packer.pyx" 11 | include "_unpacker.pyx" 12 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/msgpack/buff_converter.h: -------------------------------------------------------------------------------- 1 | #include "Python.h" 2 | 3 | /* cython does not support this preprocessor check => write it in raw C */ 4 | static PyObject * 5 | buff_to_buff(char *buff, Py_ssize_t size) 6 | { 7 | return PyMemoryView_FromMemory(buff, size, PyBUF_READ); 8 | } 9 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/msgpack/exceptions.py: -------------------------------------------------------------------------------- 1 | class UnpackException(Exception): 2 | """Base class for some exceptions raised while unpacking. 3 | 4 | NOTE: unpack may raise exception other than subclass of 5 | UnpackException. If you want to catch all error, catch 6 | Exception instead. 7 | """ 8 | 9 | 10 | class BufferFull(UnpackException): 11 | pass 12 | 13 | 14 | class OutOfData(UnpackException): 15 | pass 16 | 17 | 18 | class FormatError(ValueError, UnpackException): 19 | """Invalid msgpack format""" 20 | 21 | 22 | class StackError(ValueError, UnpackException): 23 | """Too nested""" 24 | 25 | 26 | # Deprecated. Use ValueError instead 27 | UnpackValueError = ValueError 28 | 29 | 30 | class ExtraData(UnpackValueError): 31 | """ExtraData is raised when there is trailing data. 32 | 33 | This exception is raised while only one-shot (not streaming) 34 | unpack. 35 | """ 36 | 37 | def __init__(self, unpacked, extra): 38 | self.unpacked = unpacked 39 | self.extra = extra 40 | 41 | def __str__(self): 42 | return "unpack(b) received extra data." 43 | 44 | 45 | # Deprecated. Use Exception instead to catch all exception during packing. 46 | PackException = Exception 47 | PackValueError = ValueError 48 | PackOverflowError = OverflowError 49 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/msgpack/pack.h: -------------------------------------------------------------------------------- 1 | /* 2 | * MessagePack for Python packing routine 3 | * 4 | * Copyright (C) 2009 Naoki INADA 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | #include 20 | #include 21 | #include "sysdep.h" 22 | #include 23 | #include 24 | 25 | #ifdef __cplusplus 26 | extern "C" { 27 | #endif 28 | 29 | typedef struct msgpack_packer { 30 | char *buf; 31 | size_t length; 32 | size_t buf_size; 33 | bool use_bin_type; 34 | } msgpack_packer; 35 | 36 | typedef struct Packer Packer; 37 | 38 | static inline int msgpack_pack_write(msgpack_packer* pk, const char *data, size_t l) 39 | { 40 | char* buf = pk->buf; 41 | size_t bs = pk->buf_size; 42 | size_t len = pk->length; 43 | 44 | if (len + l > bs) { 45 | bs = (len + l) * 2; 46 | buf = (char*)PyMem_Realloc(buf, bs); 47 | if (!buf) { 48 | PyErr_NoMemory(); 49 | return -1; 50 | } 51 | } 52 | memcpy(buf + len, data, l); 53 | len += l; 54 | 55 | pk->buf = buf; 56 | pk->buf_size = bs; 57 | pk->length = len; 58 | return 0; 59 | } 60 | 61 | #define msgpack_pack_append_buffer(user, buf, len) \ 62 | return msgpack_pack_write(user, (const char*)buf, len) 63 | 64 | #include "pack_template.h" 65 | 66 | // return -2 when o is too long 67 | static inline int 68 | msgpack_pack_unicode(msgpack_packer *pk, PyObject *o, long long limit) 69 | { 70 | assert(PyUnicode_Check(o)); 71 | 72 | Py_ssize_t len; 73 | const char* buf = PyUnicode_AsUTF8AndSize(o, &len); 74 | if (buf == NULL) 75 | return -1; 76 | 77 | if (len > limit) { 78 | return -2; 79 | } 80 | 81 | int ret = msgpack_pack_raw(pk, len); 82 | if (ret) return ret; 83 | 84 | return msgpack_pack_raw_body(pk, buf, len); 85 | } 86 | 87 | #ifdef __cplusplus 88 | } 89 | #endif 90 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/msgpack/unpack_define.h: -------------------------------------------------------------------------------- 1 | /* 2 | * MessagePack unpacking routine template 3 | * 4 | * Copyright (C) 2008-2010 FURUHASHI Sadayuki 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | #ifndef MSGPACK_UNPACK_DEFINE_H__ 19 | #define MSGPACK_UNPACK_DEFINE_H__ 20 | 21 | #include "msgpack/sysdep.h" 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | #ifdef __cplusplus 28 | extern "C" { 29 | #endif 30 | 31 | 32 | #ifndef MSGPACK_EMBED_STACK_SIZE 33 | #define MSGPACK_EMBED_STACK_SIZE 32 34 | #endif 35 | 36 | 37 | // CS is first byte & 0x1f 38 | typedef enum { 39 | CS_HEADER = 0x00, // nil 40 | 41 | //CS_ = 0x01, 42 | //CS_ = 0x02, // false 43 | //CS_ = 0x03, // true 44 | 45 | CS_BIN_8 = 0x04, 46 | CS_BIN_16 = 0x05, 47 | CS_BIN_32 = 0x06, 48 | 49 | CS_EXT_8 = 0x07, 50 | CS_EXT_16 = 0x08, 51 | CS_EXT_32 = 0x09, 52 | 53 | CS_FLOAT = 0x0a, 54 | CS_DOUBLE = 0x0b, 55 | CS_UINT_8 = 0x0c, 56 | CS_UINT_16 = 0x0d, 57 | CS_UINT_32 = 0x0e, 58 | CS_UINT_64 = 0x0f, 59 | CS_INT_8 = 0x10, 60 | CS_INT_16 = 0x11, 61 | CS_INT_32 = 0x12, 62 | CS_INT_64 = 0x13, 63 | 64 | //CS_FIXEXT1 = 0x14, 65 | //CS_FIXEXT2 = 0x15, 66 | //CS_FIXEXT4 = 0x16, 67 | //CS_FIXEXT8 = 0x17, 68 | //CS_FIXEXT16 = 0x18, 69 | 70 | CS_RAW_8 = 0x19, 71 | CS_RAW_16 = 0x1a, 72 | CS_RAW_32 = 0x1b, 73 | CS_ARRAY_16 = 0x1c, 74 | CS_ARRAY_32 = 0x1d, 75 | CS_MAP_16 = 0x1e, 76 | CS_MAP_32 = 0x1f, 77 | 78 | ACS_RAW_VALUE, 79 | ACS_BIN_VALUE, 80 | ACS_EXT_VALUE, 81 | } msgpack_unpack_state; 82 | 83 | 84 | typedef enum { 85 | CT_ARRAY_ITEM, 86 | CT_MAP_KEY, 87 | CT_MAP_VALUE, 88 | } msgpack_container_type; 89 | 90 | 91 | #ifdef __cplusplus 92 | } 93 | #endif 94 | 95 | #endif /* msgpack/unpack_define.h */ 96 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/parsimonious/__init__.py: -------------------------------------------------------------------------------- 1 | """Parsimonious's public API. Import from here. 2 | 3 | Things may move around in modules deeper than this one. 4 | 5 | """ 6 | from .exceptions import (ParseError, IncompleteParseError, 7 | VisitationError, UndefinedLabel, 8 | BadGrammar) 9 | from .grammar import Grammar, TokenGrammar 10 | from .nodes import NodeVisitor, VisitationError, rule 11 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/parsimonious/utils.py: -------------------------------------------------------------------------------- 1 | """General tools which don't depend on other parts of Parsimonious""" 2 | 3 | import ast 4 | 5 | 6 | class StrAndRepr(object): 7 | """Mix-in which gives the class the same __repr__ and __str__.""" 8 | 9 | def __repr__(self): 10 | return self.__str__() 11 | 12 | 13 | def evaluate_string(string): 14 | """Piggyback on Python's string support so we can have backslash escaping 15 | and niceties like \n, \t, etc. string.decode('string_escape') would have 16 | been a lower-level possibility. 17 | 18 | """ 19 | return ast.literal_eval(string) 20 | 21 | 22 | class Token(StrAndRepr): 23 | """A class to represent tokens, for use with TokenGrammars 24 | 25 | You will likely want to subclass this to hold additional information, like 26 | the characters that you lexed to create this token. Alternately, feel free 27 | to create your own class from scratch. The only contract is that tokens 28 | must have a ``type`` attr. 29 | 30 | """ 31 | __slots__ = ['type'] 32 | 33 | def __init__(self, type): 34 | self.type = type 35 | 36 | def __str__(self): 37 | return u'' % (self.type,) 38 | 39 | def __eq__(self, other): 40 | return self.type == other.type 41 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/starknet/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/abi/v0/__init__.py: -------------------------------------------------------------------------------- 1 | from .model import Abi 2 | from .parser import AbiParser, AbiParsingError 3 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/abi/v0/model.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from dataclasses import dataclass 4 | from typing import Dict, Optional, OrderedDict 5 | 6 | from ...cairo.data_types import CairoType, StructType 7 | 8 | 9 | @dataclass 10 | class Abi: 11 | """ 12 | Dataclass representing class abi. Contains parsed functions, events and structures. 13 | """ 14 | 15 | @dataclass 16 | class Function: 17 | """ 18 | Dataclass representing function's abi. 19 | """ 20 | 21 | name: str 22 | inputs: OrderedDict[str, CairoType] 23 | outputs: OrderedDict[str, CairoType] 24 | 25 | @dataclass 26 | class Event: 27 | """ 28 | Dataclass representing event's abi. 29 | """ 30 | 31 | name: str 32 | data: OrderedDict[str, CairoType] 33 | 34 | defined_structures: Dict[ 35 | str, StructType 36 | ] #: Abi of structures defined by the class. 37 | functions: Dict[str, Function] #: Functions defined by the class. 38 | constructor: Optional[ 39 | Function 40 | ] #: Contract's constructor. It is None if class doesn't define one. 41 | l1_handler: Optional[ 42 | Function 43 | ] #: Handler of L1 messages. It is None if class doesn't define one. 44 | events: Dict[str, Event] #: Events defined by the class 45 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/abi/v0/schemas.py: -------------------------------------------------------------------------------- 1 | from ....marshmallow import Schema, fields 2 | from ....marshmallow_oneofschema import OneOfSchema 3 | 4 | from .shape import ( 5 | CONSTRUCTOR_ENTRY, 6 | EVENT_ENTRY, 7 | FUNCTION_ENTRY, 8 | L1_HANDLER_ENTRY, 9 | STRUCT_ENTRY, 10 | ) 11 | 12 | 13 | class TypedParameterSchema(Schema): 14 | name = fields.String(data_key="name", required=True) 15 | type = fields.String(data_key="type", required=True) 16 | 17 | 18 | class StructMemberSchema(TypedParameterSchema): 19 | offset = fields.Integer(data_key="offset", required=False) 20 | 21 | 22 | class FunctionBaseSchema(Schema): 23 | name = fields.String(data_key="name", required=True) 24 | inputs = fields.List( 25 | fields.Nested(TypedParameterSchema()), data_key="inputs", required=True 26 | ) 27 | outputs = fields.List( 28 | fields.Nested(TypedParameterSchema()), data_key="outputs", required=True 29 | ) 30 | 31 | 32 | class FunctionAbiEntrySchema(FunctionBaseSchema): 33 | type = fields.Constant(FUNCTION_ENTRY, data_key="type", required=True) 34 | 35 | 36 | class ConstructorAbiEntrySchema(FunctionBaseSchema): 37 | type = fields.Constant(CONSTRUCTOR_ENTRY, data_key="type", required=True) 38 | 39 | 40 | class L1HandlerAbiEntrySchema(FunctionBaseSchema): 41 | type = fields.Constant(L1_HANDLER_ENTRY, data_key="type", required=True) 42 | 43 | 44 | class EventAbiEntrySchema(Schema): 45 | type = fields.Constant(EVENT_ENTRY, data_key="type", required=True) 46 | name = fields.String(data_key="name", required=True) 47 | keys = fields.List( 48 | fields.Nested(TypedParameterSchema()), data_key="keys", required=True 49 | ) 50 | data = fields.List( 51 | fields.Nested(TypedParameterSchema()), data_key="data", required=True 52 | ) 53 | 54 | 55 | class StructAbiEntrySchema(Schema): 56 | type = fields.Constant(STRUCT_ENTRY, data_key="type", required=True) 57 | name = fields.String(data_key="name", required=True) 58 | size = fields.Integer(data_key="size", required=True) 59 | members = fields.List( 60 | fields.Nested(StructMemberSchema()), data_key="members", required=True 61 | ) 62 | 63 | 64 | class ContractAbiEntrySchema(OneOfSchema): 65 | type_field_remove = False 66 | type_schemas = { 67 | FUNCTION_ENTRY: FunctionAbiEntrySchema, 68 | L1_HANDLER_ENTRY: L1HandlerAbiEntrySchema, 69 | CONSTRUCTOR_ENTRY: ConstructorAbiEntrySchema, 70 | EVENT_ENTRY: EventAbiEntrySchema, 71 | STRUCT_ENTRY: StructAbiEntrySchema, 72 | } 73 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/abi/v0/shape.py: -------------------------------------------------------------------------------- 1 | # TODO (#1260): update pylint to 3.1.0 and remove pylint disable 2 | # pylint: disable=too-many-ancestors 3 | import sys 4 | from typing import List, Literal, Union 5 | 6 | if sys.version_info < (3, 11): 7 | from typing_extensions import NotRequired, TypedDict 8 | else: 9 | from typing import NotRequired, TypedDict 10 | 11 | STRUCT_ENTRY = "struct" 12 | FUNCTION_ENTRY = "function" 13 | CONSTRUCTOR_ENTRY = "constructor" 14 | L1_HANDLER_ENTRY = "l1_handler" 15 | EVENT_ENTRY = "event" 16 | 17 | 18 | class TypedMemberDict(TypedDict): 19 | name: str 20 | type: str 21 | 22 | 23 | class StructMemberDict(TypedMemberDict): 24 | offset: NotRequired[int] 25 | 26 | 27 | class StructDict(TypedDict): 28 | type: Literal["struct"] 29 | name: str 30 | size: int 31 | members: List[StructMemberDict] 32 | 33 | 34 | class FunctionBaseDict(TypedDict): 35 | name: str 36 | inputs: List[TypedMemberDict] 37 | outputs: List[TypedMemberDict] 38 | stateMutability: NotRequired[Literal["view"]] 39 | 40 | 41 | class FunctionDict(FunctionBaseDict): 42 | type: Literal["function"] 43 | 44 | 45 | class ConstructorDict(FunctionBaseDict): 46 | type: Literal["constructor"] 47 | 48 | 49 | class L1HandlerDict(FunctionBaseDict): 50 | type: Literal["l1_handler"] 51 | 52 | 53 | class EventDict(TypedDict): 54 | name: str 55 | type: Literal["event"] 56 | data: List[TypedMemberDict] 57 | keys: List[TypedMemberDict] 58 | 59 | 60 | AbiDictEntry = Union[ 61 | StructDict, FunctionDict, ConstructorDict, L1HandlerDict, EventDict 62 | ] 63 | AbiDictList = List[AbiDictEntry] 64 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/abi/v1/__init__.py: -------------------------------------------------------------------------------- 1 | from .model import Abi 2 | from .parser import AbiParser, AbiParsingError 3 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/abi/v1/core_structures.json: -------------------------------------------------------------------------------- 1 | { 2 | "abi": [ 3 | { 4 | "type": "struct", 5 | "name": "core::starknet::eth_address::EthAddress", 6 | "members": [ 7 | { 8 | "name": "address", 9 | "type": "core::felt252" 10 | } 11 | ] 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/abi/v1/model.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from dataclasses import dataclass 4 | from typing import Dict, List, OrderedDict 5 | 6 | from ...cairo.data_types import CairoType, EnumType, StructType 7 | 8 | 9 | @dataclass 10 | class Abi: 11 | """ 12 | Dataclass representing class abi. Contains parsed functions, enums, events and structures. 13 | """ 14 | 15 | @dataclass 16 | class Function: 17 | """ 18 | Dataclass representing function's abi. 19 | """ 20 | 21 | name: str 22 | inputs: OrderedDict[str, CairoType] 23 | outputs: List[CairoType] 24 | 25 | @dataclass 26 | class Event: 27 | """ 28 | Dataclass representing event's abi. 29 | """ 30 | 31 | name: str 32 | inputs: OrderedDict[str, CairoType] 33 | 34 | defined_structures: Dict[ 35 | str, StructType 36 | ] #: Abi of structures defined by the class. 37 | defined_enums: Dict[str, EnumType] #: Abi of enums defined by the class. 38 | functions: Dict[str, Function] #: Functions defined by the class. 39 | events: Dict[str, Event] #: Events defined by the class 40 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/abi/v1/schemas.py: -------------------------------------------------------------------------------- 1 | from ....marshmallow import Schema, fields 2 | from ....marshmallow_oneofschema import OneOfSchema 3 | 4 | from .shape import ( 5 | ENUM_ENTRY, 6 | EVENT_ENTRY, 7 | FUNCTION_ENTRY, 8 | STRUCT_ENTRY, 9 | ) 10 | 11 | 12 | class TypeSchema(Schema): 13 | type = fields.String(data_key="type", required=True) 14 | 15 | 16 | class TypedParameterSchema(TypeSchema): 17 | name = fields.String(data_key="name", required=True) 18 | 19 | 20 | class FunctionBaseSchema(Schema): 21 | name = fields.String(data_key="name", required=True) 22 | inputs = fields.List( 23 | fields.Nested(TypedParameterSchema()), data_key="inputs", required=True 24 | ) 25 | outputs = fields.List( 26 | fields.Nested(TypeSchema()), data_key="outputs", required=True 27 | ) 28 | state_mutability = fields.String(data_key="state_mutability", default=None) 29 | 30 | 31 | class FunctionAbiEntrySchema(FunctionBaseSchema): 32 | type = fields.Constant(FUNCTION_ENTRY, data_key="type", required=True) 33 | 34 | 35 | class EventAbiEntrySchema(Schema): 36 | type = fields.Constant(EVENT_ENTRY, data_key="type", required=True) 37 | name = fields.String(data_key="name", required=True) 38 | inputs = fields.List( 39 | fields.Nested(TypedParameterSchema()), data_key="inputs", required=True 40 | ) 41 | 42 | 43 | class StructAbiEntrySchema(Schema): 44 | type = fields.Constant(STRUCT_ENTRY, data_key="type", required=True) 45 | name = fields.String(data_key="name", required=True) 46 | members = fields.List( 47 | fields.Nested(TypedParameterSchema()), data_key="members", required=True 48 | ) 49 | 50 | 51 | class EnumAbiEntrySchema(Schema): 52 | type = fields.Constant(ENUM_ENTRY, data_key="type", required=True) 53 | name = fields.String(data_key="name", required=True) 54 | variants = fields.List( 55 | fields.Nested(TypedParameterSchema(), data_key="variants", required=True) 56 | ) 57 | 58 | 59 | class ContractAbiEntrySchema(OneOfSchema): 60 | type_field_remove = False 61 | type_schemas = { 62 | FUNCTION_ENTRY: FunctionAbiEntrySchema, 63 | EVENT_ENTRY: EventAbiEntrySchema, 64 | STRUCT_ENTRY: StructAbiEntrySchema, 65 | ENUM_ENTRY: EnumAbiEntrySchema, 66 | } 67 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/abi/v1/shape.py: -------------------------------------------------------------------------------- 1 | from typing import List, Literal, Optional, TypedDict, Union 2 | 3 | ENUM_ENTRY = "enum" 4 | STRUCT_ENTRY = "struct" 5 | FUNCTION_ENTRY = "function" 6 | EVENT_ENTRY = "event" 7 | 8 | 9 | class TypeDict(TypedDict): 10 | type: str 11 | 12 | 13 | class TypedParameterDict(TypeDict): 14 | name: str 15 | 16 | 17 | class StructDict(TypedDict): 18 | type: Literal["struct"] 19 | name: str 20 | members: List[TypedParameterDict] 21 | 22 | 23 | class FunctionBaseDict(TypedDict): 24 | name: str 25 | inputs: List[TypedParameterDict] 26 | outputs: List[TypeDict] 27 | state_mutability: Optional[Literal["external", "view"]] 28 | 29 | 30 | class FunctionDict(FunctionBaseDict): 31 | type: Literal["function"] 32 | 33 | 34 | class EventDict(TypedDict): 35 | name: str 36 | type: Literal["event"] 37 | inputs: List[TypedParameterDict] 38 | 39 | 40 | class EnumDict(TypedDict): 41 | type: Literal["enum"] 42 | name: str 43 | variants: List[TypedParameterDict] 44 | 45 | 46 | AbiDictEntry = Union[StructDict, FunctionDict, EventDict, EnumDict] 47 | AbiDictList = List[AbiDictEntry] 48 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/abi/v2/__init__.py: -------------------------------------------------------------------------------- 1 | from .model import Abi 2 | from .parser import AbiParser, AbiParsingError 3 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/abi/v2/model.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from dataclasses import dataclass 4 | from typing import Dict, List, Optional, OrderedDict, Union 5 | 6 | from ...cairo.data_types import CairoType, EnumType, EventType, StructType 7 | 8 | 9 | @dataclass 10 | class Abi: 11 | """ 12 | Dataclass representing class abi. Contains parsed functions, enums, events and structures. 13 | """ 14 | 15 | # pylint: disable=too-many-instance-attributes 16 | 17 | @dataclass 18 | class Function: 19 | """ 20 | Dataclass representing function's abi. 21 | """ 22 | 23 | name: str 24 | inputs: OrderedDict[str, CairoType] 25 | outputs: List[CairoType] 26 | 27 | @dataclass 28 | class Constructor: 29 | """ 30 | Dataclass representing constructor's abi. 31 | """ 32 | 33 | name: str 34 | inputs: OrderedDict[str, CairoType] 35 | 36 | @dataclass 37 | class EventStruct: 38 | """ 39 | Dataclass representing struct event's abi. 40 | """ 41 | 42 | name: str 43 | members: OrderedDict[str, CairoType] 44 | 45 | @dataclass 46 | class EventEnum: 47 | """ 48 | Dataclass representing enum event's abi. 49 | """ 50 | 51 | name: str 52 | variants: OrderedDict[str, CairoType] 53 | 54 | Event = Union[EventStruct, EventEnum] 55 | 56 | @dataclass 57 | class Interface: 58 | """ 59 | Dataclass representing an interface. 60 | """ 61 | 62 | name: str 63 | items: OrderedDict[ 64 | str, Abi.Function 65 | ] # Only functions can be defined in the interface 66 | 67 | @dataclass 68 | class Impl: 69 | """ 70 | Dataclass representing an impl. 71 | """ 72 | 73 | name: str 74 | interface_name: str 75 | 76 | defined_structures: Dict[ 77 | str, StructType 78 | ] #: Abi of structures defined by the class. 79 | defined_enums: Dict[str, EnumType] #: Abi of enums defined by the class. 80 | functions: Dict[str, Function] #: Functions defined by the class. 81 | events: Dict[str, EventType] #: Events defined by the class 82 | constructor: Optional[ 83 | Constructor 84 | ] #: Contract's constructor. It is None if class doesn't define one. 85 | l1_handler: Optional[ 86 | Dict[str, Function] 87 | ] #: Handlers of L1 messages. It is None if class doesn't define one. 88 | interfaces: Dict[str, Interface] 89 | implementations: Dict[str, Impl] 90 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/abi/v2/shape.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from typing import List, Literal, Optional, TypedDict, Union 4 | 5 | STRUCT_ENTRY = "struct" 6 | EVENT_ENTRY = "event" 7 | FUNCTION_ENTRY = "function" 8 | ENUM_ENTRY = "enum" 9 | CONSTRUCTOR_ENTRY = "constructor" 10 | L1_HANDLER_ENTRY = "l1_handler" 11 | IMPL_ENTRY = "impl" 12 | INTERFACE_ENTRY = "interface" 13 | 14 | DATA_KIND = "data" 15 | NESTED_KIND = "nested" 16 | 17 | 18 | class TypeDict(TypedDict): 19 | type: str 20 | 21 | 22 | class TypedParameterDict(TypeDict): 23 | name: str 24 | 25 | 26 | class StructDict(TypedDict): 27 | type: Literal["struct"] 28 | name: str 29 | members: List[TypedParameterDict] 30 | 31 | 32 | class FunctionBaseDict(TypedDict): 33 | name: str 34 | inputs: List[TypedParameterDict] 35 | outputs: List[TypeDict] 36 | state_mutability: Optional[Literal["external", "view"]] 37 | 38 | 39 | class FunctionDict(FunctionBaseDict): 40 | type: Literal["function"] 41 | 42 | 43 | class ConstructorDict(TypedDict): 44 | type: Literal["constructor"] 45 | name: str 46 | inputs: List[TypedParameterDict] 47 | 48 | 49 | class L1HandlerDict(FunctionBaseDict): 50 | type: Literal["l1_handler"] 51 | 52 | 53 | class EventBaseDict(TypedDict): 54 | type: Literal["event"] 55 | name: str 56 | 57 | 58 | class EventStructMemberDict(TypedParameterDict): 59 | kind: Literal["data"] 60 | 61 | 62 | class EventStructDict(EventBaseDict): 63 | kind: Literal["struct"] 64 | members: List[EventStructMemberDict] 65 | 66 | 67 | class EventEnumVariantDict(TypedParameterDict): 68 | kind: Literal["nested"] 69 | 70 | 71 | class EventEnumDict(EventBaseDict): 72 | kind: Literal["enum"] 73 | variants: List[EventEnumVariantDict] 74 | 75 | 76 | EventDict = Union[EventStructDict, EventEnumDict] 77 | 78 | 79 | class EnumDict(TypedDict): 80 | type: Literal["enum"] 81 | name: str 82 | variants: List[TypedParameterDict] 83 | 84 | 85 | class ImplDict(TypedDict): 86 | type: Literal["impl"] 87 | name: str 88 | interface_name: str 89 | 90 | 91 | class InterfaceDict(TypedDict): 92 | type: Literal["interface"] 93 | name: str 94 | items: List[FunctionDict] # for now only functions can be defined here 95 | 96 | 97 | AbiDictEntry = Union[ 98 | StructDict, 99 | FunctionDict, 100 | EventDict, 101 | EnumDict, 102 | ConstructorDict, 103 | L1HandlerDict, 104 | ImplDict, 105 | InterfaceDict, 106 | ] 107 | AbiDictList = List[AbiDictEntry] 108 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/cairo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/starknet/cairo/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/cairo/data_types.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from abc import ABC 4 | from collections import OrderedDict 5 | from dataclasses import dataclass 6 | from typing import List 7 | 8 | 9 | class CairoType(ABC): 10 | """ 11 | Base type for all Cairo type representations. All types extend it. 12 | """ 13 | 14 | 15 | @dataclass 16 | class FeltType(CairoType): 17 | """ 18 | Type representation of Cairo field element. 19 | """ 20 | 21 | 22 | @dataclass 23 | class BoolType(CairoType): 24 | """ 25 | Type representation of Cairo boolean. 26 | """ 27 | 28 | 29 | @dataclass 30 | class TupleType(CairoType): 31 | """ 32 | Type representation of Cairo tuples without named fields. 33 | """ 34 | 35 | types: List[CairoType] #: types of every tuple element. 36 | 37 | 38 | @dataclass 39 | class NamedTupleType(CairoType): 40 | """ 41 | Type representation of Cairo tuples with named fields. 42 | """ 43 | 44 | types: OrderedDict[str, CairoType] #: types of every tuple member. 45 | 46 | 47 | @dataclass 48 | class ArrayType(CairoType): 49 | """ 50 | Type representation of Cairo arrays. 51 | """ 52 | 53 | inner_type: CairoType #: type of element inside array. 54 | 55 | 56 | @dataclass 57 | class StructType(CairoType): 58 | """ 59 | Type representation of Cairo structures. 60 | """ 61 | 62 | name: str #: Structure name 63 | # We need ordered dict, because it is important in serialization 64 | types: OrderedDict[str, CairoType] #: types of every structure member. 65 | 66 | 67 | @dataclass 68 | class EnumType(CairoType): 69 | """ 70 | Type representation of Cairo enums. 71 | """ 72 | 73 | name: str 74 | variants: OrderedDict[str, CairoType] 75 | 76 | 77 | @dataclass 78 | class OptionType(CairoType): 79 | """ 80 | Type representation of Cairo options. 81 | """ 82 | 83 | type: CairoType 84 | 85 | 86 | @dataclass 87 | class UintType(CairoType): 88 | """ 89 | Type representation of Cairo unsigned integers. 90 | """ 91 | 92 | bits: int 93 | 94 | def check_range(self, value: int): 95 | """ 96 | Utility method checking if the `value` is in range. 97 | """ 98 | 99 | 100 | @dataclass 101 | class TypeIdentifier(CairoType): 102 | """ 103 | Type representation of Cairo identifiers. 104 | """ 105 | 106 | name: str 107 | 108 | 109 | @dataclass 110 | class UnitType(CairoType): 111 | """ 112 | Type representation of Cairo unit `()`. 113 | """ 114 | 115 | 116 | @dataclass 117 | class EventType(CairoType): 118 | """ 119 | Type representation of Cairo Event. 120 | """ 121 | 122 | name: str 123 | types: OrderedDict[str, CairoType] 124 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/cairo/deprecated_parse/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/starknet/cairo/deprecated_parse/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/cairo/deprecated_parse/cairo_types.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | from typing import List, Optional 3 | 4 | 5 | class CairoType: 6 | """ 7 | Base class for cairo types. 8 | """ 9 | 10 | 11 | @dataclasses.dataclass 12 | class TypeFelt(CairoType): 13 | pass 14 | 15 | 16 | @dataclasses.dataclass 17 | class TypeCodeoffset(CairoType): 18 | pass 19 | 20 | 21 | @dataclasses.dataclass 22 | class TypePointer(CairoType): 23 | pointee: CairoType 24 | 25 | 26 | @dataclasses.dataclass 27 | class TypeIdentifier(CairoType): 28 | """ 29 | Represents a name of an unresolved type. 30 | This type can be resolved to TypeStruct or TypeDefinition. 31 | """ 32 | 33 | name: str 34 | 35 | 36 | @dataclasses.dataclass 37 | class TypeStruct(CairoType): 38 | scope: str 39 | 40 | 41 | @dataclasses.dataclass 42 | class TypeFunction(CairoType): 43 | """ 44 | Represents a type of a function. 45 | """ 46 | 47 | scope: str 48 | 49 | 50 | @dataclasses.dataclass 51 | class TypeTuple(CairoType): 52 | """ 53 | Represents a type of a named or unnamed tuple. 54 | For example, "(felt, felt*)" or "(a: felt, b: felt*)". 55 | """ 56 | 57 | @dataclasses.dataclass 58 | class Item(CairoType): 59 | """ 60 | Represents a possibly named type item of a TypeTuple. 61 | For example: "felt" or "a: felt". 62 | """ 63 | 64 | name: Optional[str] 65 | typ: CairoType 66 | 67 | members: List["TypeTuple.Item"] 68 | has_trailing_comma: bool = dataclasses.field(hash=False, compare=False) 69 | 70 | @property 71 | def is_named(self) -> bool: 72 | return all(member.name is not None for member in self.members) 73 | 74 | 75 | @dataclasses.dataclass 76 | class ExprIdentifier(CairoType): 77 | name: str 78 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/cairo/deprecated_parse/parser.py: -------------------------------------------------------------------------------- 1 | from ....lark import Lark 2 | 3 | from .cairo_types import CairoType 4 | from .parser_transformer import ParserTransformer 5 | 6 | CAIRO_EBNF = """ 7 | %import common.WS_INLINE 8 | %ignore WS_INLINE 9 | 10 | IDENTIFIER: /[a-zA-Z_][a-zA-Z_0-9]*/ 11 | _DBL_STAR: "**" 12 | COMMA: "," 13 | 14 | ?type: non_identifier_type 15 | | identifier -> type_struct 16 | 17 | comma_separated{item}: item? (COMMA item)* COMMA? 18 | 19 | named_type: identifier (":" type)? | non_identifier_type 20 | non_identifier_type: "felt" -> type_felt 21 | | "codeoffset" -> type_codeoffset 22 | | type "*" -> type_pointer 23 | | type _DBL_STAR -> type_pointer2 24 | | "(" comma_separated{named_type} ")" -> type_tuple 25 | 26 | identifier: IDENTIFIER ("." IDENTIFIER)* 27 | """ 28 | 29 | 30 | def parse(code: str) -> CairoType: 31 | """ 32 | Parses the given string and returns a CairoType. 33 | """ 34 | 35 | grammar = CAIRO_EBNF 36 | 37 | grammar_parser = Lark( 38 | grammar=grammar, 39 | start=["type"], 40 | parser="lalr", 41 | ) 42 | 43 | parsed = grammar_parser.parse(code) 44 | transformed = ParserTransformer().transform(parsed) 45 | 46 | return transformed 47 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/cairo/felt.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | from ..constants import FIELD_PRIME 4 | 5 | CairoData = List[int] 6 | 7 | 8 | MAX_UINT256 = (1 << 256) - 1 9 | MIN_UINT256 = 0 10 | 11 | 12 | def uint256_range_check(value: int): 13 | if not MIN_UINT256 <= value <= MAX_UINT256: 14 | raise ValueError( 15 | f"Uint256 is expected to be in range [0;2**256), got: {value}." 16 | ) 17 | 18 | 19 | MIN_FELT = -FIELD_PRIME // 2 20 | MAX_FELT = FIELD_PRIME // 2 21 | 22 | 23 | def is_in_felt_range(value: int) -> bool: 24 | return 0 <= value < FIELD_PRIME 25 | 26 | 27 | def cairo_vm_range_check(value: int): 28 | if not is_in_felt_range(value): 29 | raise ValueError( 30 | f"Felt is expected to be in range [0; {FIELD_PRIME}), got: {value}." 31 | ) 32 | 33 | 34 | def encode_shortstring(text: str) -> int: 35 | """ 36 | A function which encodes short string value (at most 31 characters) into cairo felt (MSB as first character) 37 | 38 | :param text: A short string value in python 39 | :return: Short string value encoded into felt 40 | """ 41 | if len(text) > 31: 42 | raise ValueError( 43 | f"Shortstring cannot be longer than 31 characters, got: {len(text)}." 44 | ) 45 | 46 | try: 47 | text_bytes = text.encode("ascii") 48 | except UnicodeEncodeError as u_err: 49 | raise ValueError(f"Expected an ascii string. Found: {repr(text)}.") from u_err 50 | value = int.from_bytes(text_bytes, "big") 51 | 52 | cairo_vm_range_check(value) 53 | return value 54 | 55 | 56 | def decode_shortstring(value: int) -> str: 57 | """ 58 | A function which decodes a felt value to short string (at most 31 characters) 59 | 60 | :param value: A felt value 61 | :return: Decoded string which is corresponds to that felt 62 | """ 63 | cairo_vm_range_check(value) 64 | return "".join([chr(i) for i in value.to_bytes(31, byteorder="big")]).lstrip("\x00") 65 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/cairo/v1/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/starknet/cairo/v1/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/cairo/v1/type_parser.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from typing import Dict, Union 4 | 5 | from ...abi.v1.parser_transformer import parse 6 | from ..data_types import CairoType, EnumType, StructType, TypeIdentifier 7 | 8 | 9 | class UnknownCairoTypeError(ValueError): 10 | """ 11 | Error thrown when TypeParser finds type that was not declared prior to parsing. 12 | """ 13 | 14 | type_name: str 15 | 16 | def __init__(self, type_name: str): 17 | super().__init__( 18 | # pylint: disable=line-too-long 19 | f"Type '{type_name}' is not defined. Please report this issue at https://github.com/software-mansion/starknet.py/issues" 20 | ) 21 | self.type_name = type_name 22 | 23 | 24 | class TypeParser: 25 | """ 26 | Low level utility class for parsing Cairo types that can be used in external methods. 27 | """ 28 | 29 | defined_types: Dict[str, Union[StructType, EnumType]] 30 | 31 | def __init__(self, defined_types: Dict[str, Union[StructType, EnumType]]): 32 | """ 33 | TypeParser constructor. 34 | 35 | :param defined_types: dictionary containing all defined types. For now, they can only be structures. 36 | """ 37 | self.defined_types = defined_types 38 | for name, defined_type in defined_types.items(): 39 | if name != defined_type.name: 40 | raise ValueError( 41 | f"Keys must match name of type, '{name}' != '{defined_type.name}'." 42 | ) 43 | 44 | def parse_inline_type(self, type_string: str) -> CairoType: 45 | """ 46 | Inline type is one that can be used inline, for instance as return type. For instance 47 | (core::felt252, (), (core::felt252,)). Structure can only be referenced in inline type, can't be defined 48 | this way. 49 | 50 | :param type_string: type to parse. 51 | """ 52 | parsed = parse(type_string, self.defined_types) 53 | if isinstance(parsed, TypeIdentifier): 54 | for defined_name in self.defined_types.keys(): 55 | if parsed.name == defined_name.split("<")[0].strip(":"): 56 | return self.defined_types[defined_name] 57 | raise UnknownCairoTypeError(parsed.name) 58 | 59 | return parsed 60 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/cairo/v2/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/starknet/cairo/v2/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/cairo/v2/type_parser.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from typing import Dict, Union 4 | 5 | from ...abi.v2.parser_transformer import parse 6 | from ..data_types import ( 7 | CairoType, 8 | EnumType, 9 | EventType, 10 | StructType, 11 | TypeIdentifier, 12 | ) 13 | 14 | 15 | class UnknownCairoTypeError(ValueError): 16 | """ 17 | Error thrown when TypeParser finds type that was not declared prior to parsing. 18 | """ 19 | 20 | type_name: str 21 | 22 | def __init__(self, type_name: str): 23 | super().__init__( 24 | # pylint: disable=line-too-long 25 | f"Type '{type_name}' is not defined. Please report this issue at https://github.com/software-mansion/starknet.py/issues" 26 | ) 27 | self.type_name = type_name 28 | 29 | 30 | class TypeParser: 31 | """ 32 | Low level utility class for parsing Cairo types that can be used in external methods. 33 | """ 34 | 35 | defined_types: Dict[str, Union[StructType, EnumType, EventType]] 36 | 37 | def __init__( 38 | self, defined_types: Dict[str, Union[StructType, EnumType, EventType]] 39 | ): 40 | """ 41 | TypeParser constructor. 42 | 43 | :param defined_types: dictionary containing all defined types. For now, they can only be structures. 44 | """ 45 | self.defined_types = defined_types 46 | for name, defined_type in defined_types.items(): 47 | if name != defined_type.name: 48 | raise ValueError( 49 | f"Keys must match name of type, '{name}' != '{defined_type.name}'." 50 | ) 51 | 52 | def update_defined_types( 53 | self, defined_types: Dict[str, Union[StructType, EnumType, EventType]] 54 | ) -> None: 55 | self.defined_types.update(defined_types) 56 | 57 | def add_defined_type( 58 | self, defined_type: Union[StructType, EnumType, EventType] 59 | ) -> None: 60 | self.defined_types.update({defined_type.name: defined_type}) 61 | 62 | def parse_inline_type(self, type_string: str) -> CairoType: 63 | """ 64 | Inline type is one that can be used inline, for instance as return type. For instance 65 | (core::felt252, (), (core::felt252,)). Structure can only be referenced in inline type, can't be defined 66 | this way. 67 | 68 | :param type_string: type to parse. 69 | """ 70 | parsed = parse(type_string, self.defined_types) 71 | if isinstance(parsed, TypeIdentifier): 72 | for defined_name in self.defined_types.keys(): 73 | if parsed.name == defined_name.split("<")[0].strip(":"): 74 | return self.defined_types[defined_name] 75 | raise UnknownCairoTypeError(parsed.name) 76 | 77 | return parsed 78 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/ccxt_utils.py: -------------------------------------------------------------------------------- 1 | # utils to use starknet library in ccxt 2 | from .constants import EC_ORDER 3 | from ..starkware.crypto.signature import grind_key 4 | 5 | def get_private_key_from_eth_signature(eth_signature_hex: str) -> int: 6 | r = eth_signature_hex[2 : 64 + 2] if eth_signature_hex[0:2] == '0x' else eth_signature_hex[0 : 64] 7 | return grind_key(int(r, 16), EC_ORDER) -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/common.py: -------------------------------------------------------------------------------- 1 | from typing import Literal, Union 2 | 3 | def int_from_hex(number: Union[str, int]) -> int: 4 | return number if isinstance(number, int) else int(number, 16) 5 | 6 | 7 | def int_from_bytes( 8 | value: bytes, 9 | byte_order: Literal["big", "little"] = "big", 10 | signed: bool = False, 11 | ) -> int: 12 | """ 13 | Converts the given bytes object (parsed according to the given byte order) to an integer. 14 | """ 15 | return int.from_bytes(value, byteorder=byte_order, signed=signed) 16 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/constants.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | 3 | # Address came from starkware-libs/starknet-addresses repository: https://github.com/starkware-libs/starknet-addresses 4 | FEE_CONTRACT_ADDRESS = ( 5 | "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7" 6 | ) 7 | 8 | DEFAULT_DEPLOYER_ADDRESS = ( 9 | "0x041a78e741e5aF2fEc34B695679bC6891742439f7AFB8484Ecd7766661aD02BF" 10 | ) 11 | 12 | API_VERSION = 0 13 | 14 | RPC_CONTRACT_NOT_FOUND_ERROR = 20 15 | RPC_INVALID_MESSAGE_SELECTOR_ERROR = 21 16 | RPC_CLASS_HASH_NOT_FOUND_ERROR = 28 17 | RPC_CONTRACT_ERROR = 40 18 | 19 | DEFAULT_ENTRY_POINT_NAME = "__default__" 20 | DEFAULT_L1_ENTRY_POINT_NAME = "__l1_default__" 21 | DEFAULT_ENTRY_POINT_SELECTOR = 0 22 | DEFAULT_DECLARE_SENDER_ADDRESS = 1 23 | 24 | # MAX_STORAGE_ITEM_SIZE and ADDR_BOUND must be consistent with the corresponding constant in 25 | # starkware/starknet/common/storage.cairo. 26 | MAX_STORAGE_ITEM_SIZE = 256 27 | ADDR_BOUND = 2**251 - MAX_STORAGE_ITEM_SIZE 28 | 29 | FIELD_PRIME = 0x800000000000011000000000000000000000000000000000000000000000001 30 | EC_ORDER = 0x800000000000010FFFFFFFFFFFFFFFFB781126DCAE7B2321E66A241ADC64D2F 31 | 32 | # From cairo-lang 33 | # int_from_bytes(b"STARKNET_CONTRACT_ADDRESS") 34 | CONTRACT_ADDRESS_PREFIX = 523065374597054866729014270389667305596563390979550329787219 35 | L2_ADDRESS_UPPER_BOUND = 2**251 - 256 36 | 37 | QUERY_VERSION_BASE = 2**128 38 | 39 | ROOT_PATH = Path(__file__).parent 40 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/hash/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/starknet/hash/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/hash/address.py: -------------------------------------------------------------------------------- 1 | from typing import Sequence 2 | 3 | from ..constants import CONTRACT_ADDRESS_PREFIX, L2_ADDRESS_UPPER_BOUND 4 | from .utils import ( 5 | HEX_PREFIX, 6 | _starknet_keccak, 7 | compute_hash_on_elements, 8 | encode_uint, 9 | get_bytes_length, 10 | ) 11 | 12 | 13 | def compute_address( 14 | *, 15 | class_hash: int, 16 | constructor_calldata: Sequence[int], 17 | salt: int, 18 | deployer_address: int = 0, 19 | ) -> int: 20 | """ 21 | Computes the contract address in the Starknet network - a unique identifier of the contract. 22 | 23 | :param class_hash: class hash of the contract 24 | :param constructor_calldata: calldata for the contract constructor 25 | :param salt: salt used to calculate contract address 26 | :param deployer_address: address of the deployer (if not provided default 0 is used) 27 | :return: Contract's address 28 | """ 29 | 30 | constructor_calldata_hash = compute_hash_on_elements(data=constructor_calldata) 31 | raw_address = compute_hash_on_elements( 32 | data=[ 33 | CONTRACT_ADDRESS_PREFIX, 34 | deployer_address, 35 | salt, 36 | class_hash, 37 | constructor_calldata_hash, 38 | ], 39 | ) 40 | 41 | return raw_address % L2_ADDRESS_UPPER_BOUND 42 | 43 | 44 | def get_checksum_address(address: str) -> str: 45 | """ 46 | Outputs formatted checksum address. 47 | 48 | Follows implementation of starknet.js. It is not compatible with EIP55 as it treats hex string as encoded number, 49 | instead of encoding it as ASCII string. 50 | 51 | :param address: Address to encode 52 | :return: Checksum address 53 | """ 54 | if not address.lower().startswith(HEX_PREFIX): 55 | raise ValueError(f"{address} is not a valid hexadecimal address.") 56 | 57 | int_address = int(address, 16) 58 | string_address = address[2:].zfill(64) 59 | 60 | address_in_bytes = encode_uint(int_address, get_bytes_length(int_address)) 61 | address_hash = _starknet_keccak(address_in_bytes) 62 | 63 | result = "".join( 64 | ( 65 | char.upper() 66 | if char.isalpha() and (address_hash >> 256 - 4 * i - 1) & 1 67 | else char 68 | ) 69 | for i, char in enumerate(string_address) 70 | ) 71 | 72 | return f"{HEX_PREFIX}{result}" 73 | 74 | 75 | def is_checksum_address(address: str) -> bool: 76 | """ 77 | Checks if provided string is in a checksum address format. 78 | """ 79 | return get_checksum_address(address) == address 80 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/hash/selector.py: -------------------------------------------------------------------------------- 1 | from ..constants import ( 2 | DEFAULT_ENTRY_POINT_NAME, 3 | DEFAULT_ENTRY_POINT_SELECTOR, 4 | DEFAULT_L1_ENTRY_POINT_NAME, 5 | ) 6 | from ..hash.utils import _starknet_keccak 7 | 8 | 9 | def get_selector_from_name(func_name: str) -> int: 10 | """ 11 | Returns the selector of a contract's function name. 12 | """ 13 | if func_name in [DEFAULT_ENTRY_POINT_NAME, DEFAULT_L1_ENTRY_POINT_NAME]: 14 | return DEFAULT_ENTRY_POINT_SELECTOR 15 | 16 | return _starknet_keccak(data=func_name.encode("ascii")) 17 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/hash/storage.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | 3 | from constants import ADDR_BOUND 4 | from hash.utils import _starknet_keccak, pedersen_hash 5 | 6 | 7 | def get_storage_var_address(var_name: str, *args: int) -> int: 8 | """ 9 | Returns the storage address of a Starknet storage variable given its name and arguments. 10 | """ 11 | res = _starknet_keccak(var_name.encode("ascii")) 12 | return reduce(pedersen_hash, args, res) % ADDR_BOUND 13 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/hash/utils.py: -------------------------------------------------------------------------------- 1 | import functools 2 | from typing import List, Optional, Sequence 3 | 4 | from ... import keccak 5 | 6 | from ..common import int_from_bytes 7 | from ..constants import EC_ORDER 8 | from ...starkware.crypto.signature import ( 9 | ECSignature, 10 | private_to_stark_key, 11 | sign 12 | # verify 13 | ) 14 | from ...starkware.crypto.fast_pedersen_hash import ( 15 | pedersen_hash 16 | ) 17 | 18 | MASK_250 = 2**250 - 1 19 | HEX_PREFIX = "0x" 20 | 21 | 22 | def _starknet_keccak(data: bytes) -> int: 23 | """ 24 | A variant of eth-keccak that computes a value that fits in a Starknet field element. 25 | """ 26 | return int_from_bytes(keccak.SHA3(data)) & MASK_250 27 | 28 | 29 | # def pedersen_hash(left: int, right: int) -> int: 30 | # """ 31 | # One of two hash functions (along with _starknet_keccak) used throughout Starknet. 32 | # """ 33 | # return cpp_hash(left, right) 34 | 35 | 36 | def compute_hash_on_elements(data: Sequence) -> int: 37 | """ 38 | Computes a hash chain over the data, in the following order: 39 | h(h(h(h(0, data[0]), data[1]), ...), data[n-1]), n). 40 | 41 | The hash is initialized with 0 and ends with the data length appended. 42 | The length is appended in order to avoid collisions of the following kind: 43 | H([x,y,z]) = h(h(x,y),z) = H([w, z]) where w = h(x,y). 44 | """ 45 | return functools.reduce(pedersen_hash, [*data, len(data)], 0) 46 | 47 | 48 | def message_signature( 49 | msg_hash: int, priv_key: int, seed: Optional[int] = 32 50 | ) -> ECSignature: 51 | """ 52 | Signs the message with private key. 53 | """ 54 | return sign(msg_hash, priv_key, seed) 55 | 56 | 57 | # def verify_message_signature( 58 | # msg_hash: int, signature: List[int], public_key: int 59 | # ) -> bool: 60 | # """ 61 | # Verifies ECDSA signature of a given message hash with a given public key. 62 | # Returns true if public_key signs the message. 63 | # """ 64 | # sig_r, sig_s = signature 65 | # # sig_w = pow(sig_s, -1, EC_ORDER) 66 | # return verify(msg_hash=msg_hash, r=sig_r, s=sig_s, public_key=public_key) 67 | 68 | 69 | def encode_uint(value: int, bytes_length: int = 32) -> bytes: 70 | return value.to_bytes(bytes_length, byteorder="big") 71 | 72 | 73 | def encode_uint_list(data: List[int]) -> bytes: 74 | return b"".join(encode_uint(x) for x in data) 75 | 76 | 77 | def get_bytes_length(value: int) -> int: 78 | return (value.bit_length() + 7) // 8 79 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/starknet/models/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/models/typed_data.py: -------------------------------------------------------------------------------- 1 | """ 2 | TypedDict structures for TypedData 3 | """ 4 | 5 | from enum import Enum 6 | from typing import Any, Dict, List, Optional, TypedDict 7 | 8 | class Revision(Enum): 9 | """ 10 | Enum representing the revision of the specification to be used. 11 | """ 12 | 13 | V0 = 0 14 | V1 = 1 15 | 16 | 17 | class ParameterDict(TypedDict): 18 | """ 19 | TypedDict representing a Parameter object 20 | """ 21 | 22 | name: str 23 | type: str 24 | 25 | 26 | class StarkNetDomainDict(TypedDict): 27 | """ 28 | TypedDict representing a domain object (both StarkNetDomain, StarknetDomain). 29 | """ 30 | 31 | name: str 32 | version: str 33 | chainId: str 34 | revision: Optional[Revision] 35 | 36 | 37 | class TypedDataDict(TypedDict): 38 | """ 39 | TypedDict representing a TypedData object 40 | """ 41 | 42 | types: Dict[str, List[ParameterDict]] 43 | primaryType: str 44 | domain: StarkNetDomainDict 45 | message: Dict[str, Any] 46 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/__init__.py: -------------------------------------------------------------------------------- 1 | # PayloadSerializer and FunctionSerializationAdapter would mostly be used by users 2 | from .data_serializers import ( 3 | ArraySerializer, 4 | CairoDataSerializer, 5 | FeltSerializer, 6 | NamedTupleSerializer, 7 | PayloadSerializer, 8 | StructSerializer, 9 | TupleSerializer, 10 | Uint256Serializer, 11 | ) 12 | from .errors import ( 13 | CairoSerializerException, 14 | InvalidTypeException, 15 | InvalidValueException, 16 | ) 17 | from .factory import ( 18 | serializer_for_event, 19 | serializer_for_function, 20 | serializer_for_payload, 21 | serializer_for_type, 22 | ) 23 | from .function_serialization_adapter import FunctionSerializationAdapter 24 | from .tuple_dataclass import TupleDataclass 25 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/_calldata_reader.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | from ..cairo.felt import CairoData 4 | 5 | 6 | class OutOfBoundsError(Exception): 7 | def __init__(self, position: int, requested_size: int, remaining_size: int): 8 | super().__init__( 9 | f"Requested {requested_size} elements, {remaining_size} available." 10 | ) 11 | self.position = position 12 | self.requested_size = requested_size 13 | self.remaining_len = remaining_size 14 | 15 | 16 | class CalldataReader: 17 | _data: List[int] 18 | _position: int 19 | 20 | def __init__(self, data: List[int]): 21 | self._data = data 22 | self._position = 0 23 | 24 | @property 25 | def remaining_len(self) -> int: 26 | return len(self._data) - self._position 27 | 28 | def read(self, size: int) -> CairoData: 29 | if size < 1: 30 | raise ValueError("size must be greater than 0") 31 | 32 | if size > self.remaining_len: 33 | raise OutOfBoundsError( 34 | position=self._position, 35 | requested_size=size, 36 | remaining_size=self.remaining_len, 37 | ) 38 | data = self._data[self._position : self._position + size] 39 | self._position += size 40 | return data 41 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/__init__.py: -------------------------------------------------------------------------------- 1 | from .array_serializer import ArraySerializer 2 | from .bool_serializer import BoolSerializer 3 | from .byte_array_serializer import ByteArraySerializer 4 | from .cairo_data_serializer import CairoDataSerializer 5 | from .felt_serializer import FeltSerializer 6 | from .named_tuple_serializer import NamedTupleSerializer 7 | from .payload_serializer import PayloadSerializer 8 | from .struct_serializer import StructSerializer 9 | from .tuple_serializer import TupleSerializer 10 | from .uint256_serializer import Uint256Serializer 11 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/_common.py: -------------------------------------------------------------------------------- 1 | # We have to use parametrised type from typing 2 | from collections import OrderedDict as _OrderedDict 3 | from typing import Dict, Generator, List, OrderedDict 4 | 5 | from .._context import ( 6 | DeserializationContext, 7 | SerializationContext, 8 | ) 9 | from .cairo_data_serializer import ( 10 | CairoDataSerializer, 11 | ) 12 | 13 | # The actual serialization logic is very similar among all serializers: they either serialize data based on 14 | # position or their name. Having this logic reused adds indirection, but makes sure proper logic is used everywhere. 15 | 16 | 17 | def deserialize_to_list( 18 | deserializers: List[CairoDataSerializer], context: DeserializationContext 19 | ) -> List: 20 | """ 21 | Deserializes data from context to list. This logic is used in every sequential type (arrays and tuples). 22 | """ 23 | result = [] 24 | 25 | for index, serializer in enumerate(deserializers): 26 | with context.push_entity(f"[{index}]"): 27 | result.append(serializer.deserialize_with_context(context)) 28 | 29 | return result 30 | 31 | 32 | def deserialize_to_dict( 33 | deserializers: OrderedDict[str, CairoDataSerializer], 34 | context: DeserializationContext, 35 | ) -> OrderedDict: 36 | """ 37 | Deserializes data from context to dictionary. This logic is used in every type with named fields (structs, 38 | named tuples and payloads). 39 | """ 40 | result = _OrderedDict() 41 | 42 | for key, serializer in deserializers.items(): 43 | with context.push_entity(key): 44 | result[key] = serializer.deserialize_with_context(context) 45 | 46 | return result 47 | 48 | 49 | def serialize_from_list( 50 | serializers: List[CairoDataSerializer], context: SerializationContext, values: List 51 | ) -> Generator[int, None, None]: 52 | """ 53 | Serializes data from list. This logic is used in every sequential type (arrays and tuples). 54 | """ 55 | context.ensure_valid_value( 56 | len(serializers) == len(values), 57 | f"expected {len(serializers)} elements, {len(values)} provided", 58 | ) 59 | 60 | for index, (serializer, value) in enumerate(zip(serializers, values)): 61 | with context.push_entity(f"[{index}]"): 62 | yield from serializer.serialize_with_context(context, value) 63 | 64 | 65 | def serialize_from_dict( 66 | serializers: OrderedDict[str, CairoDataSerializer], 67 | context: SerializationContext, 68 | values: Dict, 69 | ) -> Generator[int, None, None]: 70 | """ 71 | Serializes data from dict. This logic is used in every type with named fields (structs, named tuples and payloads). 72 | """ 73 | excessive_keys = set(values.keys()).difference(serializers.keys()) 74 | context.ensure_valid_value( 75 | not excessive_keys, 76 | f"unexpected keys '{','.join(excessive_keys)}' were provided", 77 | ) 78 | 79 | for name, serializer in serializers.items(): 80 | with context.push_entity(name): 81 | context.ensure_valid_value(name in values, f"key '{name}' is missing") 82 | yield from serializer.serialize_with_context(context, values[name]) 83 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/array_serializer.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import Generator, Iterable, List 3 | 4 | from .._context import ( 5 | DeserializationContext, 6 | SerializationContext, 7 | ) 8 | from ..data_serializers._common import ( 9 | deserialize_to_list, 10 | serialize_from_list, 11 | ) 12 | from ..data_serializers.cairo_data_serializer import ( 13 | CairoDataSerializer, 14 | ) 15 | 16 | 17 | @dataclass 18 | class ArraySerializer(CairoDataSerializer[Iterable, List]): 19 | """ 20 | Serializer for arrays. In abi they are represented as a pointer to a type. 21 | Can serialize any iterable and prepends its length to resulting list. 22 | Deserializes data to a list. 23 | 24 | Examples: 25 | [1,2,3] => [3,1,2,3] 26 | [] => [0] 27 | """ 28 | 29 | inner_serializer: CairoDataSerializer 30 | 31 | def deserialize_with_context(self, context: DeserializationContext) -> List: 32 | with context.push_entity("len"): 33 | [size] = context.reader.read(1) 34 | 35 | return deserialize_to_list([self.inner_serializer] * size, context) 36 | 37 | def serialize_with_context( 38 | self, context: SerializationContext, value: List 39 | ) -> Generator[int, None, None]: 40 | yield len(value) 41 | yield from serialize_from_list( 42 | [self.inner_serializer] * len(value), context, value 43 | ) 44 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/bool_serializer.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import Generator 3 | 4 | from .._context import ( 5 | Context, 6 | DeserializationContext, 7 | SerializationContext, 8 | ) 9 | from .cairo_data_serializer import ( 10 | CairoDataSerializer, 11 | ) 12 | 13 | 14 | @dataclass 15 | class BoolSerializer(CairoDataSerializer[bool, int]): 16 | """ 17 | Serializer for boolean. 18 | """ 19 | 20 | def deserialize_with_context(self, context: DeserializationContext) -> bool: 21 | [val] = context.reader.read(1) 22 | self._ensure_bool(context, val) 23 | return bool(val) 24 | 25 | def serialize_with_context( 26 | self, context: SerializationContext, value: bool 27 | ) -> Generator[int, None, None]: 28 | context.ensure_valid_type(value, isinstance(value, bool), "bool") 29 | self._ensure_bool(context, value) 30 | yield int(value) 31 | 32 | @staticmethod 33 | def _ensure_bool(context: Context, value: int): 34 | context.ensure_valid_value( 35 | value in [0, 1], 36 | f"invalid value '{value}' - must be in [0, 2) range", 37 | ) 38 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/byte_array_serializer.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import Generator 3 | 4 | from ...cairo.felt import decode_shortstring, encode_shortstring 5 | from .._context import ( 6 | DeserializationContext, 7 | SerializationContext, 8 | ) 9 | from ._common import ( 10 | deserialize_to_list, 11 | serialize_from_list, 12 | ) 13 | from .cairo_data_serializer import ( 14 | CairoDataSerializer, 15 | ) 16 | from .felt_serializer import FeltSerializer 17 | 18 | BYTES_31_SIZE = 31 19 | 20 | 21 | @dataclass 22 | class ByteArraySerializer(CairoDataSerializer[str, str]): 23 | """ 24 | Serializer for ByteArrays. Serializes to and deserializes from str values. 25 | 26 | Examples: 27 | "" => [0,0,0] 28 | "hello" => [0,448378203247,5] 29 | """ 30 | 31 | def deserialize_with_context(self, context: DeserializationContext) -> str: 32 | with context.push_entity("data_array_len"): 33 | [size] = context.reader.read(1) 34 | 35 | data = deserialize_to_list([FeltSerializer()] * size, context) 36 | 37 | with context.push_entity("pending_word"): 38 | [pending_word] = context.reader.read(1) 39 | 40 | with context.push_entity("pending_word_len"): 41 | [pending_word_len] = context.reader.read(1) 42 | 43 | pending_word = decode_shortstring(pending_word) 44 | context.ensure_valid_value( 45 | len(pending_word) == pending_word_len, 46 | f"Invalid length {pending_word_len} for pending word {pending_word}", 47 | ) 48 | 49 | data_joined = "".join(map(decode_shortstring, data)) 50 | return data_joined + pending_word 51 | 52 | def serialize_with_context( 53 | self, context: SerializationContext, value: str 54 | ) -> Generator[int, None, None]: 55 | context.ensure_valid_type(value, isinstance(value, str), "str") 56 | data = [ 57 | value[i : i + BYTES_31_SIZE] for i in range(0, len(value), BYTES_31_SIZE) 58 | ] 59 | pending_word = ( 60 | "" if len(data) == 0 or len(data[-1]) == BYTES_31_SIZE else data.pop(-1) 61 | ) 62 | 63 | yield len(data) 64 | yield from serialize_from_list([FeltSerializer()] * len(data), context, data) 65 | yield encode_shortstring(pending_word) 66 | yield len(pending_word) 67 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/cairo_data_serializer.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | from typing import Generator, Generic, List, TypeVar 3 | 4 | from .._calldata_reader import CairoData 5 | from .._context import ( 6 | DeserializationContext, 7 | SerializationContext, 8 | ) 9 | 10 | # Python type that is accepted by a serializer 11 | # pylint: disable=invalid-name 12 | SerializationType = TypeVar("SerializationType") 13 | 14 | # Python type that will be returned from a serializer. Often same as SerializationType. 15 | # pylint: disable=invalid-name 16 | DeserializationType = TypeVar("DeserializationType") 17 | 18 | 19 | class CairoDataSerializer(ABC, Generic[SerializationType, DeserializationType]): 20 | """ 21 | Base class for serializing/deserializing data to/from calldata. 22 | """ 23 | 24 | def deserialize(self, data: List[int]) -> DeserializationType: 25 | """ 26 | Transform calldata into python value. 27 | 28 | :param data: calldata to deserialize. 29 | :return: defined DeserializationType. 30 | """ 31 | with DeserializationContext.create(data) as context: 32 | return self.deserialize_with_context(context) 33 | 34 | def serialize(self, data: SerializationType) -> CairoData: 35 | """ 36 | Transform python data into calldata. 37 | 38 | :param data: data to serialize. 39 | :return: calldata. 40 | """ 41 | with SerializationContext.create() as context: 42 | serialized_data = list(self.serialize_with_context(context, data)) 43 | 44 | return self.remove_units_from_serialized_data(serialized_data) 45 | 46 | @abstractmethod 47 | def deserialize_with_context( 48 | self, context: DeserializationContext 49 | ) -> DeserializationType: 50 | """ 51 | Transform calldata into python value. 52 | 53 | :param context: context of this deserialization. 54 | :return: defined DeserializationType. 55 | """ 56 | 57 | @abstractmethod 58 | def serialize_with_context( 59 | self, context: SerializationContext, value: SerializationType 60 | ) -> Generator[int, None, None]: 61 | """ 62 | Transform python value into calldata. 63 | 64 | :param context: context of this serialization. 65 | :param value: python value to serialize. 66 | :return: defined SerializationType. 67 | """ 68 | 69 | @staticmethod 70 | def remove_units_from_serialized_data(serialized_data: List) -> List: 71 | return [x for x in serialized_data if x is not None] 72 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/enum_serializer.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import Dict, Generator, OrderedDict, Tuple, Union 3 | 4 | from .._context import ( 5 | DeserializationContext, 6 | SerializationContext, 7 | ) 8 | from .cairo_data_serializer import ( 9 | CairoDataSerializer, 10 | ) 11 | from ..tuple_dataclass import TupleDataclass 12 | 13 | 14 | @dataclass 15 | class EnumSerializer(CairoDataSerializer[Union[Dict, TupleDataclass], TupleDataclass]): 16 | """ 17 | Serializer of enums. 18 | Can serialize a dictionary and TupleDataclass. 19 | Deserializes data to a TupleDataclass. 20 | 21 | Example: 22 | enum MyEnum { 23 | a: u128, 24 | b: u128 25 | } 26 | 27 | {"a": 1} => [0, 1] 28 | {"b": 100} => [1, 100] 29 | TupleDataclass(variant='a', value=100) => [0, 100] 30 | """ 31 | 32 | serializers: OrderedDict[str, CairoDataSerializer] 33 | 34 | def deserialize_with_context( 35 | self, context: DeserializationContext 36 | ) -> TupleDataclass: 37 | [variant_index] = context.reader.read(1) 38 | variant_name, serializer = self._get_variant(variant_index) 39 | 40 | with context.push_entity("enum.variant: " + variant_name): 41 | result_dict = { 42 | "variant": variant_name, 43 | "value": serializer.deserialize_with_context(context), 44 | } 45 | 46 | return TupleDataclass.from_dict(result_dict) 47 | 48 | def serialize_with_context( 49 | self, context: SerializationContext, value: Union[Dict, TupleDataclass] 50 | ) -> Generator[int, None, None]: 51 | if isinstance(value, Dict): 52 | items = list(value.items()) 53 | if len(items) != 1: 54 | raise ValueError( 55 | "Can serialize only one enum variant, got: " + str(len(items)) 56 | ) 57 | 58 | variant_name, variant_value = items[0] 59 | else: 60 | variant_name, variant_value = value 61 | 62 | yield self._get_variant_index(variant_name) 63 | yield from self.serializers[variant_name].serialize_with_context( 64 | context, variant_value 65 | ) 66 | 67 | def _get_variant(self, variant_index: int) -> Tuple[str, CairoDataSerializer]: 68 | return list(self.serializers.items())[variant_index] 69 | 70 | def _get_variant_index(self, variant_name: str) -> int: 71 | return list(self.serializers.keys()).index(variant_name) 72 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/felt_serializer.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | from dataclasses import dataclass 3 | from typing import Generator 4 | 5 | from ...cairo.felt import encode_shortstring, is_in_felt_range 6 | from ...constants import FIELD_PRIME 7 | from .._context import ( 8 | Context, 9 | DeserializationContext, 10 | SerializationContext, 11 | ) 12 | from .cairo_data_serializer import ( 13 | CairoDataSerializer, 14 | ) 15 | 16 | 17 | @dataclass 18 | class FeltSerializer(CairoDataSerializer[int, int]): 19 | """ 20 | Serializer for field element. At the time of writing it is the only existing numeric type. 21 | """ 22 | 23 | def deserialize_with_context(self, context: DeserializationContext) -> int: 24 | [val] = context.reader.read(1) 25 | self._ensure_felt(context, val) 26 | return val 27 | 28 | def serialize_with_context( 29 | self, context: SerializationContext, value: int 30 | ) -> Generator[int, None, None]: 31 | if isinstance(value, str): 32 | warnings.warn( 33 | "Serializing shortstrings in FeltSerializer is deprecated. " 34 | "Use starknet_py.cairo.felt.encode_shortstring instead.", 35 | category=DeprecationWarning, 36 | ) 37 | value = encode_shortstring(value) 38 | yield value 39 | return 40 | 41 | context.ensure_valid_type(value, isinstance(value, int), "int") 42 | self._ensure_felt(context, value) 43 | yield value 44 | 45 | @staticmethod 46 | def _ensure_felt(context: Context, value: int): 47 | context.ensure_valid_value( 48 | is_in_felt_range(value), 49 | f"invalid value '{value}' - must be in [0, {FIELD_PRIME}) range", 50 | ) 51 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/named_tuple_serializer.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import Dict, Generator, NamedTuple, OrderedDict, Union 3 | 4 | from .._context import ( 5 | DeserializationContext, 6 | SerializationContext, 7 | ) 8 | from ._common import ( 9 | deserialize_to_dict, 10 | serialize_from_dict, 11 | ) 12 | from .cairo_data_serializer import ( 13 | CairoDataSerializer, 14 | ) 15 | from ..tuple_dataclass import TupleDataclass 16 | 17 | 18 | @dataclass 19 | class NamedTupleSerializer( 20 | CairoDataSerializer[Union[Dict, NamedTuple, TupleDataclass], TupleDataclass] 21 | ): 22 | """ 23 | Serializer for tuples with named fields. 24 | Can serialize a dictionary, a named tuple and TupleDataclass. 25 | Deserializes data to a TupleDataclass. 26 | 27 | Example: 28 | {"a": 1, "b": 2} => [1,2] 29 | """ 30 | 31 | serializers: OrderedDict[str, CairoDataSerializer] 32 | 33 | def deserialize_with_context( 34 | self, context: DeserializationContext 35 | ) -> TupleDataclass: 36 | as_dictionary = deserialize_to_dict(self.serializers, context) 37 | return TupleDataclass.from_dict(as_dictionary) 38 | 39 | def serialize_with_context( 40 | self, 41 | context: SerializationContext, 42 | value: Union[Dict, NamedTuple, TupleDataclass], 43 | ) -> Generator[int, None, None]: 44 | # We can't use isinstance(value, NamedTuple), because there is no NamedTuple type. 45 | context.ensure_valid_type( 46 | value, 47 | isinstance(value, (dict, TupleDataclass)) or self._is_namedtuple(value), 48 | "dict, NamedTuple or TupleDataclass", 49 | ) 50 | 51 | # noinspection PyUnresolvedReferences, PyProtectedMember 52 | values: Dict = value if isinstance(value, dict) else value._asdict() 53 | 54 | yield from serialize_from_dict(self.serializers, context, values) 55 | 56 | @staticmethod 57 | def _is_namedtuple(value) -> bool: 58 | return isinstance(value, tuple) and hasattr(value, "_fields") 59 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/option_serializer.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import Any, Generator, Optional 3 | 4 | from .._context import ( 5 | DeserializationContext, 6 | SerializationContext, 7 | ) 8 | from .cairo_data_serializer import ( 9 | CairoDataSerializer, 10 | ) 11 | 12 | 13 | @dataclass 14 | class OptionSerializer(CairoDataSerializer[Optional[Any], Optional[Any]]): 15 | """ 16 | Serializer for Option type. 17 | Can serialize None and common CairoTypes. 18 | Deserializes data to None or CairoType. 19 | 20 | Example: 21 | None => [1] 22 | {"option1": 123, "option2": None} => [0, 123, 1] 23 | """ 24 | 25 | serializer: CairoDataSerializer 26 | 27 | def deserialize_with_context( 28 | self, context: DeserializationContext 29 | ) -> Optional[Any]: 30 | (is_none,) = context.reader.read(1) 31 | if is_none == 1: 32 | return None 33 | 34 | return self.serializer.deserialize_with_context(context) 35 | 36 | def serialize_with_context( 37 | self, context: SerializationContext, value: Optional[Any] 38 | ) -> Generator[int, None, None]: 39 | if value is None: 40 | yield 1 41 | else: 42 | yield 0 43 | yield from self.serializer.serialize_with_context(context, value) 44 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/output_serializer.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass, field 2 | from typing import Dict, Generator, List, Tuple 3 | 4 | from .._context import ( 5 | DeserializationContext, 6 | SerializationContext, 7 | ) 8 | from .cairo_data_serializer import ( 9 | CairoDataSerializer, 10 | ) 11 | 12 | 13 | @dataclass 14 | class OutputSerializer(CairoDataSerializer[List, Tuple]): 15 | """ 16 | Serializer for function output. 17 | Can't serialize anything. 18 | Deserializes data to a Tuple. 19 | 20 | Example: 21 | [1, 1, 1] => (340282366920938463463374607431768211457) 22 | """ 23 | 24 | serializers: List[CairoDataSerializer] = field(init=True) 25 | 26 | def deserialize_with_context(self, context: DeserializationContext) -> Tuple: 27 | result = [] 28 | 29 | for index, serializer in enumerate(self.serializers): 30 | with context.push_entity("output[" + str(index) + "]"): 31 | result.append(serializer.deserialize_with_context(context)) 32 | 33 | return tuple(result) 34 | 35 | def serialize_with_context( 36 | self, context: SerializationContext, value: Dict 37 | ) -> Generator[int, None, None]: 38 | raise ValueError( 39 | "Output serializer can't be used to transform python data into calldata." 40 | ) 41 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/payload_serializer.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict as _OrderedDict 2 | from dataclasses import InitVar, dataclass, field 3 | from typing import Dict, Generator, OrderedDict 4 | 5 | from .._context import ( 6 | DeserializationContext, 7 | SerializationContext, 8 | ) 9 | from ._common import ( 10 | deserialize_to_dict, 11 | serialize_from_dict, 12 | ) 13 | from .array_serializer import ArraySerializer 14 | from .cairo_data_serializer import ( 15 | CairoDataSerializer, 16 | ) 17 | from .felt_serializer import FeltSerializer 18 | from ..tuple_dataclass import TupleDataclass 19 | 20 | SIZE_SUFFIX = "_len" 21 | SIZE_SUFFIX_LEN = len(SIZE_SUFFIX) 22 | 23 | 24 | @dataclass 25 | class PayloadSerializer(CairoDataSerializer[Dict, TupleDataclass]): 26 | """ 27 | Serializer for payloads like function arguments/function outputs/events. 28 | Can serialize a dictionary. 29 | Deserializes data to a TupleDataclass. 30 | 31 | Example: 32 | {"a": 1, "b": 2} => [1,2] 33 | """ 34 | 35 | # Value present only in constructor. 36 | # We don't want to mutate the serializers received in constructor. 37 | input_serializers: InitVar[OrderedDict[str, CairoDataSerializer]] 38 | 39 | serializers: OrderedDict[str, CairoDataSerializer] = field(init=False) 40 | 41 | def __post_init__(self, input_serializers): 42 | """ 43 | ABI adds ARG_len for every argument ARG that is an array. We parse length as a part of ArraySerializer, so we 44 | need to remove those lengths from args. 45 | """ 46 | self.serializers = _OrderedDict( 47 | (key, serializer) 48 | for key, serializer in input_serializers.items() 49 | if not self._is_len_arg(key, input_serializers) 50 | ) 51 | 52 | def deserialize_with_context( 53 | self, context: DeserializationContext 54 | ) -> TupleDataclass: 55 | as_dictionary = deserialize_to_dict(self.serializers, context) 56 | return TupleDataclass.from_dict(as_dictionary) 57 | 58 | def serialize_with_context( 59 | self, context: SerializationContext, value: Dict 60 | ) -> Generator[int, None, None]: 61 | yield from serialize_from_dict(self.serializers, context, value) 62 | 63 | @staticmethod 64 | def _is_len_arg(arg_name: str, serializers: Dict[str, CairoDataSerializer]) -> bool: 65 | return ( 66 | arg_name.endswith(SIZE_SUFFIX) 67 | and isinstance(serializers[arg_name], FeltSerializer) 68 | # There is an ArraySerializer under key that is arg_name without the size suffix 69 | and isinstance( 70 | serializers.get(arg_name[:-SIZE_SUFFIX_LEN]), ArraySerializer 71 | ) 72 | ) 73 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/struct_serializer.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import Dict, Generator, OrderedDict 3 | 4 | from .._context import ( 5 | DeserializationContext, 6 | SerializationContext, 7 | ) 8 | from ._common import ( 9 | deserialize_to_dict, 10 | serialize_from_dict, 11 | ) 12 | from .cairo_data_serializer import ( 13 | CairoDataSerializer, 14 | ) 15 | 16 | 17 | @dataclass 18 | class StructSerializer(CairoDataSerializer[Dict, Dict]): 19 | """ 20 | Serializer of custom structures. 21 | Can serialize a dictionary. 22 | Deserializes data to a dictionary. 23 | 24 | Example: 25 | {"a": 1, "b": 2} => [1,2] 26 | """ 27 | 28 | serializers: OrderedDict[str, CairoDataSerializer] 29 | 30 | def deserialize_with_context(self, context: DeserializationContext) -> Dict: 31 | return deserialize_to_dict(self.serializers, context) 32 | 33 | def serialize_with_context( 34 | self, context: SerializationContext, value: Dict 35 | ) -> Generator[int, None, None]: 36 | yield from serialize_from_dict(self.serializers, context, value) 37 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/tuple_serializer.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import Generator, Iterable, List, Tuple 3 | 4 | from .._context import ( 5 | DeserializationContext, 6 | SerializationContext, 7 | ) 8 | from ._common import ( 9 | deserialize_to_list, 10 | serialize_from_list, 11 | ) 12 | from .cairo_data_serializer import ( 13 | CairoDataSerializer, 14 | ) 15 | 16 | 17 | @dataclass 18 | class TupleSerializer(CairoDataSerializer[Iterable, Tuple]): 19 | """ 20 | Serializer for tuples without named fields. 21 | Can serialize any iterable. 22 | Deserializes data to a python tuple. 23 | 24 | Example: 25 | (1,2,(3,4)) => [1,2,3,4] 26 | """ 27 | 28 | serializers: List[CairoDataSerializer] 29 | 30 | def deserialize_with_context(self, context: DeserializationContext) -> Tuple: 31 | return tuple(deserialize_to_list(self.serializers, context)) 32 | 33 | def serialize_with_context( 34 | self, context: SerializationContext, value: Iterable 35 | ) -> Generator[int, None, None]: 36 | yield from serialize_from_list(self.serializers, context, [*value]) 37 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/uint256_serializer.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import Generator, TypedDict, Union 3 | 4 | from ...cairo.felt import uint256_range_check 5 | from .._context import ( 6 | Context, 7 | DeserializationContext, 8 | SerializationContext, 9 | ) 10 | from .cairo_data_serializer import ( 11 | CairoDataSerializer, 12 | ) 13 | 14 | U128_UPPER_BOUND = 2**128 15 | 16 | 17 | class Uint256Dict(TypedDict): 18 | low: int 19 | high: int 20 | 21 | 22 | @dataclass 23 | class Uint256Serializer(CairoDataSerializer[Union[int, Uint256Dict], int]): 24 | """ 25 | Serializer of Uint256. In Cairo it is represented by structure {low: Uint128, high: Uint128}. 26 | Can serialize an int. 27 | Deserializes data to an int. 28 | 29 | Examples: 30 | 0 => [0,0] 31 | 1 => [1,0] 32 | 2**128 => [0,1] 33 | 3 + 2**128 => [3,1] 34 | """ 35 | 36 | def deserialize_with_context(self, context: DeserializationContext) -> int: 37 | [low, high] = context.reader.read(2) 38 | 39 | # Checking if resulting value is in [0, 2**256) range is not enough. Uint256 should be made of two uint128. 40 | with context.push_entity("low"): 41 | self._ensure_valid_uint128(low, context) 42 | with context.push_entity("high"): 43 | self._ensure_valid_uint128(high, context) 44 | 45 | return (high << 128) + low 46 | 47 | def serialize_with_context( 48 | self, context: SerializationContext, value: Union[int, Uint256Dict] 49 | ) -> Generator[int, None, None]: 50 | context.ensure_valid_type(value, isinstance(value, (int, dict)), "int or dict") 51 | if isinstance(value, int): 52 | yield from self._serialize_from_int(value) 53 | else: 54 | yield from self._serialize_from_dict(context, value) 55 | 56 | @staticmethod 57 | def _serialize_from_int(value: int) -> Generator[int, None, None]: 58 | uint256_range_check(value) 59 | result = (value % 2**128, value // 2**128) 60 | yield from result 61 | 62 | def _serialize_from_dict( 63 | self, context: SerializationContext, value: Uint256Dict 64 | ) -> Generator[int, None, None]: 65 | with context.push_entity("low"): 66 | self._ensure_valid_uint128(value["low"], context) 67 | yield value["low"] 68 | with context.push_entity("high"): 69 | self._ensure_valid_uint128(value["high"], context) 70 | yield value["high"] 71 | 72 | @staticmethod 73 | def _ensure_valid_uint128(value: int, context: Context): 74 | context.ensure_valid_value( 75 | 0 <= value < U128_UPPER_BOUND, "expected value in range [0;2**128)" 76 | ) 77 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/data_serializers/unit_serializer.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import Any, Generator, Optional 3 | 4 | from .._context import ( 5 | DeserializationContext, 6 | SerializationContext, 7 | ) 8 | from .cairo_data_serializer import ( 9 | CairoDataSerializer, 10 | ) 11 | 12 | 13 | @dataclass 14 | class UnitSerializer(CairoDataSerializer[None, None]): 15 | """ 16 | Serializer for unit type. 17 | Can only serialize None. 18 | Deserializes data to None. 19 | 20 | Example: 21 | [] => None 22 | """ 23 | 24 | def deserialize_with_context(self, context: DeserializationContext) -> None: 25 | return None 26 | 27 | def serialize_with_context( 28 | self, context: SerializationContext, value: Optional[Any] 29 | ) -> Generator[None, None, None]: 30 | if value is not None: 31 | raise ValueError("Can only serialize `None`.") 32 | yield None 33 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/errors.py: -------------------------------------------------------------------------------- 1 | class CairoSerializerException(Exception): 2 | """Exception thrown by CairoSerializer.""" 3 | 4 | 5 | class InvalidTypeException(CairoSerializerException, TypeError): 6 | """Exception thrown when invalid type was provided.""" 7 | 8 | 9 | class InvalidValueException(CairoSerializerException, ValueError): 10 | """Exception thrown when invalid value was provided.""" 11 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/serialization/tuple_dataclass.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from dataclasses import dataclass, fields, make_dataclass 4 | from typing import Dict, Optional, Tuple 5 | 6 | 7 | @dataclass(frozen=True, eq=False) 8 | class TupleDataclass: 9 | """ 10 | Dataclass that behaves like a tuple at the same time. Used when data has defined order and names. 11 | For instance in case of named tuples or function responses. 12 | """ 13 | 14 | # getattr is called when attribute is not found in object. For instance when using object.unknown_attribute. 15 | # This way pyright will know that there might be some arguments it doesn't know about and will stop complaining 16 | # about some fields that don't exist statically. 17 | def __getattr__(self, item): 18 | # This should always fail - only attributes that don't exist end up in here. 19 | # We use __getattribute__ to get the native error. 20 | return super().__getattribute__(item) 21 | 22 | def __getitem__(self, item: int): 23 | field = fields(self)[item] 24 | return getattr(self, field.name) 25 | 26 | def __iter__(self): 27 | return (getattr(self, field.name) for field in fields(self)) 28 | 29 | def as_tuple(self) -> Tuple: 30 | """ 31 | Creates a regular tuple from TupleDataclass. 32 | """ 33 | return tuple(self) 34 | 35 | def as_dict(self) -> Dict: 36 | """ 37 | Creates a regular dict from TupleDataclass. 38 | """ 39 | return {field.name: getattr(self, field.name) for field in fields(self)} 40 | 41 | # Added for backward compatibility with previous implementation based on NamedTuple 42 | def _asdict(self): 43 | return self.as_dict() 44 | 45 | def __eq__(self, other): 46 | if isinstance(other, TupleDataclass): 47 | return self.as_tuple() == other.as_tuple() 48 | return self.as_tuple() == other 49 | 50 | @staticmethod 51 | def from_dict(data: Dict, *, name: Optional[str] = None) -> TupleDataclass: 52 | result_class = make_dataclass( 53 | name or "TupleDataclass", 54 | fields=[(key, type(value)) for key, value in data.items()], 55 | bases=(TupleDataclass,), 56 | frozen=True, 57 | eq=False, 58 | ) 59 | return result_class(**data) 60 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/starknet/utils/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/utils/constructor_args_translator.py: -------------------------------------------------------------------------------- 1 | from typing import List, Optional, Union 2 | 3 | from ..abi.v2 import shape as ShapeV2 4 | from ..abi.v0 import AbiParser as AbiParserV0 5 | from ..abi.v1 import AbiParser as AbiParserV1 6 | from ..abi.v2 import AbiParser as AbiParserV2 7 | from ..serialization import ( 8 | FunctionSerializationAdapter, 9 | serializer_for_function, 10 | ) 11 | from ..serialization.factory import ( 12 | serializer_for_constructor_v2, 13 | serializer_for_function_v1, 14 | ) 15 | 16 | 17 | def translate_constructor_args( 18 | abi: List, constructor_args: Optional[Union[List, dict]], *, cairo_version: int = 1 19 | ) -> List[int]: 20 | serializer = ( 21 | _get_constructor_serializer_v1(abi) 22 | if cairo_version == 1 23 | else _get_constructor_serializer_v0(abi) 24 | ) 25 | 26 | if serializer is None or len(serializer.inputs_serializer.serializers) == 0: 27 | return [] 28 | 29 | if not constructor_args: 30 | raise ValueError( 31 | "Provided contract has a constructor and no arguments were provided." 32 | ) 33 | 34 | args, kwargs = ( 35 | ([], constructor_args) 36 | if isinstance(constructor_args, dict) 37 | else (constructor_args, {}) 38 | ) 39 | return serializer.serialize(*args, **kwargs) 40 | 41 | 42 | def _get_constructor_serializer_v1(abi: List) -> Optional[FunctionSerializationAdapter]: 43 | if _is_abi_v2(abi): 44 | parsed = AbiParserV2(abi).parse() 45 | constructor = parsed.constructor 46 | 47 | if constructor is None or not constructor.inputs: 48 | return None 49 | 50 | return serializer_for_constructor_v2(constructor) 51 | 52 | parsed = AbiParserV1(abi).parse() 53 | constructor = parsed.functions.get("constructor", None) 54 | 55 | # Constructor might not accept any arguments 56 | if constructor is None or not constructor.inputs: 57 | return None 58 | 59 | return serializer_for_function_v1(constructor) 60 | 61 | 62 | def _is_abi_v2(abi: List) -> bool: 63 | for entry in abi: 64 | if entry["type"] in [ 65 | ShapeV2.CONSTRUCTOR_ENTRY, 66 | ShapeV2.L1_HANDLER_ENTRY, 67 | ShapeV2.INTERFACE_ENTRY, 68 | ShapeV2.IMPL_ENTRY, 69 | ]: 70 | return True 71 | if entry["type"] == ShapeV2.EVENT_ENTRY: 72 | if "inputs" in entry: 73 | return False 74 | if "kind" in entry: 75 | return True 76 | return False 77 | 78 | 79 | def _get_constructor_serializer_v0(abi: List) -> Optional[FunctionSerializationAdapter]: 80 | parsed = AbiParserV0(abi).parse() 81 | 82 | # Constructor might not accept any arguments 83 | if not parsed.constructor or not parsed.constructor.inputs: 84 | return None 85 | 86 | return serializer_for_function(parsed.constructor) 87 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/utils/iterable.py: -------------------------------------------------------------------------------- 1 | from typing import Iterable, TypeVar, Union 2 | 3 | T = TypeVar("T") 4 | 5 | 6 | # pyright: reportGeneralTypeIssues=false 7 | def ensure_iterable(value: Union[T, Iterable[T]]) -> Iterable[T]: 8 | try: 9 | iter(value) 10 | # Now we now it is iterable 11 | return value 12 | except TypeError: 13 | return [value] 14 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starknet/utils/schema.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from ..marshmallow import EXCLUDE, RAISE 4 | from ..marshmallow import Schema as MarshmallowSchema 5 | 6 | MARSHMALLOW_UKNOWN_EXCLUDE = os.environ.get("STARKNET_PY_MARSHMALLOW_UKNOWN_EXCLUDE") 7 | 8 | 9 | class Schema(MarshmallowSchema): 10 | class Meta: 11 | unknown = ( 12 | EXCLUDE if (MARSHMALLOW_UKNOWN_EXCLUDE or "").lower() == "true" else RAISE 13 | ) 14 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starkware/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/starkware/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starkware/crypto/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/starkware/crypto/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starkware/crypto/fast_pedersen_hash.py: -------------------------------------------------------------------------------- 1 | from ...ecdsa.curves import Curve 2 | from ...ecdsa.ellipticcurve import CurveFp, Point 3 | 4 | from .signature import ( 5 | ALPHA, 6 | BETA, 7 | CONSTANT_POINTS, 8 | EC_ORDER, 9 | FIELD_PRIME, 10 | N_ELEMENT_BITS_HASH, 11 | SHIFT_POINT, 12 | ) 13 | from .utils import from_bytes, to_bytes 14 | 15 | curve_stark = CurveFp(FIELD_PRIME, ALPHA, BETA) 16 | LOW_PART_BITS = 248 17 | LOW_PART_MASK = 2**248 - 1 18 | HASH_SHIFT_POINT = Point(curve_stark, SHIFT_POINT[0], SHIFT_POINT[1], EC_ORDER) 19 | P_0 = Point(curve_stark, CONSTANT_POINTS[2][0], CONSTANT_POINTS[2][1], EC_ORDER) 20 | P_1 = Point(curve_stark, CONSTANT_POINTS[2 + LOW_PART_BITS][0], CONSTANT_POINTS[2 + LOW_PART_BITS][1], EC_ORDER) 21 | P_2 = Point(curve_stark, CONSTANT_POINTS[2 + N_ELEMENT_BITS_HASH][0], CONSTANT_POINTS[2 + N_ELEMENT_BITS_HASH][1], EC_ORDER) 22 | P_3 = Point(curve_stark, CONSTANT_POINTS[2 + N_ELEMENT_BITS_HASH + LOW_PART_BITS][0], CONSTANT_POINTS[2 + N_ELEMENT_BITS_HASH + LOW_PART_BITS][1], EC_ORDER) 23 | 24 | def process_single_element(element: int, p1, p2) -> Point: 25 | assert 0 <= element < FIELD_PRIME, "Element integer value is out of range" 26 | 27 | high_nibble = element >> LOW_PART_BITS 28 | low_part = element & LOW_PART_MASK 29 | return low_part * p1 + high_nibble * p2 30 | 31 | 32 | def pedersen_hash(x: int, y: int) -> int: 33 | """ 34 | Computes the Starkware version of the Pedersen hash of x and y. 35 | The hash is defined by: 36 | shift_point + x_low * P_0 + x_high * P1 + y_low * P2 + y_high * P3 37 | where x_low is the 248 low bits of x, x_high is the 4 high bits of x and similarly for y. 38 | shift_point, P_0, P_1, P_2, P_3 are constant points generated from the digits of pi. 39 | """ 40 | return ( 41 | HASH_SHIFT_POINT + process_single_element(x, P_0, P_1) + process_single_element(y, P_2, P_3) 42 | ).x() 43 | 44 | 45 | def pedersen_hash_func(x: bytes, y: bytes) -> bytes: 46 | """ 47 | A variant of 'pedersen_hash', where the elements and their resulting hash are in bytes. 48 | """ 49 | assert len(x) == len(y) == 32, "Unexpected element length." 50 | return to_bytes(pedersen_hash(*(from_bytes(element) for element in (x, y)))) 51 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/starkware/crypto/utils.py: -------------------------------------------------------------------------------- 1 | from typing import ( 2 | AsyncGenerator, 3 | Optional, 4 | TypeVar, 5 | ) 6 | 7 | import sys 8 | 9 | if sys.version_info.minor >= 11: 10 | from typing import Literal, ParamSpec 11 | else: 12 | from typing_extensions import Literal, ParamSpec 13 | 14 | T = TypeVar("T") 15 | P = ParamSpec("P") 16 | K = TypeVar("K") 17 | V = TypeVar("V") 18 | TAsyncGenerator = TypeVar("TAsyncGenerator", bound=AsyncGenerator) 19 | NumType = TypeVar("NumType", int, float) 20 | HASH_BYTES = 32 21 | 22 | # If more shared types start popping up here extract to types.py. 23 | Endianness = Literal["big", "little"] 24 | TComparable = TypeVar("TComparable", bound="Comparable") 25 | 26 | def to_bytes( 27 | value: int, 28 | length: Optional[int] = None, 29 | byte_order: Optional[Endianness] = None, 30 | signed: Optional[bool] = None, 31 | ) -> bytes: 32 | """ 33 | Converts the given integer to a bytes object of given length and byte order. 34 | The default values are 32B width (which is the hash result width) and 'big', respectively. 35 | """ 36 | if length is None: 37 | length = HASH_BYTES 38 | 39 | if byte_order is None: 40 | byte_order = "big" 41 | 42 | if signed is None: 43 | signed = False 44 | 45 | return int.to_bytes(value, length=length, byteorder=byte_order, signed=signed) 46 | 47 | 48 | def from_bytes( 49 | value: bytes, 50 | byte_order: Optional[Endianness] = None, 51 | signed: Optional[bool] = None, 52 | ) -> int: 53 | """ 54 | Converts the given bytes object (parsed according to the given byte order) to an integer. 55 | Default byte order is 'big'. 56 | """ 57 | if byte_order is None: 58 | byte_order = "big" 59 | 60 | if signed is None: 61 | signed = False 62 | 63 | return int.from_bytes(value, byteorder=byte_order, signed=signed) -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/sympy/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/sympy/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/sympy/core/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/sympy/core/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/sympy/core/intfunc.py: -------------------------------------------------------------------------------- 1 | """ 2 | The routines here were removed from numbers.py, power.py, 3 | digits.py and factor_.py so they could be imported into core 4 | without raising circular import errors. 5 | 6 | Although the name 'intfunc' was chosen to represent functions that 7 | work with integers, it can also be thought of as containing 8 | internal/core functions that are needed by the classes of the core. 9 | """ 10 | 11 | from ..external.gmpy import (gcdext) 12 | 13 | def igcdex(a, b): 14 | """Returns x, y, g such that g = x*a + y*b = gcd(a, b). 15 | 16 | Examples 17 | ======== 18 | 19 | >>> from sympy.core.intfunc import igcdex 20 | >>> igcdex(2, 3) 21 | (-1, 1, 1) 22 | >>> igcdex(10, 12) 23 | (-1, 1, 2) 24 | 25 | >>> x, y, g = igcdex(100, 2004) 26 | >>> x, y, g 27 | (-20, 1, 4) 28 | >>> x*100 + y*2004 29 | 4 30 | 31 | """ 32 | if (not a) and (not b): 33 | return (0, 1, 0) 34 | g, x, y = gcdext(int(a), int(b)) 35 | return x, y, g 36 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/sympy/external/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/sympy/external/__init__.py -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/toolz/__init__.py: -------------------------------------------------------------------------------- 1 | from .itertoolz import * 2 | 3 | from .functoolz import * 4 | 5 | from .dicttoolz import * 6 | 7 | from .recipes import * 8 | 9 | from functools import partial, reduce 10 | 11 | sorted = sorted 12 | 13 | map = map 14 | 15 | filter = filter 16 | 17 | # Aliases 18 | comp = compose 19 | 20 | from . import curried 21 | 22 | # functoolz._sigs.create_signature_registry() 23 | 24 | from ._version import get_versions 25 | __version__ = get_versions()['version'] 26 | del get_versions 27 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/toolz/compatibility.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | warnings.warn("The toolz.compatibility module is no longer " 3 | "needed in Python 3 and has been deprecated. Please " 4 | "import these utilities directly from the standard library. " 5 | "This module will be removed in a future release.", 6 | category=DeprecationWarning, stacklevel=2) 7 | 8 | import operator 9 | import sys 10 | 11 | PY3 = sys.version_info[0] > 2 12 | PY34 = sys.version_info[0] == 3 and sys.version_info[1] == 4 13 | PYPY = hasattr(sys, 'pypy_version_info') and PY3 14 | 15 | __all__ = ('map', 'filter', 'range', 'zip', 'reduce', 'zip_longest', 16 | 'iteritems', 'iterkeys', 'itervalues', 'filterfalse', 17 | 'PY3', 'PY34', 'PYPY') 18 | 19 | 20 | map = map 21 | filter = filter 22 | range = range 23 | zip = zip 24 | from functools import reduce 25 | from itertools import zip_longest 26 | from itertools import filterfalse 27 | iteritems = operator.methodcaller('items') 28 | iterkeys = operator.methodcaller('keys') 29 | itervalues = operator.methodcaller('values') 30 | from collections.abc import Sequence 31 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/toolz/curried/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Alternate namespace for toolz such that all functions are curried 3 | 4 | Currying provides implicit partial evaluation of all functions 5 | 6 | Example: 7 | 8 | Get usually requires two arguments, an index and a collection 9 | >>> from curried import get 10 | >>> get(0, ('a', 'b')) 11 | 'a' 12 | 13 | When we use it in higher order functions we often want to pass a partially 14 | evaluated form 15 | >>> data = [(1, 2), (11, 22), (111, 222)] 16 | >>> list(map(lambda seq: get(0, seq), data)) 17 | [1, 11, 111] 18 | 19 | The curried version allows simple expression of partial evaluation 20 | >>> list(map(get(0), data)) 21 | [1, 11, 111] 22 | 23 | See Also: 24 | funccurry 25 | """ 26 | from . import operator 27 | from .. import ( 28 | apply, 29 | comp, 30 | complement, 31 | compose, 32 | compose_left, 33 | concat, 34 | concatv, 35 | count, 36 | curry, 37 | diff, 38 | first, 39 | flip, 40 | frequencies, 41 | identity, 42 | interleave, 43 | isdistinct, 44 | isiterable, 45 | juxt, 46 | last, 47 | memoize, 48 | merge_sorted, 49 | peek, 50 | pipe, 51 | second, 52 | thread_first, 53 | thread_last, 54 | ) 55 | from .exceptions import merge, merge_with 56 | 57 | # accumulate = curry(accumulate) 58 | # assoc = curry(assoc) 59 | # assoc_in = curry(assoc_in) 60 | # cons = curry(cons) 61 | # countby = curry(countby) 62 | # dissoc = curry(dissoc) 63 | # do = curry(do) 64 | # drop = curry(drop) 65 | # excepts = curry(excepts) 66 | # filter = curry(filter) 67 | # get = curry(get) 68 | # get_in = curry(get_in) 69 | # groupby = curry(groupby) 70 | # interpose = curry(interpose) 71 | # itemfilter = curry(itemfilter) 72 | # itemmap = curry(itemmap) 73 | # iterate = curry(iterate) 74 | # join = curry(join) 75 | # keyfilter = curry(keyfilter) 76 | # keymap = curry(keymap) 77 | # map = curry(map) 78 | # mapcat = curry(mapcat) 79 | # nth = curry(nth) 80 | # partial = curry(partial) 81 | # partition = curry(partition) 82 | # partition_all = curry(partition_all) 83 | # partitionby = curry(partitionby) 84 | # peekn = curry(peekn) 85 | # pluck = curry(pluck) 86 | # random_sample = curry(random_sample) 87 | # reduce = curry(reduce) 88 | # reduceby = curry(reduceby) 89 | # remove = curry(remove) 90 | # sliding_window = curry(sliding_window) 91 | # sorted = curry(sorted) 92 | # tail = curry(tail) 93 | # take = curry(take) 94 | # take_nth = curry(take_nth) 95 | # topk = curry(topk) 96 | # unique = curry(unique) 97 | # update_in = curry(update_in) 98 | # valfilter = curry(valfilter) 99 | # valmap = curry(valmap) 100 | 101 | del exceptions 102 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/toolz/curried/exceptions.py: -------------------------------------------------------------------------------- 1 | from .. import ( 2 | curry, 3 | merge_with, 4 | merge 5 | ) 6 | 7 | 8 | __all__ = ['merge_with', 'merge'] 9 | 10 | 11 | @curry 12 | def merge_with(func, d, *dicts, **kwargs): 13 | return merge_with(func, d, *dicts, **kwargs) 14 | 15 | 16 | @curry 17 | def merge(d, *dicts, **kwargs): 18 | return merge(d, *dicts, **kwargs) 19 | 20 | 21 | merge_with.__doc__ = merge_with.__doc__ 22 | merge.__doc__ = merge.__doc__ 23 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/toolz/curried/operator.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import operator 4 | 5 | from ..functoolz import curry 6 | 7 | 8 | # Tests will catch if/when this needs updated 9 | IGNORE = { 10 | "__abs__", "__index__", "__inv__", "__invert__", "__neg__", "__not__", 11 | "__pos__", "_abs", "abs", "attrgetter", "index", "inv", "invert", 12 | "itemgetter", "neg", "not_", "pos", "truth" 13 | } 14 | locals().update( 15 | {name: f if name in IGNORE else curry(f) 16 | for name, f in vars(operator).items() if callable(f)} 17 | ) 18 | 19 | # Clean up the namespace. 20 | del IGNORE 21 | del curry 22 | del operator 23 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/toolz/recipes.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | from .itertoolz import frequencies, pluck, getter 3 | 4 | 5 | __all__ = ('countby', 'partitionby') 6 | 7 | 8 | def countby(key, seq): 9 | """ Count elements of a collection by a key function 10 | 11 | >>> countby(len, ['cat', 'mouse', 'dog']) 12 | {3: 2, 5: 1} 13 | 14 | >>> def iseven(x): return x % 2 == 0 15 | >>> countby(iseven, [1, 2, 3]) # doctest:+SKIP 16 | {True: 1, False: 2} 17 | 18 | See Also: 19 | groupby 20 | """ 21 | if not callable(key): 22 | key = getter(key) 23 | return frequencies(map(key, seq)) 24 | 25 | 26 | def partitionby(func, seq): 27 | """ Partition a sequence according to a function 28 | 29 | Partition `s` into a sequence of lists such that, when traversing 30 | `s`, every time the output of `func` changes a new list is started 31 | and that and subsequent items are collected into that list. 32 | 33 | >>> is_space = lambda c: c == " " 34 | >>> list(partitionby(is_space, "I have space")) 35 | [('I',), (' ',), ('h', 'a', 'v', 'e'), (' ',), ('s', 'p', 'a', 'c', 'e')] 36 | 37 | >>> is_large = lambda x: x > 10 38 | >>> list(partitionby(is_large, [1, 2, 1, 99, 88, 33, 99, -1, 5])) 39 | [(1, 2, 1), (99, 88, 33, 99), (-1, 5)] 40 | 41 | See also: 42 | partition 43 | groupby 44 | itertools.groupby 45 | """ 46 | return map(tuple, pluck(1, itertools.groupby(seq, key=func))) 47 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/toolz/utils.py: -------------------------------------------------------------------------------- 1 | def raises(err, lamda): 2 | try: 3 | lamda() 4 | return False 5 | except err: 6 | return True 7 | 8 | 9 | no_default = '__no__default__' 10 | -------------------------------------------------------------------------------- /hyperliquid/ccxt/static_dependencies/typing_inspect/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccxt/hyperliquid-python/ff874400423f05b7de35e0086e34c68ed1d40dd5/hyperliquid/ccxt/static_dependencies/typing_inspect/__init__.py -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | setuptools>=60.9.0 2 | certifi>=2018.1.18 3 | requests>=2.18.4 4 | cryptography>=2.6.1 5 | aiohttp<=3.10.11 6 | aiodns>=1.1.1 7 | yarl>=1.7.2 8 | pyopenssl 9 | --------------------------------------------------------------------------------