This low-level Python library allows you to work with the TON blockchain.
- tonsdk/provider part is dirty.
pip install tonsdkYou can find examples in examples folder
fromtonsdk.contract.walletimportWalletVersionEnum, Walletsfromtonsdk.utilsimportbytes_to_b64strfromtonsdk.cryptoimportmnemonic_newwallet_workchain=0wallet_version=WalletVersionEnum.v3r2wallet_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))fromtonsdk.contract.token.nftimportNFTItemfromtonsdk.contract.token.ftimportJettonWalletfromtonsdk.utilsimportAddress, to_nanobody=NFTItem().create_transfer_body(
Address("New Owner Address")
)
query=wallet.create_transfer_message(
"NFT Item Address",
to_nano(0.05, "ton"),
0, # owner wallet seqnopayload=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 seqnopayload=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))Note - to use these clients you should install tvm_valuetypes and aiohttp packages
fromabcimportABC, abstractmethodimportasyncioimportaiohttpfromtvm_valuetypesimportserialize_tvm_stackfromtonsdk.providerimportToncenterClient, SyncTonlibClient, prepare_address, address_statefromtonsdk.utilsimportTonCurrencyEnum, from_nanofromtonsdk.bocimportCellclassAbstractTonClient(ABC):
@abstractmethoddef_run(self, to_run, *, single_query=True):
raiseNotImplementeddefget_address_information(self, address: str,
currency_to_show: TonCurrencyEnum=TonCurrencyEnum.ton):
returnself.get_addresses_information([address], currency_to_show)[0]
defget_addresses_information(self, addresses,
currency_to_show: TonCurrencyEnum=TonCurrencyEnum.ton):
ifnotaddresses:
return []
tasks= []
foraddressinaddresses:
address=prepare_address(address)
tasks.append(self.provider.raw_get_account_state(address))
results=self._run(tasks, single_query=False)
forresultinresults:
result["state"] =address_state(result)
if"balance"inresult:
ifint(result["balance"]) <0:
result["balance"] =0else:
result["balance"] =from_nano(
int(result["balance"]), currency_to_show)
returnresultsdefseqno(self, addr: str):
addr=prepare_address(addr)
result=self._run(self.provider.raw_run_method(addr, "seqno", []))
if'stack'inresultand ('@type'inresultandresult['@type'] =='smc.runResult'):
result['stack'] =serialize_tvm_stack(result['stack'])
returnresultdefsend_boc(self, boc: Cell):
returnself._run(self.provider.raw_send_message(boc))
classTonCenterTonClient(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:
returnself.loop.run_until_complete(
self.__execute(to_run, single_query))
exceptException: # ToncenterWrongResult, asyncio.exceptions.TimeoutError, aiohttp.client_exceptions.ClientConnectorErrorraiseasyncdef__execute(self, to_run, single_query):
timeout=aiohttp.ClientTimeout(total=5)
asyncwithaiohttp.ClientSession(timeout=timeout) assession:
ifsingle_query:
to_run= [to_run]
tasks= []
fortaskinto_run:
tasks.append(task["func"](
session, *task["args"], **task["kwargs"]))
returnawaitasyncio.gather(*tasks)
classTonLibJsonTonClient(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.dylibself.provider.init()
def_run(self, to_read, *, single_query=True):
try:
ifnotsingle_query:
queries_order= {query_id: ifori,
query_idinenumerate(to_read)}
returnself.provider.read_results(queries_order)
else:
returnself.provider.read_result(to_read)
exceptException: # TonLibWrongResult, TimeoutErrorraise# create a client instanceclient=TonCenterTonClient()
# use client to get any addr informationaddr_info=client.get_address_information(
"EQAhE3sLxHZpsyZ_HecMuwzvXHKLjYx4kEUehhOy2JmCcHCT")
# get your wallet seqnoseqno=client.seqno(wallet.address.to_string())
# send any bocclient.send_boc(nft_boc)