Git Product home page Git Product logo

pytonapi's Issues

Wrong error format

Hello!

I've discovered a minor bug: the error content in case of json.JSONDecodeError (line 73) is being returned in a set format instead of a dictionary.

try:
content = response.json()
except httpx.ResponseNotRead:
content_bytes = await response.aread()
content_decoded = content_bytes.decode()
try:
content = json.loads(content_decoded)
except json.JSONDecodeError:
content = {"error": content_decoded}
except json.JSONDecodeError:
content = {"error", response.text}
except Exception as e:
raise TONAPIError(f"Failed to read response content: {e}")

This is causing an AttributeError here

error = content.get("error", content)

Missing method to "Get Jetton balance by owner address"

pytonapi.tonapi.methods.accounts.AccountsMethod is missing the method get_jetton_balance(account_id, jetton_id) corresponding to the /v2/accounts/{account_id}/jettons/{jetton_id} API endpoint.
There is only the method get_jettons_balances(account_id) that fetches balances for all Jettons but no method to fetch the balance for a particular Jetton

Wrong received `int` type in `liteserver.get_account_state`

Hi!

I try to get the raw account state using liteserver method as follows:

from pytonapi import AsyncTonapi

client = AsyncTonapi(api_key="<API_KEY>")

account_address = "EQCqFPpSLtcstURtrXLRCv9wyjfrw7_44_nwvD8JiSmSjbUI"

state = await client.liteserver.get_account_state(account_address)

And I get the following error:

---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
Cell In[24], line 1
----> 1 state_tonapi = await client.liteserver.get_account_state(account_address)

