TonX


NameTonX JSON
Version 0.1.5 PyPI version JSON
download
home_pagehttps://github.com/AYMENJD/tonx
SummaryA user-friendly Python library for interacting with TON (The Open Network), offering convenient payment handling and much more.
upload_time2023-12-27 14:18:01
maintainer
docs_urlNone
authorAYMEN Mohammed
requires_python>=3.9
licenseMIT
keywords ton telegram cryptocurrency blockchain tonlib payments crypto digital currency decentralized smart contracts dapp ethereum bitcoin cryptocurrency payments crypto wallet transaction secure privacy token block explorer smart contract development
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # TonX [![Version](https://img.shields.io/pypi/v/TonX?style=flat&logo=pypi)](https://pypi.org/project/TonX) [![Downloads](https://static.pepy.tech/personalized-badge/TonX?period=month&units=none&left_color=grey&right_color=brightgreen&left_text=Downloads)](https://pepy.tech/project/tonx)

TonX is an asynchronous [**Tonlib**](https://github.com/ton-blockchain/ton) wrapper for **TON** community written in **Python**.

### Features
- Easy, **Fast** and **Powerful**
- Fully **asynchronous**
- Supports **Payments**, **Wallet Tracker**, [**Tonlib**](https://github.com/ton-blockchain/ton) **types**/**functions** and much **more**.


### Requirements
> NOTE: [TonX](https://github.com/AYMENJD/tonx) will automatically attempt to download the correct pre-built binary of tonlibjson from  [**Tonlib Releases**](https://github.com/ton-blockchain/ton/releases)

- Python 3.9+

### Installation
You can install TonX using pip:

```bash
pip install tonx
```

To install with payments support, use:

```bash
pip install tonx[payments]
```

To install the development version from Github, use the following command:

```bash
pip install git+https://github.com/AYMENJD/tonx.git
```

## Examples

### Basic usage
Getting wallet **balance** of [**Fragment**](https://fragment.com):

```python
from tonx import Client, types, utils
from urllib.request import urlopen
import json, asyncio


async def main():
    ton_config = json.loads(
        urlopen("https://ton-blockchain.github.io/global.config.json").read()
    )  # Main net

    async with Client(
        config=ton_config,
        keystore=types.KeyStoreTypeDirectory("tonlib-db/"),
    ) as client:
        account_state = await client.getAccountState(
            types.AccountAddress("EQBAjaOyi2wGWlk-EDkSabqqnF-MrrwMadnwqrurKpkla9nE")
        )

        if account_state.getType() != "error":
            balance_in_toncoin = utils.from_nanograms(account_state.balance)

            print(
                f"Fragment.com wallet has {utils.truncate_zeros(balance_in_toncoin)} TON"
            )
        else:
            print(
                f"Something went wrong: {account_state.code} - {account_state.message}"
            )


asyncio.run(main())
```

### Payments
Accepting and handling **payments** in **TON**:

```python
from tonx import Client, types, utils
from tonx.payments import Payments, Invoice
from urllib.request import urlopen
import json, asyncio, logging

logging.basicConfig(
    level=logging.INFO,
    format="[%(levelname)s][p %(process)d %(threadName)s][%(created)f][%(filename)s:%(lineno)d][%(funcName)s]  %(message)s",
)


async def main():
    # ton_config = json.loads(
    #     urlopen("https://ton-blockchain.github.io/global.config.json").read()
    # ) # Main net
    ton_config = json.loads(
        urlopen("https://ton-blockchain.github.io/testnet-global.config.json").read()
    )  #  Test net

    client = Client(
        config=ton_config,
        keystore=types.KeyStoreTypeDirectory("tonlib-db/"),
    )
    payments = Payments(
        client=client,
        account_address=types.AccountAddress(
            "WALLET_ADDRESS"  # Wallet address that will receive the payments
        ),
    )

    @payments.on_invoicePayment()
    async def invoice_payment_handler(client, invoice: Invoice):
        if invoice.is_completed:
            payment_info = (
                f"Payment for Invoice #{invoice.id}\n"
                f"Amount: {utils.truncate_zeros(invoice.paid_amount)} TON\n"
                f"From: {utils.Address.normalize(invoice.paid_by_address)}\n"
                f"Is completed: {invoice.is_completed}\n"
                f"Extra: {invoice.extra}\n\n"
            )
        elif invoice.is_expired:
            payment_info = (
                f"Payment for expired Invoice #{invoice.id}\n"
                f"Amount: {utils.truncate_zeros(invoice.paid_amount)} TON\n"
                f"From: {utils.Address.normalize(invoice.paid_by_address)}\n"
                f"Is completed: {invoice.is_completed}\n"
                f"Extra: {invoice.extra}\n\n"
            )
        print(payment_info)

    await client.start(payments)

    # Create an example invoice
    invoice_1 = await payments.createInvoice(
        amount=0.05,
        comment="This is a test payment for TonX\n\n",
        extra={
            "name": "AYMEN",
            "user_id": 1088394097,
        },  # Extra data that will be stored with the invoice
        ttl=None,  # Invoice is valid for every with no expire time (NOTE: the default value for ttl is 3600 seconds a.k.a 1 hour)
    )

    invoice_2 = await payments.createInvoice(
        0.05,
        "This is a test payment for TonX\n\n",
        extra={"name": "AWM", "user_id": 39809485},
        ttl=300,  #  Invoice is valid for 5 minutes (the minimum value)
    )

    print(f"Payment link for invoice 1 ({invoice_1.id}): {invoice_1.payment_link}")
    print(f"Payment link for invoice 2 ({invoice_2.id}): {invoice_2.payment_link}")
    print()

    await client.idle(register_signal_handlers=True)


asyncio.run(main())
```

### Tracking
An example of **Tracking** a wallet **transactions**, for example [**@Wallet**](https://t.me/Wallet) Bot

```python
from tonx import Client, types, utils
from tonx.payments import Payments
from urllib.request import urlopen
import json, logging

logging.basicConfig(
    level=logging.INFO,
    format="[%(levelname)s][p %(process)d %(threadName)s][%(created)f][%(filename)s:%(lineno)d][%(funcName)s]  %(message)s",
)

ton_config = json.loads(
    urlopen("https://ton-blockchain.github.io/global.config.json").read()
)  # Main net

client = Client(
    config=ton_config,
    keystore=types.KeyStoreTypeDirectory("tonlib-db/"),
)
payments = Payments(
    client=client,
    account_address=types.AccountAddress(
        "EQBDanbCeUqI4_v-xrnAN0_I2wRvEIaLg1Qg2ZN5c6Zl1KOh"  # Wallet to watch transactions, for example t.me/Wallet address
    ),
)


@payments.on_incomingTransaction(
    filter_fn=lambda _, transaction: utils.from_nanograms(transaction.in_msg.value)
    >= 1  # Handle only transaction that is 1+ TON
)
async def handle_incoming_transactions(_, transaction: types.RawTransaction):
    comment = None
    if transaction.in_msg.msg_data.getType() == "msg.dataText":
        comment = transaction.in_msg.msg_data.text.decode()

    transaction_info = (
        f"Received a transaction:\n"
        f"Amount: `{utils.truncate_zeros(utils.from_nanograms(transaction.in_msg.value))} TON`\n"
        f"From: {utils.Address.normalize(transaction.in_msg.source)}\n"
        f"Comment: {comment}\n"
    )
    print(transaction_info)


@payments.on_outgoingTransaction()
async def handle_outgoing_transactions(_, transaction: types.RawTransaction):
    comment = None
    if transaction.out_msgs[0].msg_data.getType() == "msg.dataText":
        comment = transaction.out_msgs[0].msg_data.text.decode()

    transaction_info = (
        f"Sending "
        f"`{utils.truncate_zeros(utils.from_nanograms(transaction.out_msgs[0].value))} TON` "
        f"to `{utils.Address.normalize(transaction.out_msgs[0].destination)}` "
        f"({comment})\n"
    )
    print(transaction_info)


client.run(payments)
```
# License

MIT [License](https://github.com/AYMENJD/tonx/blob/main/LICENSE)



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/AYMENJD/tonx",
    "name": "TonX",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": "",
    "keywords": "ton,telegram,cryptocurrency,blockchain,tonlib,payments,crypto,digital currency,decentralized,smart contracts,dApp,Ethereum,Bitcoin,cryptocurrency payments,crypto wallet,transaction,secure,privacy,token,block explorer,smart contract development",
    "author": "AYMEN Mohammed",
    "author_email": "let.me.code.safe@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/50/c5/7bf11540ef10ea2aebbfb1f4608114e2e2af8bb30bef62aa46a07d9fe07b/TonX-0.1.5.tar.gz",
    "platform": null,
    "description": "# TonX [![Version](https://img.shields.io/pypi/v/TonX?style=flat&logo=pypi)](https://pypi.org/project/TonX) [![Downloads](https://static.pepy.tech/personalized-badge/TonX?period=month&units=none&left_color=grey&right_color=brightgreen&left_text=Downloads)](https://pepy.tech/project/tonx)\n\nTonX is an asynchronous [**Tonlib**](https://github.com/ton-blockchain/ton) wrapper for **TON** community written in **Python**.\n\n### Features\n- Easy, **Fast** and **Powerful**\n- Fully **asynchronous**\n- Supports **Payments**, **Wallet Tracker**, [**Tonlib**](https://github.com/ton-blockchain/ton) **types**/**functions** and much **more**.\n\n\n### Requirements\n> NOTE: [TonX](https://github.com/AYMENJD/tonx) will automatically attempt to download the correct pre-built binary of tonlibjson from  [**Tonlib Releases**](https://github.com/ton-blockchain/ton/releases)\n\n- Python 3.9+\n\n### Installation\nYou can install TonX using pip:\n\n```bash\npip install tonx\n```\n\nTo install with payments support, use:\n\n```bash\npip install tonx[payments]\n```\n\nTo install the development version from Github, use the following command:\n\n```bash\npip install git+https://github.com/AYMENJD/tonx.git\n```\n\n## Examples\n\n### Basic usage\nGetting wallet **balance** of [**Fragment**](https://fragment.com):\n\n```python\nfrom tonx import Client, types, utils\nfrom urllib.request import urlopen\nimport json, asyncio\n\n\nasync def main():\n    ton_config = json.loads(\n        urlopen(\"https://ton-blockchain.github.io/global.config.json\").read()\n    )  # Main net\n\n    async with Client(\n        config=ton_config,\n        keystore=types.KeyStoreTypeDirectory(\"tonlib-db/\"),\n    ) as client:\n        account_state = await client.getAccountState(\n            types.AccountAddress(\"EQBAjaOyi2wGWlk-EDkSabqqnF-MrrwMadnwqrurKpkla9nE\")\n        )\n\n        if account_state.getType() != \"error\":\n            balance_in_toncoin = utils.from_nanograms(account_state.balance)\n\n            print(\n                f\"Fragment.com wallet has {utils.truncate_zeros(balance_in_toncoin)} TON\"\n            )\n        else:\n            print(\n                f\"Something went wrong: {account_state.code} - {account_state.message}\"\n            )\n\n\nasyncio.run(main())\n```\n\n### Payments\nAccepting and handling **payments** in **TON**:\n\n```python\nfrom tonx import Client, types, utils\nfrom tonx.payments import Payments, Invoice\nfrom urllib.request import urlopen\nimport json, asyncio, logging\n\nlogging.basicConfig(\n    level=logging.INFO,\n    format=\"[%(levelname)s][p %(process)d %(threadName)s][%(created)f][%(filename)s:%(lineno)d][%(funcName)s]  %(message)s\",\n)\n\n\nasync def main():\n    # ton_config = json.loads(\n    #     urlopen(\"https://ton-blockchain.github.io/global.config.json\").read()\n    # ) # Main net\n    ton_config = json.loads(\n        urlopen(\"https://ton-blockchain.github.io/testnet-global.config.json\").read()\n    )  #  Test net\n\n    client = Client(\n        config=ton_config,\n        keystore=types.KeyStoreTypeDirectory(\"tonlib-db/\"),\n    )\n    payments = Payments(\n        client=client,\n        account_address=types.AccountAddress(\n            \"WALLET_ADDRESS\"  # Wallet address that will receive the payments\n        ),\n    )\n\n    @payments.on_invoicePayment()\n    async def invoice_payment_handler(client, invoice: Invoice):\n        if invoice.is_completed:\n            payment_info = (\n                f\"Payment for Invoice #{invoice.id}\\n\"\n                f\"Amount: {utils.truncate_zeros(invoice.paid_amount)} TON\\n\"\n                f\"From: {utils.Address.normalize(invoice.paid_by_address)}\\n\"\n                f\"Is completed: {invoice.is_completed}\\n\"\n                f\"Extra: {invoice.extra}\\n\\n\"\n            )\n        elif invoice.is_expired:\n            payment_info = (\n                f\"Payment for expired Invoice #{invoice.id}\\n\"\n                f\"Amount: {utils.truncate_zeros(invoice.paid_amount)} TON\\n\"\n                f\"From: {utils.Address.normalize(invoice.paid_by_address)}\\n\"\n                f\"Is completed: {invoice.is_completed}\\n\"\n                f\"Extra: {invoice.extra}\\n\\n\"\n            )\n        print(payment_info)\n\n    await client.start(payments)\n\n    # Create an example invoice\n    invoice_1 = await payments.createInvoice(\n        amount=0.05,\n        comment=\"This is a test payment for TonX\\n\\n\",\n        extra={\n            \"name\": \"AYMEN\",\n            \"user_id\": 1088394097,\n        },  # Extra data that will be stored with the invoice\n        ttl=None,  # Invoice is valid for every with no expire time (NOTE: the default value for ttl is 3600 seconds a.k.a 1 hour)\n    )\n\n    invoice_2 = await payments.createInvoice(\n        0.05,\n        \"This is a test payment for TonX\\n\\n\",\n        extra={\"name\": \"AWM\", \"user_id\": 39809485},\n        ttl=300,  #  Invoice is valid for 5 minutes (the minimum value)\n    )\n\n    print(f\"Payment link for invoice 1 ({invoice_1.id}): {invoice_1.payment_link}\")\n    print(f\"Payment link for invoice 2 ({invoice_2.id}): {invoice_2.payment_link}\")\n    print()\n\n    await client.idle(register_signal_handlers=True)\n\n\nasyncio.run(main())\n```\n\n### Tracking\nAn example of **Tracking** a wallet **transactions**, for example [**@Wallet**](https://t.me/Wallet) Bot\n\n```python\nfrom tonx import Client, types, utils\nfrom tonx.payments import Payments\nfrom urllib.request import urlopen\nimport json, logging\n\nlogging.basicConfig(\n    level=logging.INFO,\n    format=\"[%(levelname)s][p %(process)d %(threadName)s][%(created)f][%(filename)s:%(lineno)d][%(funcName)s]  %(message)s\",\n)\n\nton_config = json.loads(\n    urlopen(\"https://ton-blockchain.github.io/global.config.json\").read()\n)  # Main net\n\nclient = Client(\n    config=ton_config,\n    keystore=types.KeyStoreTypeDirectory(\"tonlib-db/\"),\n)\npayments = Payments(\n    client=client,\n    account_address=types.AccountAddress(\n        \"EQBDanbCeUqI4_v-xrnAN0_I2wRvEIaLg1Qg2ZN5c6Zl1KOh\"  # Wallet to watch transactions, for example t.me/Wallet address\n    ),\n)\n\n\n@payments.on_incomingTransaction(\n    filter_fn=lambda _, transaction: utils.from_nanograms(transaction.in_msg.value)\n    >= 1  # Handle only transaction that is 1+ TON\n)\nasync def handle_incoming_transactions(_, transaction: types.RawTransaction):\n    comment = None\n    if transaction.in_msg.msg_data.getType() == \"msg.dataText\":\n        comment = transaction.in_msg.msg_data.text.decode()\n\n    transaction_info = (\n        f\"Received a transaction:\\n\"\n        f\"Amount: `{utils.truncate_zeros(utils.from_nanograms(transaction.in_msg.value))} TON`\\n\"\n        f\"From: {utils.Address.normalize(transaction.in_msg.source)}\\n\"\n        f\"Comment: {comment}\\n\"\n    )\n    print(transaction_info)\n\n\n@payments.on_outgoingTransaction()\nasync def handle_outgoing_transactions(_, transaction: types.RawTransaction):\n    comment = None\n    if transaction.out_msgs[0].msg_data.getType() == \"msg.dataText\":\n        comment = transaction.out_msgs[0].msg_data.text.decode()\n\n    transaction_info = (\n        f\"Sending \"\n        f\"`{utils.truncate_zeros(utils.from_nanograms(transaction.out_msgs[0].value))} TON` \"\n        f\"to `{utils.Address.normalize(transaction.out_msgs[0].destination)}` \"\n        f\"({comment})\\n\"\n    )\n    print(transaction_info)\n\n\nclient.run(payments)\n```\n# License\n\nMIT [License](https://github.com/AYMENJD/tonx/blob/main/LICENSE)\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A user-friendly Python library for interacting with TON (The Open Network), offering convenient payment handling and much more.",
    "version": "0.1.5",
    "project_urls": {
        "Homepage": "https://github.com/AYMENJD/tonx",
        "Source": "https://github.com/AYMENJD/tonx",
        "Tracker": "https://github.com/AYMENJD/tonx/issues"
    },
    "split_keywords": [
        "ton",
        "telegram",
        "cryptocurrency",
        "blockchain",
        "tonlib",
        "payments",
        "crypto",
        "digital currency",
        "decentralized",
        "smart contracts",
        "dapp",
        "ethereum",
        "bitcoin",
        "cryptocurrency payments",
        "crypto wallet",
        "transaction",
        "secure",
        "privacy",
        "token",
        "block explorer",
        "smart contract development"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "50c57bf11540ef10ea2aebbfb1f4608114e2e2af8bb30bef62aa46a07d9fe07b",
                "md5": "8cf830b541e9823d08eb10450a8eb172",
                "sha256": "4d0b037224ba3dec679bf9b896fe57e2a90a843eaa54ec28ac41424baa519183"
            },
            "downloads": -1,
            "filename": "TonX-0.1.5.tar.gz",
            "has_sig": false,
            "md5_digest": "8cf830b541e9823d08eb10450a8eb172",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 52217,
            "upload_time": "2023-12-27T14:18:01",
            "upload_time_iso_8601": "2023-12-27T14:18:01.347054Z",
            "url": "https://files.pythonhosted.org/packages/50/c5/7bf11540ef10ea2aebbfb1f4608114e2e2af8bb30bef62aa46a07d9fe07b/TonX-0.1.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-12-27 14:18:01",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "AYMENJD",
    "github_project": "tonx",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "tonx"
}
        
Elapsed time: 0.20271s