Skip to content

Commit

Permalink
Merge branch 'development'
Browse files Browse the repository at this point in the history
  • Loading branch information
cptartur committed Oct 14, 2022
2 parents acf9d65 + 10248fe commit 1baf80a
Show file tree
Hide file tree
Showing 23 changed files with 477 additions and 351 deletions.
2 changes: 1 addition & 1 deletion docs/guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ will allow for simple migration for StarkNet.py users.

.. literalinclude:: ../starknet_py/tests/e2e/docs/guide/test_full_node_client.py
:language: python
:lines: 10-13,22-23
:lines: 12-15,24-25
:dedent: 4


Expand Down
2 changes: 1 addition & 1 deletion docs/quickstart.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ there is both synchronous and asynchronous API available.

.. literalinclude:: ../starknet_py/tests/e2e/docs/quickstart/test_using_full_node_client.py
:language: python
:lines: 12-15,24-25
:lines: 14-17,26-27
:dedent: 4

You can see all Full Node Client's methods :ref:`FullNodeClient`.
Expand Down
9 changes: 5 additions & 4 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 3 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "starknet-py"
version = "0.6.2-alpha"
version = "0.6.3-alpha"
description = "A python SDK for StarkNet"
authors = ["Tomasz Rejowski <[email protected]>", "Jakub Ptak <[email protected]>"]
include = ["starknet_py", "starknet_py/utils/crypto/libcrypto_c_exports.*"]
Expand Down Expand Up @@ -41,7 +41,7 @@ pytest-mock = "^3.6.1"
pytest-xdist = "^2.5.0"
web3 = {extras=["tester"], version="6.0.0b4"}
pyright = "^1.1.270"
starknet-devnet = "0.3.1"
starknet-devnet = "^0.3.3"

[tool.poe.tasks]
test = ["test_unit", "test_e2e", "test_docs"]
Expand Down Expand Up @@ -107,6 +107,5 @@ markers = [
include = ["starknet_py/"]
exclude = [
"**/__pycache__",
"starknet_py/tests",
"**/*_test.py",
"starknet_py/tests/e2e/docs",
]
6 changes: 3 additions & 3 deletions starknet_py/compile/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import os
import typing
from pathlib import Path
from typing import List, NewType, Optional, Tuple, Union
from typing import List, Optional, Tuple, Union

from starkware.starknet.services.api.contract_class import ContractClass
from starkware.cairo.lang.compiler.constants import MAIN_SCOPE, LIBS_DIR_ENVVAR
Expand All @@ -17,8 +17,8 @@
)
from starkware.starknet.compiler.starknet_pass_manager import starknet_pass_manager

CairoSourceCode = NewType("CairoSourceCode", str)
CairoFilename = NewType("CairoFilename", str)
CairoSourceCode = str
CairoFilename = str
StarknetCompilationSource = Union[CairoSourceCode, List[CairoFilename]]


Expand Down
13 changes: 8 additions & 5 deletions starknet_py/compile/compiler_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
from starkware.starknet.services.api.contract_class import ContractClass
from starkware.starknet.compiler.validation_utils import PreprocessorError

from starknet_py.compile.compiler import Compiler, create_contract_class
from starknet_py.compile.compiler import (
Compiler,
create_contract_class,
)
from starknet_py.tests.e2e.conftest import contracts_dir

directory = os.path.dirname(__file__)
Expand All @@ -31,7 +34,7 @@ def test_compile_direct_load():

def test_compile_file_load():
output_file_str = Compiler(
contract_source=[test_file_path.resolve().absolute()]
contract_source=[str(test_file_path.resolve().absolute())]
).compile_contract()
output_json = json.loads(output_file_str)

Expand All @@ -54,7 +57,7 @@ def test_throws_on_compile_with_wrong_extension():

