Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Orbit/thongdev/customrun #16

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
api info token
  • Loading branch information
thong183 committed Apr 3, 2024
commit dfe95ea9940e15a8a4dd51a18c7e16fb1c9f05b7
14 changes: 8 additions & 6 deletions .env.dist
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
TON_CONSOLE__API_KEY = ""
TON_CONSOLE__API_KEY = "AFVDINKN6H4UXLAAAAAFQNNUC6P2JZHNZALNC6LVMWGUASBBI372VHRNRSUB7NGQCSB5BQA"
TON__HOST_URL = "https://toncenter.com"

TON__TON_CONTRACT_ADDRESS = "EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c"
TON__TGR_CONTRACT_ADDRESS = "EQAvDfWFG0oYX19jwNDNBBL1rKNT9XfaGP9HyTb5nb2Eml6y"
Expand All @@ -10,18 +11,19 @@ STON_FI__PROXY_TON_ADDRESS = "EQCM3B12QK1e4yZSf8GtBRT0aLMNyEsBc_DhVfRRtOEffLez"
STON_FI__TON_CONTRACT_ADDRESS = "EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c"
STON_FI__ROUTER_ADDRESS = "EQB3ncyBUTjZUA5EnFKR5_EnOMI9V1tTEAAPaiU71gc4TiUt"


SWAP__FEE_PERCENT = 0.2
SWAP__TGR_CASHBACK_PERCENT = 0.1
SWAP__TON_FEE_ADDRESS = ""
SWAP__TON_FEE_ADDRESS = "UQDlCpEgRM4Zxh39DaPoSI1gZx0XFx8UlHdjZBYRsVP71cUq"

DATABASE__DEV_URL_ASYNC = "sqlite+aiosqlite:///./database.db"
DATABASE__DEV_URL_SYNC = "sqlite:///./database.db"
DATABASE__DEV_MODE = True

SECRET = ""
ALGORITHM = ""
SECRET = "123456"
ALGORITHM = "HS256"

JWT__COOKIE_SECURE = False
JWT__COOKIE_SECURE = True

SERVER__DOMAIN = ""
SERVER__CORS_ALLOW_ORIGINS = []
SERVER__CORS_ALLOW_ORIGINS = ["http://localhost:3000","http://192.168.0.56:3000","http://192.168.1.153:3000"]
17 changes: 17 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#
FROM python:3.10

#
WORKDIR /code

#
COPY ./requirements.txt /code/requirements.txt

#
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt

#
COPY ./src /code/src

#
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "80"]
Binary file removed database.db-journal
Binary file not shown.
14 changes: 14 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
version: '3.8'

services:
server:
build:
context: .
dockerfile: Dockerfile
volumes:
- .:/ton-backend/
command: uvicorn src.server:app --reload --host 0.0.0.0 --port 8000
env_file:
- ./.env.dist
ports:
- 8000:8000
10 changes: 9 additions & 1 deletion src/api/v1/ton/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from fastapi import FastAPI

from .schemas import GetJettonsBalancesResponse
from .schemas import GetJettonsBalancesResponse, TokenInfoResponse
from .wallets import get_jettons_balances_endpoint
from .token import get_info_token_endpoint


def register_routes(app: FastAPI):
Expand All @@ -11,3 +12,10 @@ def register_routes(app: FastAPI):
response_model=GetJettonsBalancesResponse,
methods=["GET"],
)

app.add_api_route(
path="/api/v1/token/get_token_info",
endpoint=get_info_token_endpoint,
response_model=TokenInfoResponse,
methods=["GET"],
)
5 changes: 5 additions & 0 deletions src/api/v1/ton/schemas.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from typing import Dict
from pydantic import BaseModel
from src.utils.address import ValidatedAddress
from src.ton.schemas import TokenInfo


class GetJettonsBalancesRequest(BaseModel):
Expand All @@ -9,3 +10,7 @@ class GetJettonsBalancesRequest(BaseModel):

class GetJettonsBalancesResponse(BaseModel):
balances: Dict[ValidatedAddress, int]


class TokenInfoResponse(BaseModel):
data: TokenInfo
14 changes: 14 additions & 0 deletions src/api/v1/ton/token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from fastapi import Depends

from src.config import config
from src.ton.ton_api import get_info_token

from .schemas import TokenInfoResponse


async def get_info_token_endpoint(
address: str
):
info_token = await get_info_token(address= address)
response = TokenInfoResponse(data=info_token)
return response
1 change: 1 addition & 0 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class Ton(BaseSettings):
tgr_contract_address: str
fnz_contract_address: str
scale_contract_address: str
host_url: str


