Initial commit
This commit is contained in:
commit
9638f5a31b
45 files changed
+2421
No files matched your search
@@ -0,0 +1,6 @@
|
||||
from app.core.models.asset import Asset
|
||||
from app.core.models.memory import Memory
|
||||
from app.core.models.transaction import UserBalance, InternalTransaction
|
||||
from app.core.models.user import User
|
||||
from app.core.models.wallet_connection import WalletConnection
|
||||
from app.core.models.base import AlchemyBase
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,152 @@
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime
|
||||
from hashlib import sha256
|
||||
|
||||
from pytonconnect import TonConnect as ExternalLib_TonConnect
|
||||
from pytonconnect.storage import DefaultStorage
|
||||
|
||||
from app.core._config import PROJECT_HOST
|
||||
from app.core.logger import make_log
|
||||
from app.core.models.wallet_connection import WalletConnection
|
||||
|
||||
TON_CONNECT_MANIFEST_URI = os.getenv("TON_CONNECT_MANIFEST_URI")
|
||||
|
||||
|
||||
def unpack_wallet_info(wallet_info) -> dict:
|
||||
return {
|
||||
'provider': wallet_info.provider,
|
||||
'device': {
|
||||
'platform': wallet_info.device.platform,
|
||||
'app_name': wallet_info.device.app_name,
|
||||
'app_version': wallet_info.device.app_version,
|
||||
'max_protocol_version': wallet_info.device.max_protocol_version,
|
||||
'features': wallet_info.device.features
|
||||
} if wallet_info.device else None,
|
||||
'account': {
|
||||
'address': wallet_info.account.address,
|
||||
'chain': wallet_info.account.chain,
|
||||
'wallet_state_init': wallet_info.account.wallet_state_init,
|
||||
'public_key': wallet_info.account.public_key,
|
||||
} if wallet_info.account else None,
|
||||
'ton_proof': {
|
||||
'timestamp': wallet_info.ton_proof.timestamp,
|
||||
'domain_len': wallet_info.ton_proof.domain_len,
|
||||
'domain_val': wallet_info.ton_proof.domain_val,
|
||||
'payload': wallet_info.ton_proof.payload,
|
||||
'signature': wallet_info.ton_proof.signature,
|
||||
} if wallet_info.ton_proof else None
|
||||
}
|
||||
|
||||
|
||||
class TonConnect:
|
||||
def __init__(self, callback_fn: tuple = None):
|
||||
self._manifest_uri = TON_CONNECT_MANIFEST_URI
|
||||
if not self._manifest_uri:
|
||||
self._manifest_uri = f"{PROJECT_HOST}/api/tonconnect-manifest.json"
|
||||
|
||||
self._sdk_client = ExternalLib_TonConnect(
|
||||
manifest_url=self._manifest_uri, storage=DefaultStorage()
|
||||
)
|
||||
|
||||
def status_change_callback(status):
|
||||
status = unpack_wallet_info(status)
|
||||
make_log("TonConnect", f"Changed status (connected={self.connected}): {status}", level='debug')
|
||||
|
||||
if callback_fn:
|
||||
callback_fn[0](self, status, *callback_fn[1:])
|
||||
|
||||
self.set_status_change_callback(status_change_callback)
|
||||
|
||||
async def new_connection(self, app_name: str):
|
||||
wallets = self._sdk_client.get_wallets()
|
||||
for wallet in wallets:
|
||||
if wallet["app_name"] == app_name:
|
||||
return await self._sdk_client.connect(wallet)
|
||||
|
||||
async def restore_connection(self):
|
||||
return await self._sdk_client.restore_connection()
|
||||
|
||||
def pause_connection(self):
|
||||
try:
|
||||
self._sdk_client.pause_connection()
|
||||
except BaseException as e:
|
||||
make_log("pause_connection", e, level='error')
|
||||
|
||||
@asynccontextmanager
|
||||
async def connection(self):
|
||||
try:
|
||||
yield None
|
||||
finally:
|
||||
self.pause_connection()
|
||||
|
||||
@property
|
||||
def connected(self):
|
||||
# make_log("is_connected", self._sdk_client._storage._cache)
|
||||
return self._sdk_client.connected
|
||||
|
||||
@property
|
||||
def connection_key(self):
|
||||
return self._sdk_client._storage._cache.get(DefaultStorage.KEY_CONNECTION, None)
|
||||
# return self._sdk_client._storage.get_item(DefaultStorage.KEY_CONNECTION, None)
|
||||
|
||||
def set_status_change_callback(self, callback):
|
||||
self._sdk_client.on_status_change(callback)
|
||||
|
||||
@classmethod
|
||||
def by_key(cls, connection_key: str, callback_fn: tuple = None):
|
||||
ton_connect = cls(callback_fn=callback_fn)
|
||||
ton_connect._sdk_client._storage._cache[DefaultStorage.KEY_CONNECTION] = connection_key
|
||||
# ton_connect._sdk_client._storage.set_item(DefaultStorage.KEY_CONNECTION, connection_key)
|
||||
# Immediately restore connection
|
||||
return ton_connect
|
||||
|
||||
@classmethod
|
||||
def by_user(cls, session, user, callback_fn: tuple = None):
|
||||
def new_callback_fn(self, status, _callback_fn):
|
||||
try:
|
||||
if not session.query(
|
||||
WalletConnection
|
||||
).filter(WalletConnection.connection_id == sha256(self.connection_key.encode()).hexdigest()) \
|
||||
.count():
|
||||
new_connection = WalletConnection(
|
||||
user_id=user.id,
|
||||
network='ton',
|
||||
wallet_key=f"{status['device'].get('app_name', 'UNKNOWN_NAME')}=={status['device'].get('app_version', '1.0')}",
|
||||
connection_id=sha256(self.connection_key.encode()).hexdigest(),
|
||||
wallet_address=status['account']['address'],
|
||||
keys={
|
||||
'connection_key': self.connection_key,
|
||||
},
|
||||
meta={
|
||||
key: status[key] for key in status if status[key]
|
||||
},
|
||||
created=datetime.now(),
|
||||
updated=datetime.now(),
|
||||
invalidated=False
|
||||
)
|
||||
session.add(new_connection)
|
||||
session.commit()
|
||||
except BaseException as e:
|
||||
make_log("TonConnect.save_connection", e, level='error')
|
||||
|
||||
if _callback_fn:
|
||||
_callback_fn[0](self, status, *_callback_fn[1:])
|
||||
|
||||
ton_connect = cls(callback_fn=(new_callback_fn, callback_fn))
|
||||
connections = (
|
||||
session.query(WalletConnection).filter(
|
||||
WalletConnection.user_id == user.id,
|
||||
WalletConnection.invalidated == False,
|
||||
WalletConnection.network == 'ton'
|
||||
)
|
||||
)
|
||||
if connections.count() == 0:
|
||||
return ton_connect, None
|
||||
|
||||
connection = connections.first()
|
||||
ton_connect._sdk_client._storage._cache[DefaultStorage.KEY_CONNECTION] = connection.keys["connection_key"]
|
||||
# ton_connect._sdk_client._storage.set_item(DefaultStorage.KEY_CONNECTION, bytes.fromhex(connection.keys["connection_key"]))
|
||||
# Immediately restore connection
|
||||
return ton_connect, connection
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
from .wrapped_bot import Wrapped_CBotChat
|
||||
@@ -0,0 +1,129 @@
|
||||
from aiogram import Bot
|
||||
|
||||
from app.core.logger import make_log
|
||||
|
||||
|
||||
class Wrapped_CBotChat:
|
||||
def __init__(self, api_key: str, chat_id: int = None, **kwargs):
|
||||
if isinstance(api_key, Bot):
|
||||
self._bot_key = api_key.token
|
||||
self._bot = api_key
|
||||
elif type(api_key) is str:
|
||||
self._bot_key = api_key
|
||||
self._bot = Bot(token=api_key)
|
||||
else:
|
||||
raise TypeError(f'api_key must be Bot or str, not {type(api_key)}')
|
||||
|
||||
self._chat_id = chat_id
|
||||
self.options = kwargs
|
||||
|
||||
def __repr__(self):
|
||||
if self.options.get('cbot_id'):
|
||||
return f'Bot, chat_id={self.options["cbot_id"]} ' + '\\'
|
||||
|
||||
return "Bot"
|
||||
|
||||
async def send_message(self, text: str, **kwargs):
|
||||
try:
|
||||
make_log(self, f"Send message to {self._chat_id}. Text len: {len(text)}", level='debug')
|
||||
return await self._bot.send_message(
|
||||
self._chat_id,
|
||||
text,
|
||||
parse_mode='html',
|
||||
disable_web_page_preview=True,
|
||||
**kwargs
|
||||
)
|
||||
except BaseException as e:
|
||||
make_log(self, f"Error sending message to {self._chat_id}. Error: {e}", level='warning')
|
||||
return None
|
||||
|
||||
async def edit_message(self, message_id, text, **kwargs):
|
||||
try:
|
||||
make_log(self, f"Edit message {self._chat_id}/{message_id}. Text len: {len(text)}", level='debug')
|
||||
return await self._bot.edit_message_text(
|
||||
text,
|
||||
chat_id=self._chat_id,
|
||||
message_id=message_id,
|
||||
parse_mode='html',
|
||||
disable_web_page_preview=True,
|
||||
**kwargs
|
||||
)
|
||||
except Exception as e:
|
||||
make_log(self, f"Error editing message {self._chat_id}/{message_id}. Error: {e}", level='warning')
|
||||
if 'exactly the same as a current content' in f'{e}':
|
||||
return True
|
||||
|
||||
return None
|
||||
|
||||
async def delete_message(self, message_id):
|
||||
try:
|
||||
make_log(self, f"Delete message {self._chat_id}/{message_id}", level='debug')
|
||||
return await self._bot.delete_message(
|
||||
self._chat_id,
|
||||
message_id
|
||||
)
|
||||
except Exception as e:
|
||||
make_log(self, f"Error deleting message {self._chat_id}/{message_id}. Error: {e}", level='warning')
|
||||
return None
|
||||
|
||||
async def send_photo(self, file_id, **kwargs):
|
||||
try:
|
||||
make_log(self, f"Send photo to {self._chat_id}. File: {file_id}", level='debug')
|
||||
return await self._bot.send_photo(
|
||||
self._chat_id,
|
||||
file_id,
|
||||
**kwargs
|
||||
)
|
||||
except Exception as e:
|
||||
make_log(self, f"Error sending photo to {self._chat_id}. Error: {e}", level='warning')
|
||||
return None
|
||||
|
||||
async def send_document(self, file_id, **kwargs):
|
||||
try:
|
||||
make_log(self, f"Send document to {self._chat_id}. File: {file_id}", level='debug')
|
||||
return await self._bot.send_document(
|
||||
self._chat_id,
|
||||
file_id,
|
||||
**kwargs
|
||||
)
|
||||
except Exception as e:
|
||||
make_log(self, f"Error sending document to {self._chat_id}. Error: {e}", level='warning')
|
||||
return None
|
||||
|
||||
async def send_video(self, file_id, **kwargs):
|
||||
try:
|
||||
make_log(self, f"Send video to {self._chat_id}. File: {file_id}", level='debug')
|
||||
return await self._bot.send_video(
|
||||
self._chat_id,
|
||||
file_id,
|
||||
**kwargs
|
||||
)
|
||||
except Exception as e:
|
||||
make_log(self, f"Error sending video to {self._chat_id}. Error: {e}", level='warning')
|
||||
return None
|
||||
|
||||
async def copy_message(self, from_chat_id, message_id, **kwargs):
|
||||
try:
|
||||
make_log(self, f"Copy message from {from_chat_id}/{message_id} to {self._chat_id}", level='debug')
|
||||
return await self._bot.copy_message(
|
||||
self._chat_id,
|
||||
from_chat_id,
|
||||
message_id,
|
||||
**kwargs
|
||||
)
|
||||
except Exception as e:
|
||||
make_log(self, f"Error copying message from {from_chat_id}/{message_id} to {self._chat_id}. Error: {e}", level='warning')
|
||||
return None
|
||||
|
||||
async def forward_message(self, from_chat_id, message_id, **kwargs):
|
||||
try:
|
||||
make_log(self, f"Forward message from {from_chat_id}/{message_id} to {self._chat_id}", level='debug')
|
||||
return await self._bot.forward_message(
|
||||
self._chat_id,
|
||||
from_chat_id,
|
||||
message_id,
|
||||
**kwargs
|
||||
)
|
||||
except Exception as e:
|
||||
make_log(self, f"Error forwarding message from {from_chat_id}/{message_id} to {self._chat_id}. Error: {e}", level='warning')
|
||||
return None
|
||||
@@ -0,0 +1,50 @@
|
||||
from sqlalchemy import Column, Integer, String, DateTime, JSON, Boolean
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from app.core._defaults import DEFAULT_ASSET_INITOBJ
|
||||
from app.core.models.base import AlchemyBase
|
||||
|
||||
|
||||
class Asset(AlchemyBase):
|
||||
__tablename__ = 'assets'
|
||||
|
||||
id = Column(Integer, autoincrement=True, primary_key=True)
|
||||
symbol = Column(String(32), nullable=False)
|
||||
name = Column(String(256), nullable=False)
|
||||
decimals = Column(Integer, nullable=False)
|
||||
|
||||
network = Column(String(32), nullable=True)
|
||||
address = Column(String(1024), nullable=True)
|
||||
meta = Column(JSON, nullable=False, default={})
|
||||
rates = Column(JSON, nullable=False, default={})
|
||||
|
||||
created = Column(DateTime, nullable=False, default=0)
|
||||
is_active = Column(Boolean, nullable=False, default=True)
|
||||
|
||||
balances = relationship('UserBalance', back_populates='asset')
|
||||
internal_transactions = relationship('InternalTransaction', back_populates='asset')
|
||||
|
||||
@classmethod
|
||||
def init_table(cls, engine):
|
||||
AlchemyBase.metadata.create_all(engine)
|
||||
|
||||
@classmethod
|
||||
def find(cls, session, **kwargs):
|
||||
if 'symbol' in kwargs:
|
||||
kwargs['symbol'] = kwargs['symbol'].upper()
|
||||
|
||||
result = session.query(cls).filter_by(**kwargs)
|
||||
results_count = result.count()
|
||||
if results_count == 0:
|
||||
any_count = session.query(cls).count()
|
||||
if any_count == 0:
|
||||
init_asset = cls(**DEFAULT_ASSET_INITOBJ)
|
||||
session.add(init_asset)
|
||||
session.commit()
|
||||
return cls.find(session, **kwargs)
|
||||
|
||||
raise Exception(f"Asset not found: {kwargs}")
|
||||
elif results_count == 1:
|
||||
return result.first()
|
||||
else:
|
||||
raise Exception(f"Multiple assets found: {results_count}")
|
||||
@@ -0,0 +1,3 @@
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
AlchemyBase = declarative_base()
|
||||
@@ -0,0 +1,50 @@
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app.core.logger import make_log
|
||||
|
||||
|
||||
class Memory:
|
||||
def __init__(self):
|
||||
self._execute_queue = []
|
||||
self._delayed_queue = {}
|
||||
|
||||
self.transactions_disabled = False
|
||||
|
||||
@asynccontextmanager
|
||||
async def transaction(self, desc=""):
|
||||
make_log("Memory.transaction", f"Starting transaction; {desc}", level='debug')
|
||||
while self.transactions_disabled:
|
||||
await asyncio.sleep(.2)
|
||||
|
||||
self.transactions_disabled = True
|
||||
try:
|
||||
yield None
|
||||
except BaseException as e:
|
||||
self.transactions_disabled = False
|
||||
make_log("Memory.transaction", f"Transaction error: {e}", level='error')
|
||||
raise e
|
||||
|
||||
self.transactions_disabled = False
|
||||
make_log("Memory.transaction", f"Transaction finished; {desc}", level='debug')
|
||||
|
||||
def add_task(self, _fn, *args, **kwargs):
|
||||
try:
|
||||
if type(kwargs.get("delay_s")) in [int, float]:
|
||||
kwargs['execute_ts'] = (datetime.now() + timedelta(seconds=kwargs.pop('delay_s'))).timestamp()
|
||||
|
||||
_execute_ts = kwargs.pop('execute_ts')
|
||||
_execute_ts = int(_execute_ts)
|
||||
assert _execute_ts > 0
|
||||
while _execute_ts in self._delayed_queue:
|
||||
_execute_ts += .01
|
||||
|
||||
self._delayed_queue[_execute_ts] = [_fn, args, kwargs]
|
||||
except (KeyError, ValueError, AssertionError) as e:
|
||||
if not ("execute_ts" in str(e)):
|
||||
make_log("Queue.add_task", f"Error when adding task to memory: {e}", level='error')
|
||||
|
||||
self._execute_queue.append([_fn, args, kwargs])
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, Boolean, Float
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from .base import AlchemyBase
|
||||
|
||||
|
||||
class UserBalance(AlchemyBase):
|
||||
__tablename__ = 'user_balances'
|
||||
|
||||
id = Column(Integer, autoincrement=True, primary_key=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
asset_id = Column(Integer, ForeignKey('assets.id'), nullable=False)
|
||||
balance = Column(Float, nullable=False, default=0)
|
||||
|
||||
updated = Column(DateTime, nullable=False, default=0)
|
||||
created = Column(DateTime, nullable=False, default=0)
|
||||
|
||||
user = relationship('User', uselist=False, foreign_keys=[user_id], back_populates='balances')
|
||||
asset = relationship('Asset', uselist=False, foreign_keys=[asset_id], back_populates='balances')
|
||||
|
||||
|
||||
class InternalTransaction(AlchemyBase):
|
||||
__tablename__ = 'internal_transactions'
|
||||
|
||||
id = Column(Integer, autoincrement=True, primary_key=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
asset_id = Column(Integer, ForeignKey('assets.id'), nullable=False)
|
||||
amount = Column(Float, nullable=False)
|
||||
|
||||
is_spent = Column(Boolean, nullable=False) # transaction type
|
||||
spent_transaction_id = Column(Integer, ForeignKey('internal_transactions.id'), nullable=True)
|
||||
type = Column(String(256), nullable=False, default="NOT_SPECIFIED")
|
||||
|
||||
created = Column(DateTime, nullable=False, default=0)
|
||||
|
||||
user = relationship('User', uselist=False, back_populates='internal_transactions', foreign_keys=[user_id])
|
||||
asset = relationship('Asset', uselist=False, foreign_keys=[asset_id])
|
||||
spent_transaction = relationship('InternalTransaction', uselist=False, foreign_keys=[spent_transaction_id])
|
||||
@@ -0,0 +1,29 @@
|
||||
from sqlalchemy import Column, Integer, String, BigInteger, DateTime, JSON
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from app.core.translation import TranslationCore
|
||||
from ..base import AlchemyBase
|
||||
|
||||
|
||||
class User(AlchemyBase, TranslationCore):
|
||||
LOCALE_DOMAIN = 'sanic_telegram_bot'
|
||||
|
||||
__tablename__ = 'users'
|
||||
id = Column(Integer, autoincrement=True, primary_key=True)
|
||||
telegram_id = Column(BigInteger, nullable=False)
|
||||
|
||||
username = Column(String(512), nullable=True)
|
||||
lang_code = Column(String(8), nullable=False, default="en")
|
||||
meta = Column(JSON, nullable=False, default={})
|
||||
|
||||
last_use = Column(DateTime, nullable=False, default=0)
|
||||
created = Column(DateTime, nullable=False, default=0)
|
||||
|
||||
balances = relationship('UserBalance', back_populates='user')
|
||||
internal_transactions = relationship('InternalTransaction', back_populates='user')
|
||||
wallet_connections = relationship('WalletConnection', back_populates='user')
|
||||
|
||||
def __str__(self):
|
||||
return f"User, {self.id}_{self.telegram_id} | Username: {self.username} " + '\\'
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, JSON, Boolean
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from .base import AlchemyBase
|
||||
|
||||
|
||||
class WalletConnection(AlchemyBase):
|
||||
__tablename__ = 'wallet_connections'
|
||||
|
||||
id = Column(Integer, autoincrement=True, primary_key=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
network = Column(String(32), nullable=False)
|
||||
wallet_key = Column(String(256), nullable=False)
|
||||
connection_id = Column(String(2048), nullable=False, unique=True)
|
||||
|
||||
wallet_address = Column(String(1024), nullable=False)
|
||||
|
||||
keys = Column(JSON, nullable=False, default={})
|
||||
meta = Column(JSON, nullable=False, default={})
|
||||
|
||||
created = Column(DateTime, nullable=False, default=0)
|
||||
updated = Column(DateTime, nullable=False, default=0)
|
||||
invalidated = Column(Boolean, nullable=False, default=True)
|
||||
without_pk = Column(Boolean, nullable=False, default=False)
|
||||
|
||||
user = relationship('User', uselist=False, back_populates='wallet_connections', foreign_keys=[user_id])
|
||||
|
||||
Reference in new issue
Block a user