def test_compile_with_search_path():
output_file_str = Compiler(
contract_source=[base_contract_path.resolve().absolute()],
contract_source=[str(base_contract_path.resolve().absolute())],
cairo_path=[str(contracts_dir)],
).compile_contract()
output_json = json.loads(output_file_str)
Expand All @@ -65,7 +68,7 @@ def test_compile_with_search_path():
def test_compile_with_env_var(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv(LIBS_DIR_ENVVAR, str(contracts_dir))
output_file_str = Compiler(
contract_source=[base_contract_path.resolve().absolute()]
contract_source=[str(base_contract_path.resolve().absolute())]
).compile_contract()
output_json = json.loads(output_file_str)

Expand All @@ -75,7 +78,7 @@ def test_compile_with_env_var(monkeypatch: pytest.MonkeyPatch):
def test_throws_on_compile_without_search_path_and_env_var():
with pytest.raises(ImportLoaderError) as m_err:
Compiler(
contract_source=[base_contract_path.resolve().absolute()]
contract_source=[str(base_contract_path.resolve().absolute())]
).compile_contract()
assert "Could not find module 'inner.inner'." in str(m_err.value)

Expand Down
13 changes: 13 additions & 0 deletions starknet_py/net/client_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ class TransactionType(Enum):
INVOKE = "INVOKE"
DEPLOY = "DEPLOY"
DECLARE = "DECLARE"
L1_HANDLER = "L1_HANDLER"


@dataclass
Expand Down Expand Up @@ -129,6 +130,18 @@ class DeployTransaction(Transaction):
class_hash: int


@dataclass
class L1HandlerTransaction(Transaction):
"""
Dataclass representing l1 handler transaction
"""

contract_address: int
calldata: List[int]
entry_point_selector: int
nonce: Optional[int] = None


class TransactionStatus(Enum):
"""
Enum representing transaction statuses
Expand Down
31 changes: 13 additions & 18 deletions starknet_py/net/http_client.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
from abc import abstractmethod, ABC
from contextlib import nullcontext
from enum import Enum
from typing import Optional

import aiohttp
from aiohttp import ClientSession, ClientResponse

from starknet_py.net.client_errors import ClientError
Expand All @@ -15,35 +13,32 @@ class HttpMethod(Enum):


class HttpClient(ABC):
def __init__(self, url, session: Optional[aiohttp.ClientSession] = None):
def __init__(self, url, session: Optional[ClientSession] = None):
self.url = url
self.session = session

def http_session(self) -> ClientSession:
if self.session is not None:
# noinspection PyTypeChecker
return nullcontext(self.session) # pyright: ignore
return aiohttp.ClientSession()

async def request(
self,
address: str,
http_method: HttpMethod,
params: Optional[dict] = None,
payload: Optional[dict] = None,
):
async with self.http_session() as session:
return await self._make_request(
session=session,
address=address,
http_method=http_method,
params=params, # pyright: ignore
payload=payload, # pyright: ignore
)
kwargs = {
"address": address,
"http_method": http_method,
"params": params,
"payload": payload,
}
if self.session:
return await self._make_request(session=self.session, **kwargs)

async with ClientSession() as session:
return await self._make_request(session=session, **kwargs)

async def _make_request(
self,
session: aiohttp.ClientSession,
session: ClientSession,
address: str,
http_method: HttpMethod,
params: dict,
Expand Down
7 changes: 5 additions & 2 deletions starknet_py/net/l1/messaging_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import pytest
import web3
from eth_abi.codec import ABICodec
from eth_typing import HexStr
from hexbytes import HexBytes

from starkware.starknet.services.api.feeder_gateway.response_objects import (
Expand Down Expand Up @@ -138,7 +139,9 @@ def get_tx_receipt(_tx_hash):
}
)

w3_mock_receipt.eth.get_transaction_receipt = get_tx_receipt
# Ignore typing, because get_tx_receipt return type
# is slightly incompatible with eth.get_transaction_receipt return type
w3_mock_receipt.eth.get_transaction_receipt = get_tx_receipt # pyright: ignore

mock_l2_client = Mock()
# L2 Mock
Expand All @@ -164,7 +167,7 @@ async def get_l2_tx_receipt(_tx_hash) -> TransactionReceipt:
client=mock_l2_client,
)
eth_to_sn_msgs = await MessageToStarknet.from_tx_hash(
tx_hash="0x123123123",
tx_hash=HexStr("0x123123123"),
web3=w3_mock_receipt,
)

Expand Down
3 changes: 2 additions & 1 deletion starknet_py/net/models/address_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ def test_parse_address(input_addr, output):

def test_parse_invalid_address():
with pytest.raises(TypeError) as excinfo:
# Ignore typing, because it is an error check (float can't be passed here)
# noinspection PyTypeChecker
parse_address(0.22)
parse_address(0.22) # pyright: ignore

assert "address format" in str(excinfo.value)

Expand Down
13 changes: 13 additions & 0 deletions starknet_py/net/schemas/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
Event,
DeclareTransactionResponse,
DeployTransactionResponse,
L1HandlerTransaction,
)
from starknet_py.net.schemas.common import (
Felt,
Expand Down Expand Up @@ -108,12 +109,24 @@ def make_dataclass(self, data, **kwargs) -> DeclareTransaction:
return DeclareTransaction(**data)


class L1HandlerTransactionSchema(TransactionSchema):
contract_address = Felt(data_key="contract_address", required=True)
calldata = fields.List(Felt(), data_key="calldata", required=True)
entry_point_selector = Felt(data_key="entry_point_selector", required=True)
nonce = Felt(data_key="nonce", load_default=None)

@post_load
def make_dataclass(self, data, **kwargs) -> L1HandlerTransaction:
return L1HandlerTransaction(**data)


class TypesOfTransactionsSchema(OneOfSchema):
type_field = "type"
type_schemas = {
"INVOKE_FUNCTION": InvokeTransactionSchema,
"DECLARE": DeclareTransactionSchema,
"DEPLOY": DeployTransactionSchema,
"L1_HANDLER": L1HandlerTransactionSchema,
}


Expand Down
24 changes: 13 additions & 11 deletions starknet_py/tests/e2e/account/account_client_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,9 @@ async def test_create_account_client_with_private_key(network):
acc_client = await AccountClient.create_account(
client=gt_client, private_key=private_key, chain=StarknetChainId.TESTNET
)
assert acc_client.signer.private_key == private_key

# Ignore typing, because BaseSigner doesn't have private_key property, but this one has
assert acc_client.signer.private_key == private_key # pyright: ignore
assert acc_client.signer is not None
assert acc_client.address is not None

Expand All @@ -155,19 +157,19 @@ async def test_create_account_client_with_signer(network):


@pytest.mark.asyncio
async def test_sending_multicall(account_client, map_contract):
for (k, v) in ((20, 20), (30, 30)):
calls = [
map_contract.functions["put"].prepare(key=10, value=10),
map_contract.functions["put"].prepare(key=k, value=v),
]
@pytest.mark.parametrize("key, val", [(20, 20), (30, 30)])
async def test_sending_multicall(account_client, map_contract, key, val):
calls = [
map_contract.functions["put"].prepare(key=10, value=10),
map_contract.functions["put"].prepare(key=key, value=val),
]

res = await account_client.execute(calls, int(1e20))
await account_client.wait_for_tx(res.transaction_hash)
res = await account_client.execute(calls, int(1e20))
await account_client.wait_for_tx(res.transaction_hash)

(value,) = await map_contract.functions["get"].call(key=k)
(value,) = await map_contract.functions["get"].call(key=key)

assert value == v
assert value == val


@pytest.mark.run_on_devnet
Expand Down
Loading

0 comments on commit 1baf80a

Please sign in to comment.