class Swap(BaseSettings):
Expand Down
6 changes: 2 additions & 4 deletions src/dex/ston_fi_contracts/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,6 @@ async def get_pool_data(
response = await self.tonapi_client.blockchain.execute_get_method(
account_id=pool_address.to_string(),
method_name="get_pool_data",
args=[],
)

reserve0 = int(response.stack[0].num, 16)
Expand Down Expand Up @@ -258,10 +257,10 @@ async def get_expected_tokens(
token0_amount: int,
token1_amount: int,
) -> int:
response = await self.tonapi_client.blockchain.execute_get_method(
response = await self.tonapi_client.blockchain.execute_get_wallets_method(
account_id=pool_address,
method_name="get_expected_tokens",
args=[
arggs=[
f"{token1_amount}",
f"{token0_amount}",
],
Expand All @@ -276,7 +275,6 @@ async def get_lp_account_data(
response = await self.tonapi_client.blockchain.execute_get_method(
account_id=lp_account_address,
method_name="get_lp_account_data",
args=[],
)

token0_address = parse_address_from_bytes(
Expand Down
64 changes: 64 additions & 0 deletions src/ton/schemas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from typing import Any
from dataclasses import dataclass
import json
@dataclass
class Data:
image: str
name: str
symbol: str
description: str
decimals: str

@staticmethod
def from_dict(obj: Any) -> 'Data':
_image = str(obj.get("image"))
_name = str(obj.get("name"))
_symbol = str(obj.get("symbol"))
_description = str(obj.get("description"))
_decimals = str(obj.get("decimals"))
return Data(_image, _name, _symbol, _description, _decimals)

@dataclass
class JettonContent:
type: str
data: Data

@staticmethod
def from_dict(obj: Any) -> 'JettonContent':
_type = str(obj.get("type"))
_data = Data.from_dict(obj.get("data"))
return JettonContent(_type, _data)

@dataclass
class Result:
total_supply: float
mintable: bool
admin_address: str
jetton_content: JettonContent
jetton_wallet_code: str
contract_type: str

@staticmethod
def from_dict(obj: Any) -> 'Result':
_total_supply = float(obj.get("total_supply"))
_mintable = True
_admin_address = str(obj.get("admin_address"))
_jetton_content = JettonContent.from_dict(obj.get("jetton_content"))
_jetton_wallet_code = str(obj.get("jetton_wallet_code"))
_contract_type = str(obj.get("contract_type"))
return Result(_total_supply, _mintable, _admin_address, _jetton_content, _jetton_wallet_code, _contract_type)

@dataclass
class TokenInfo:
ok: bool
result: Result

@staticmethod
def from_dict(obj: Any) -> 'TokenInfo':
_ok = obj.get("ok")
_result = Result.from_dict(obj.get("result"))
return TokenInfo(_ok, _result)

# Example Usage
# jsonstring = json.loads(myjsonstring)
# token = TokenInfo.from_dict(jsonstring)
23 changes: 23 additions & 0 deletions src/ton/ton_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from src.config import config
from src.ton.schemas import TokenInfo
import httpx
import json
import logging
logger = logging.getLogger("ton-debug")

async def get_info_token(address: str) -> TokenInfo:
"""
Get token data info.
"""
timeout = httpx.Timeout(120)
try:
async with httpx.AsyncClient(timeout=timeout) as session:
session: httpx.AsyncClient
params = {"address":address}
url = f"{config.ton.host_url}/api/v2/getTokenData"
response = await session.request("GET", url=url, params= params,headers={"Content-Type":"application/json"})
jsonStr = response.json()
resData = json.loads(json.dumps(jsonStr))
return TokenInfo.from_dict(resData)
except httpx.LocalProtocolError as err:
logger.error(err)
12 changes: 8 additions & 4 deletions src/ton/utils.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from pytonapi import AsyncTonapi
from tonsdk.boc import Cell, Slice, begin_cell
from tonsdk.utils import Address, b64str_to_bytes, bytes_to_b64str

from src.ton.tonapi_client_factory import TonapiClientFactory

import logging
logger = logging.getLogger("ton-debug")

def get_address_cell(address: Address | str) -> Cell:
if isinstance(address, str):
Expand Down Expand Up @@ -50,11 +51,14 @@ async def get_jetton_wallet_address(
tonapi_client = TonapiClientFactory.get_tonapi_client()

owner_wallet_address_hex = get_address_cell(owner_wallet_address)

response = await tonapi_client.blockchain.execute_get_method(

owner_wallet_address_hex_value = owner_wallet_address_hex.to_boc(False).hex()
logger.info("wallet address: " + owner_wallet_address_hex_value)

response = await tonapi_client.blockchain.execute_get_wallets_method(
account_id=jetton_contract_address,
method_name="get_wallet_address",
args=[owner_wallet_address_hex.to_boc(False).hex()],
arggs=[owner_wallet_address_hex_value],
)

wallet_address = parse_address_from_bytes(
Expand Down