# TONsdk
[![PyPI](https://img.shields.io/pypi/v/tonsdk?color=blue)](https://pypi.org/project/tonsdk/)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/tonsdk)](https://pypi.org/project/tonsdk/)
[![Downloads](https://static.pepy.tech/badge/tonsdk)](https://pepy.tech/project/tonsdk)
## Description
This low-level Python library allows you to work with the [TON blockchain](https://ton.org/).
### Notes
- tonsdk/provider part is dirty.
## How to install
```bash
pip install tonsdk
```
## How to use
You can find examples in [examples](https://github.com/tonfactory/tonsdk/tree/master/examples) folder
## General usage examples
### Create mnemonic, init wallet class, create external message to deploy the wallet
```python
from tonsdk.contract.wallet import WalletVersionEnum, Wallets
from tonsdk.utils import bytes_to_b64str
from tonsdk.crypto import mnemonic_new
wallet_workchain = 0
wallet_version = WalletVersionEnum.v3r2
wallet_mnemonics = mnemonic_new()
_mnemonics, _pub_k, _priv_k, wallet = Wallets.from_mnemonics(
wallet_mnemonics, wallet_version, wallet_workchain)
query = wallet.create_init_external_message()
base64_boc = bytes_to_b64str(query["message"].to_boc(False))
print("""
Mnemonic: {}
Raw address: {}
Bounceable, url safe, user friendly address: {}
Base64boc to deploy the wallet: {}
""".format(wallet_mnemonics,
wallet.address.to_string(),
wallet.address.to_string(True, True, True),
base64_boc))
```
### Transfer NFT & Jettons by creating a transfer message from an owner wallet
```python
from tonsdk.contract.token.nft import NFTItem
from tonsdk.contract.token.ft import JettonWallet
from tonsdk.utils import Address, to_nano
body = NFTItem().create_transfer_body(
Address("New Owner Address")
)
query = wallet.create_transfer_message(
"NFT Item Address",
to_nano(0.05, "ton"),
0, # owner wallet seqno
payload=body
)
nft_boc = bytes_to_b64str(query["message"].to_boc(False))
body = JettonWallet().create_transfer_body(
Address("Destination address"),
to_nano(40000, "ton") # jettons amount
)
query = wallet.create_transfer_message(
"Jetton Wallet Address",
to_nano(0.05, "ton"),
0, # owner wallet seqno
payload=body
)
jettons_boc = bytes_to_b64str(query["message"].to_boc(False))
print("""
Base64boc to transfer the NFT item: {}
Base64boc to transfer the jettons: {}
""".format(nft_boc, jettons_boc))
```
### Clients usage example (dirty)
*Note - to use these clients you should install tvm_valuetypes and aiohttp packages*
```python
from abc import ABC, abstractmethod
import asyncio
import aiohttp
from tvm_valuetypes import serialize_tvm_stack
from tonsdk.provider import ToncenterClient, SyncTonlibClient, prepare_address, address_state
from tonsdk.utils import TonCurrencyEnum, from_nano
from tonsdk.boc import Cell
class AbstractTonClient(ABC):
@abstractmethod
def _run(self, to_run, *, single_query=True):
raise NotImplemented
def get_address_information(self, address: str,
currency_to_show: TonCurrencyEnum = TonCurrencyEnum.ton):
return self.get_addresses_information([address], currency_to_show)[0]
def get_addresses_information(self, addresses,
currency_to_show: TonCurrencyEnum = TonCurrencyEnum.ton):
if not addresses:
return []
tasks = []
for address in addresses:
address = prepare_address(address)
tasks.append(self.provider.raw_get_account_state(address))
results = self._run(tasks, single_query=False)
for result in results:
result["state"] = address_state(result)
if "balance" in result:
if int(result["balance"]) < 0:
result["balance"] = 0
else:
result["balance"] = from_nano(
int(result["balance"]), currency_to_show)
return results
def seqno(self, addr: str):
addr = prepare_address(addr)
result = self._run(self.provider.raw_run_method(addr, "seqno", []))
if 'stack' in result and ('@type' in result and result['@type'] == 'smc.runResult'):
result['stack'] = serialize_tvm_stack(result['stack'])
return result
def send_boc(self, boc: Cell):
return self._run(self.provider.raw_send_message(boc))
class TonCenterTonClient(AbstractTonClient):
def __init__(self):
self.loop = asyncio.get_event_loop()
self.provider = ToncenterClient(base_url="https://testnet.toncenter.com/api/v2/",
api_key="eb542b65e88d2da318fb7c163b9245e4edccb2eb8ba11cabda092cdb6fbc3395")
def _run(self, to_run, *, single_query=True):
try:
return self.loop.run_until_complete(
self.__execute(to_run, single_query))
except Exception: # ToncenterWrongResult, asyncio.exceptions.TimeoutError, aiohttp.client_exceptions.ClientConnectorError
raise
async def __execute(self, to_run, single_query):
timeout = aiohttp.ClientTimeout(total=5)
async with aiohttp.ClientSession(timeout=timeout) as session:
if single_query:
to_run = [to_run]
tasks = []
for task in to_run:
tasks.append(task["func"](
session, *task["args"], **task["kwargs"]))
return await asyncio.gather(*tasks)
class TonLibJsonTonClient(AbstractTonClient):
def __init__(self):
self.loop = asyncio.get_event_loop()
self.provider = SyncTonlibClient(config="./.tonlibjson/testnet.json",
keystore="./.tonlibjson/keystore",
cdll_path="./.tonlibjson/linux_libtonlibjson.so") # or macos_libtonlibjson.dylib
self.provider.init()
def _run(self, to_read, *, single_query=True):
try:
if not single_query:
queries_order = {query_id: i for i,
query_id in enumerate(to_read)}
return self.provider.read_results(queries_order)
else:
return self.provider.read_result(to_read)
except Exception: # TonLibWrongResult, TimeoutError
raise
# create a client instance
client = TonCenterTonClient()
# use client to get any addr information
addr_info = client.get_address_information(
"EQAhE3sLxHZpsyZ_HecMuwzvXHKLjYx4kEUehhOy2JmCcHCT")
# get your wallet seqno
seqno = client.seqno(wallet.address.to_string())
# send any boc
client.send_boc(nft_boc)
```
Raw data
{
"_id": null,
"home_page": null,
"name": "tonsdk",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": null,
"keywords": "TON, TON SDK, TON utils, TON tools",
"author": "tonfactory.org",
"author_email": null,
"download_url": "https://files.pythonhosted.org/packages/ab/f7/d412886e7c8ef04670e90727f29e318116f9f7d77a11eae0137d8e91a1f4/tonsdk-1.0.15.tar.gz",
"platform": null,
"description": "# TONsdk\n[![PyPI](https://img.shields.io/pypi/v/tonsdk?color=blue)](https://pypi.org/project/tonsdk/)\n[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/tonsdk)](https://pypi.org/project/tonsdk/)\n[![Downloads](https://static.pepy.tech/badge/tonsdk)](https://pepy.tech/project/tonsdk)\n\n## Description\nThis low-level Python library allows you to work with the [TON blockchain](https://ton.org/).\n\n### Notes\n\n- tonsdk/provider part is dirty.\n\n## How to install\n\n```bash\npip install tonsdk\n```\n\n## How to use\n\nYou can find examples in [examples](https://github.com/tonfactory/tonsdk/tree/master/examples) folder\n\n## General usage examples\n### Create mnemonic, init wallet class, create external message to deploy the wallet\n\n```python\nfrom tonsdk.contract.wallet import WalletVersionEnum, Wallets\nfrom tonsdk.utils import bytes_to_b64str\nfrom tonsdk.crypto import mnemonic_new\n\n\nwallet_workchain = 0\nwallet_version = WalletVersionEnum.v3r2\nwallet_mnemonics = mnemonic_new()\n\n_mnemonics, _pub_k, _priv_k, wallet = Wallets.from_mnemonics(\n wallet_mnemonics, wallet_version, wallet_workchain)\nquery = wallet.create_init_external_message()\nbase64_boc = bytes_to_b64str(query[\"message\"].to_boc(False))\n\nprint(\"\"\"\nMnemonic: {}\n\nRaw address: {}\n\nBounceable, url safe, user friendly address: {}\n\nBase64boc to deploy the wallet: {}\n\"\"\".format(wallet_mnemonics,\n wallet.address.to_string(),\n wallet.address.to_string(True, True, True),\n base64_boc))\n```\n\n### Transfer NFT & Jettons by creating a transfer message from an owner wallet\n```python\nfrom tonsdk.contract.token.nft import NFTItem\nfrom tonsdk.contract.token.ft import JettonWallet\nfrom tonsdk.utils import Address, to_nano\n\nbody = NFTItem().create_transfer_body(\n Address(\"New Owner Address\")\n)\nquery = wallet.create_transfer_message(\n \"NFT Item Address\",\n to_nano(0.05, \"ton\"),\n 0, # owner wallet seqno\n payload=body\n)\nnft_boc = bytes_to_b64str(query[\"message\"].to_boc(False))\n\nbody = JettonWallet().create_transfer_body(\n Address(\"Destination address\"),\n to_nano(40000, \"ton\") # jettons amount\n)\nquery = wallet.create_transfer_message(\n \"Jetton Wallet Address\",\n to_nano(0.05, \"ton\"),\n 0, # owner wallet seqno\n payload=body\n)\njettons_boc = bytes_to_b64str(query[\"message\"].to_boc(False))\n\nprint(\"\"\"\nBase64boc to transfer the NFT item: {}\n\nBase64boc to transfer the jettons: {}\n\"\"\".format(nft_boc, jettons_boc))\n```\n\n### Clients usage example (dirty)\n\n*Note - to use these clients you should install tvm_valuetypes and aiohttp packages*\n\n```python\nfrom abc import ABC, abstractmethod\nimport asyncio\nimport aiohttp\nfrom tvm_valuetypes import serialize_tvm_stack\n\nfrom tonsdk.provider import ToncenterClient, SyncTonlibClient, prepare_address, address_state\nfrom tonsdk.utils import TonCurrencyEnum, from_nano\nfrom tonsdk.boc import Cell\n\n\nclass AbstractTonClient(ABC):\n @abstractmethod\n def _run(self, to_run, *, single_query=True):\n raise NotImplemented\n\n def get_address_information(self, address: str,\n currency_to_show: TonCurrencyEnum = TonCurrencyEnum.ton):\n return self.get_addresses_information([address], currency_to_show)[0]\n\n def get_addresses_information(self, addresses,\n currency_to_show: TonCurrencyEnum = TonCurrencyEnum.ton):\n if not addresses:\n return []\n\n tasks = []\n for address in addresses:\n address = prepare_address(address)\n tasks.append(self.provider.raw_get_account_state(address))\n\n results = self._run(tasks, single_query=False)\n\n for result in results:\n result[\"state\"] = address_state(result)\n if \"balance\" in result:\n if int(result[\"balance\"]) < 0:\n result[\"balance\"] = 0\n else:\n result[\"balance\"] = from_nano(\n int(result[\"balance\"]), currency_to_show)\n\n return results\n \n def seqno(self, addr: str):\n addr = prepare_address(addr)\n result = self._run(self.provider.raw_run_method(addr, \"seqno\", []))\n\n if 'stack' in result and ('@type' in result and result['@type'] == 'smc.runResult'):\n result['stack'] = serialize_tvm_stack(result['stack'])\n\n return result\n\n def send_boc(self, boc: Cell):\n return self._run(self.provider.raw_send_message(boc))\n\n\nclass TonCenterTonClient(AbstractTonClient):\n def __init__(self):\n self.loop = asyncio.get_event_loop()\n self.provider = ToncenterClient(base_url=\"https://testnet.toncenter.com/api/v2/\",\n api_key=\"eb542b65e88d2da318fb7c163b9245e4edccb2eb8ba11cabda092cdb6fbc3395\")\n\n def _run(self, to_run, *, single_query=True):\n try:\n return self.loop.run_until_complete(\n self.__execute(to_run, single_query))\n\n except Exception: # ToncenterWrongResult, asyncio.exceptions.TimeoutError, aiohttp.client_exceptions.ClientConnectorError\n raise\n\n async def __execute(self, to_run, single_query):\n timeout = aiohttp.ClientTimeout(total=5)\n\n async with aiohttp.ClientSession(timeout=timeout) as session:\n if single_query:\n to_run = [to_run]\n\n tasks = []\n for task in to_run:\n tasks.append(task[\"func\"](\n session, *task[\"args\"], **task[\"kwargs\"]))\n\n return await asyncio.gather(*tasks)\n\n\nclass TonLibJsonTonClient(AbstractTonClient):\n def __init__(self):\n self.loop = asyncio.get_event_loop()\n self.provider = SyncTonlibClient(config=\"./.tonlibjson/testnet.json\",\n keystore=\"./.tonlibjson/keystore\",\n cdll_path=\"./.tonlibjson/linux_libtonlibjson.so\") # or macos_libtonlibjson.dylib\n self.provider.init()\n\n def _run(self, to_read, *, single_query=True):\n try:\n if not single_query:\n queries_order = {query_id: i for i,\n query_id in enumerate(to_read)}\n return self.provider.read_results(queries_order)\n\n else:\n return self.provider.read_result(to_read)\n\n except Exception: # TonLibWrongResult, TimeoutError\n raise\n\n\n# create a client instance\nclient = TonCenterTonClient()\n\n# use client to get any addr information\naddr_info = client.get_address_information(\n \"EQAhE3sLxHZpsyZ_HecMuwzvXHKLjYx4kEUehhOy2JmCcHCT\")\n\n# get your wallet seqno\nseqno = client.seqno(wallet.address.to_string())\n\n# send any boc\nclient.send_boc(nft_boc)\n```\n",
"bugtrack_url": null,
"license": "Apache 2.0",
"summary": "Python SDK for TON",
"version": "1.0.15",
"project_urls": {
"Github": "https://github.com/tonfactory/tonsdk"
},
"split_keywords": [
"ton",
" ton sdk",
" ton utils",
" ton tools"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "40ba27cab7dd033960f98d5c70b297d9d8723c563d0bc46dbf682981238aa8ab",
"md5": "098fd6162979d3f3dd4cd91e8f353402",
"sha256": "1897241bee8977486bf83279873c20ff67143366e0768ef85ab4df989edcae80"
},
"downloads": -1,
"filename": "tonsdk-1.0.15-py3-none-any.whl",
"has_sig": false,
"md5_digest": "098fd6162979d3f3dd4cd91e8f353402",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7",
"size": 71136,
"upload_time": "2024-07-09T07:11:22",
"upload_time_iso_8601": "2024-07-09T07:11:22.704075Z",
"url": "https://files.pythonhosted.org/packages/40/ba/27cab7dd033960f98d5c70b297d9d8723c563d0bc46dbf682981238aa8ab/tonsdk-1.0.15-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "abf7d412886e7c8ef04670e90727f29e318116f9f7d77a11eae0137d8e91a1f4",
"md5": "61e9741e1895c80cd036bc77b778470d",
"sha256": "7f8020ef1e4ec9b48b93a0437f2828571acf59e18f945484990a061eaf1ce641"
},
"downloads": -1,
"filename": "tonsdk-1.0.15.tar.gz",
"has_sig": false,
"md5_digest": "61e9741e1895c80cd036bc77b778470d",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7",
"size": 58688,
"upload_time": "2024-07-09T07:11:24",
"upload_time_iso_8601": "2024-07-09T07:11:24.653085Z",
"url": "https://files.pythonhosted.org/packages/ab/f7/d412886e7c8ef04670e90727f29e318116f9f7d77a11eae0137d8e91a1f4/tonsdk-1.0.15.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-07-09 07:11:24",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "tonfactory",
"github_project": "tonsdk",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "tonsdk"
}