File [/usr/local/lib/python3.10/site-packages/pytonapi/async_tonapi/methods/liteserver.py:121](http://localhost:8889/usr/local/lib/python3.10/site-packages/pytonapi/async_tonapi/methods/liteserver.py#line=120), in LiteserverMethod.get_account_state(self, account_address, target_block)
    118 params = {"target_block": target_block} if target_block else {}
    119 response = await self._get(method=method, params=params)
--> 121 return RawAccountState(**response)

File [/usr/local/lib/python3.10/site-packages/pydantic/v1/main.py:341](http://localhost:8889/usr/local/lib/python3.10/site-packages/pydantic/v1/main.py#line=340), in BaseModel.__init__(__pydantic_self__, **data)
    339 values, fields_set, validation_error = validate_model(__pydantic_self__.__class__, data)
    340 if validation_error:
--> 341     raise validation_error
    342 try:
    343     object_setattr(__pydantic_self__, '__dict__', values)

ValidationError: 1 validation error for RawAccountState
shardblk -> shard
  value is not a valid integer (type=type_error.integer)

I'm pretty sure this error stems from int annotation here:

I tried to do the simple HTTP request without Pydantic response parsing like that:

response = await client._get(method=f"v2/liteserver/get_account_state/{account_address}", params={})

and get the following response

{'id': {'workchain': -1,
  'shard': '8000000000000000',
  'seqno': 37496117,
  'root_hash': '01166afa4bcb8b8bc65499ca755f434f0cfc4d13b7e90eb42ed436a831853e45',
  'file_hash': 'fd4620e8510e0d0b657f7edc6e3cc9f505fac97f63f8f79c8d9c9ee4082f5dd0'},
 'shardblk': {'workchain': 0,
  'shard': 'c000000000000000',
  'seqno': 43158333,
  'root_hash': 'bd96247321a94c9d17945286f85a13e296e2a4ce932764a6c95ddd0126e60bc3',
  'file_hash': 'f0728e43f52308da96a88b6c664a5b115ec01d51c499e8e057e83da901a9b322'},
 'shard_proof':
  .....

So response["shardblk"]["shard"] is indeed not an integer, at least not a decimal one.

I would be grateful if someone can help/share the experience with it.

@nessshon I'm also happy to make a PR, but I'm not quite sure how we should fix it.

JSONDecodeError on client.blockchain.send_message method

Traceback (most recent call last):
File "/Users/username/app/venv/lib/python3.11/site-packages/pytonapi/async_tonapi/client.py", line 64, in __read_content
content = response.json()
^^^^^^^^^^^^^^^
File "/Users/username/app/venv/lib/python3.11/site-packages/httpx/_models.py", line 764, in json
return jsonlib.loads(self.content, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.6/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/init.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.6/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.6/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/username/app/main.py", line 124, in
asyncio.run(main_loop())
File "/usr/local/Cellar/[email protected]/3.11.6/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.6/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.6/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "/Users/username/app/main.py", line 119, in main_loop
print(await client.blockchain.send_message({'boc': boc}))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/username/app/venv/lib/python3.11/site-packages/pytonapi/async_tonapi/methods/blockchain.py", line 238, in send_message
response = await self._post(method=method, body=body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/username/app/venv/lib/python3.11/site-packages/pytonapi/async_tonapi/client.py", line 264, in _post
return await request("POST", method, headers, params=params, body=body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/username/app/venv/lib/python3.11/site-packages/pytonapi/async_tonapi/client.py", line 187, in _request
return await self.__process_response(response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/username/app/venv/lib/python3.11/site-packages/pytonapi/async_tonapi/client.py", line 80, in __process_response
content = await self.__read_content(response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/username/app/venv/lib/python3.11/site-packages/pytonapi/async_tonapi/client.py", line 68, in __read_content
raise TONAPIError(f"Failed to read response content: {e}")
pytonapi.exceptions.TONAPIError: Failed to read response content: Expecting value: line 1 column 1 (char 0)

python3.6.11
pytonapi=0.2.3

pytonapi.exceptions.TONAPINotFoundError: entity not found

Sometimes, when I set message listener, I get such an error on incoming transaction. I even have bought Lite payment plan but the issue persists. I set my handler just like in example.

async def set_transaction_handler():
    tonapi = AsyncTonapi(api_key=TONAPI_KEY)

    # Subscribe to transaction events for the specified accounts
    await tonapi.sse.subscribe_to_transactions(
        accounts=ACCOUNTS, handler=handler, args=(tonapi,)
    )

async def handler(event: TransactionEventData, tonapi: AsyncTonapi) -> None:
    """
    Handle SSEvent for transactions.

    :param event: The SSEvent object containing transaction details.
    :param tonapi: An instance of AsyncTonapi for interacting with TON API.
    """
    print("Transaction received")

    trace = await tonapi.traces.get_trace(event.tx_hash)
Traceback (most recent call last):
  File "/home/b4cksl4sh/PycharmProjects/autoWallet/main.py", line 96, in <module>
    asyncio.run(set_transaction_handler())
  File "/usr/lib/python3.12/asyncio/runners.py", line 194, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/asyncio/base_events.py", line 687, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/home/b4cksl4sh/PycharmProjects/autoWallet/main.py", line 32, in set_transaction_handler
    await tonapi.sse.subscribe_to_transactions(
  File "/home/b4cksl4sh/PycharmProjects/autoWallet/.venv/lib/python3.12/site-packages/pytonapi/async_tonapi/methods/sse.py", line 41, in subscribe_to_transactions
    result = await handler(event, *args)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/b4cksl4sh/PycharmProjects/autoWallet/main.py", line 79, in handler
    trace = await tonapi.traces.get_trace(event.tx_hash)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/b4cksl4sh/PycharmProjects/autoWallet/.venv/lib/python3.12/site-packages/pytonapi/async_tonapi/methods/traces.py", line 21, in get_trace
    response_data = await self._get(method=method)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/b4cksl4sh/PycharmProjects/autoWallet/.venv/lib/python3.12/site-packages/pytonapi/async_tonapi/client.py", line 253, in _get
    return await request("GET", method, headers, params=params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/b4cksl4sh/PycharmProjects/autoWallet/.venv/lib/python3.12/site-packages/pytonapi/async_tonapi/client.py", line 196, in _request
    return await self.__process_response(response)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/b4cksl4sh/PycharmProjects/autoWallet/.venv/lib/python3.12/site-packages/pytonapi/async_tonapi/client.py", line 101, in __process_response
    raise error_class(error_message)
pytonapi.exceptions.TONAPINotFoundError: entity not found

Sending TON

Hello, how can I send a TON to another person using your library?

fix ClientConnectorCertificateError

  1. Add ssl=False to the AsyncTonapiClient class, to the _request(...) method.
async with await session.get(f"{self.__base_url}{method}",
                      params=params, ssl=False
                      ) as response:
  1. Write a description that your library only works with python above 3.10

Thanks ๐Ÿ‘

lack of raw_body property in Message schema

Hi! Are there any potential pitfalls with adding the "raw_body" property to the Message class in schemas? Not to make any additional requests to tonapi when raw body is actually needed. As i understand its just one line addition. Could you please add it? Or i can make a pr if you wish.

httpx.ResponseNotRead: Attempted to access streaming response content, without having called `read()`

Hello, I've got an error while using tonapi.sse.subscribe_to_transactions when "HTTP/1.1 502 Bad Gateway" occurs.

My code snippet:

async def handler(event: TransactionEventData, tonapi: AsyncTonapi) -> None:
    pass

async def main() -> None:
    tonapi = AsyncTonapi(api_key=API_KEY, timeout=60)
    await tonapi.sse.subscribe_to_transactions(
        accounts=ACCOUNTS, handler=handler, args=(tonapi,)
    )
    

if __name__ == "__main__":
    asyncio.run(main())

I've also found a possible solution here: https://github.com/encode/httpx/discussions/1856

Stacktrace:

Traceback (most recent call last):
  File "D:\Projects\WhaleWatch\oapi.py", line 112, in main
    await tonapi.sse.subscribe_to_transactions(
  File "D:\Projects\WhaleWatch\venv\lib\site-packages\pytonapi\async_tonapi\methods\sse.py", line 25, in subscribe_to_transactions
    async for data in self._subscribe(method=method, params=params):
  File "D:\Projects\WhaleWatch\venv\lib\site-packages\pytonapi\async_tonapi\client.py", line 118, in _subscribe
    await self.__process_response(response)
  File "D:\Projects\WhaleWatch\venv\lib\site-packages\pytonapi\async_tonapi\client.py", line 80, in __process_response
    content = await self.__read_content(response)
  File "D:\Projects\WhaleWatch\venv\lib\site-packages\pytonapi\async_tonapi\client.py", line 66, in __read_content
    content = {"error": response.text}
  File "D:\Projects\WhaleWatch\venv\lib\site-packages\httpx\_models.py", line 576, in text
    content = self.content
  File "D:\Projects\WhaleWatch\venv\lib\site-packages\httpx\_models.py", line 570, in content
    raise ResponseNotRead()
httpx.ResponseNotRead: Attempted to access streaming response content, without having called `read()`.

Send Ton

Traceback (most recent call last):
File "C:\Users\maprod-pc\IdeaProjects\maprod-pyramid\crypto.py", line 58, in
asyncio.run(main())
File "C:\Users\maprod-pc\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\maprod-pc\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\maprod-pc\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\maprod-pc\IdeaProjects\maprod-pyramid\crypto.py", line 33, in main
method_result = await tonapi.blockchain.execute_get_method(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\maprod-pc\AppData\Local\Programs\Python\Python311\Lib\site-packages\pytonapi\async_tonapi\methods\blockchain.py", line 226, in execute_get_method
response = await self._get(method=method)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\maprod-pc\AppData\Local\Programs\Python\Python311\Lib\site-packages\pytonapi\async_tonapi\client.py", line 253, in _get
return await request("GET", method, headers, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\maprod-pc\AppData\Local\Programs\Python\Python311\Lib\site-packages\pytonapi\async_tonapi\client.py", line 196, in _request
return await self.__process_response(response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\maprod-pc\AppData\Local\Programs\Python\Python311\Lib\site-packages\pytonapi\async_tonapi\client.py", line 101, in __process_response
raise error_class(error)
pytonapi.exceptions.TONAPINotFoundError: entity not found

tonapi.blockchain.send_message(data) Always Returns False

When calling the send_message function from tonapi.blockchain with the provided data, the transaction_result always returns False, regardless of the actual outcome of the transaction. This behavior is observed whether the transaction was successful or an error occurred.

        query = wallet.create_transfer_message(
            to_addr=destination_address,
            amount=transfer_amount,
            payload=payload,
            seqno=seqno,
        )

        message_boc = bytes_to_b64str(query["message"].to_boc(False))

        data = {'boc': message_boc}
        transaction_result = await tonapi.blockchain.send_message(data)
        print(transaction_result)

pydantic.v1.error_wrappers.ValidationError

I'v got an error:

Error: 1 validation error for Trace
children -> 0 -> transaction -> out_msgs -> 1 -> init -> library
field required (type=value_error.missing) on tx 6fa11e0361f5a981724dc44de172464884746d7d1d72f25a5fe3e251b7727658

One of out_msgs field didn't have an field init at all but usually does (for example in a4a644cad11d72a8b6a9fc1537488e7d5d9c11aec6f18e17a43d6d96ea4c925c init just null)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.