1
0
personal-data/personal_data/fetchers/defi_partisia_blockchain.py

183 lines
5.6 KiB
Python
Raw Normal View History

2024-04-16 21:23:27 +00:00
import dataclasses
import datetime
2024-04-23 20:58:25 +00:00
import email.utils
2024-04-16 21:38:35 +00:00
import json
2024-04-23 20:58:25 +00:00
import logging
2024-05-15 22:47:42 +00:00
from collections.abc import Iterator, Mapping
2024-04-16 22:02:51 +00:00
from decimal import Decimal
2024-04-16 21:23:27 +00:00
2024-05-21 21:37:59 +00:00
import requests
2024-05-15 22:47:42 +00:00
from frozendict import frozendict
2024-04-16 21:23:27 +00:00
from personal_data.data import DeduplicateMode, Scraper
2024-04-23 20:58:25 +00:00
2024-04-16 22:48:21 +00:00
from .. import secrets
2024-04-16 21:23:27 +00:00
logger = logging.getLogger(__name__)
# mainnet: https://reader.partisiablockchain.com
# testnet: https://node1.testnet.partisiablockchain.com
HOSTNAME = 'reader.partisiablockchain.com'
URL_ACCOUNT_PLUGIN = 'https://{hostname}/{shard}blockchain/accountPlugin/local'
2024-04-16 21:38:35 +00:00
URL_ACCOUNT_PLUGIN_GLOBAL = 'https://{hostname}/{shard}blockchain/accountPlugin/global'
2024-05-21 21:37:59 +00:00
URL_CONTRACT_STATE = 'https://{hostname}/{shard}blockchain/contracts/{address}?requireContractState=false'
2024-04-16 21:23:27 +00:00
2024-05-15 22:52:13 +00:00
MPC_DECIMALS = 10000
2024-04-23 20:58:25 +00:00
2024-05-16 22:24:01 +00:00
2024-04-23 16:04:12 +00:00
def shard_id_for_address(address: str) -> str:
2024-05-21 21:37:59 +00:00
if address.endswith('a'):
return 'shards/Shard0/' # TODO
elif address.endswith('2'):
return 'shards/Shard1/' # TODO
else:
return 'shards/Shard2/' # TODO
2024-04-23 20:58:25 +00:00
2024-04-23 16:04:12 +00:00
2024-04-16 21:23:27 +00:00
@dataclasses.dataclass(frozen=True)
2024-05-21 21:37:59 +00:00
class Balances:
update_time: datetime.datetime
balances: Mapping[str, Decimal]
2024-04-16 21:23:27 +00:00
2024-05-21 21:37:59 +00:00
@dataclasses.dataclass(frozen=True)
class PbcClient:
session: requests.Session
def get_json(
2024-05-22 21:21:29 +00:00
self,
url: str,
data: Mapping[str, str] = frozendict(),
method='POST',
2024-05-21 21:37:59 +00:00
) -> tuple[dict, datetime.datetime]:
2024-04-16 22:02:51 +00:00
headers = {
2024-04-23 20:58:25 +00:00
'Content-Type': 'application/json',
'Accept': 'application/json',
2024-04-16 22:02:51 +00:00
}
2024-05-21 21:37:59 +00:00
response = self.session.request(
2024-05-22 21:21:29 +00:00
method,
url,
headers=headers,
data=json.dumps(data),
2024-05-21 21:37:59 +00:00
)
2024-04-16 22:02:51 +00:00
response.raise_for_status()
2024-04-23 20:58:25 +00:00
date_text = response.headers.get('last-modified') or response.headers.get(
'date',
)
2024-04-23 20:11:43 +00:00
date = email.utils.parsedate_to_datetime(date_text)
2024-04-17 22:24:19 +00:00
json_data = response.json()
if json_data is None:
msg = 'No result data for ' + url
raise Exception(msg)
2024-05-21 21:37:59 +00:00
return (json_data, date)
2024-04-16 22:02:51 +00:00
2024-05-21 21:37:59 +00:00
def determine_coins(self) -> list[dict[str, str]]:
2024-04-23 20:58:25 +00:00
data: dict = {'path': []}
2024-04-16 22:02:51 +00:00
url = URL_ACCOUNT_PLUGIN_GLOBAL.format(
2024-04-23 20:58:25 +00:00
hostname=HOSTNAME,
shard='',
2024-04-16 22:02:51 +00:00
)
json_data, date = self.get_json(url, data=data)
return json_data['coins']['coins']
2024-05-21 21:37:59 +00:00
def get_account_balances(self, address: str) -> Balances:
2024-04-16 22:02:51 +00:00
coins = self.determine_coins()
2024-04-16 21:23:27 +00:00
url = URL_ACCOUNT_PLUGIN.format(
2024-04-23 20:58:25 +00:00
hostname=HOSTNAME,
shard=shard_id_for_address(address),
2024-04-16 21:23:27 +00:00
)
2024-04-23 20:58:25 +00:00
data: dict = {
'path': [
{'type': 'field', 'name': 'accounts'},
{'type': 'avl', 'keyType': 'BLOCKCHAIN_ADDRESS', 'key': address},
],
}
2024-04-16 22:02:51 +00:00
account_data, date = self.get_json(url, data=data)
2024-04-16 21:23:27 +00:00
2024-05-21 21:37:59 +00:00
balances: dict[str, Decimal] = {}
balances['MPC'] = Decimal(account_data['mpcTokens']) / MPC_DECIMALS
2024-04-16 22:02:51 +00:00
for coin_idx, amount_data in enumerate(account_data['accountCoins']):
2024-04-23 20:58:25 +00:00
coin_data = coins[coin_idx]
byoc_balance = Decimal(amount_data['balance'])
2024-04-16 22:02:51 +00:00
denominator = Decimal(coin_data['conversionRate']['denominator'])
native_balance = byoc_balance / denominator
2024-05-21 21:37:59 +00:00
balances[coin_data['symbol']] = native_balance
2024-04-16 22:02:51 +00:00
del coin_idx, coin_data
2024-04-16 21:23:27 +00:00
2024-05-21 21:37:59 +00:00
return Balances(date, balances)
def get_contract_state(self, address: str) -> tuple[dict, datetime.datetime]:
url = URL_CONTRACT_STATE.format(
hostname=HOSTNAME,
shard=shard_id_for_address(address),
address=address,
)
data: dict = {'path': []}
return self.get_json(url, data=data)
@dataclasses.dataclass(frozen=True)
class MpcBalance(Scraper):
dataset_name = 'defi_mpc_balance'
deduplicate_mode = DeduplicateMode.ONLY_LATEST
deduplicate_ignore_columns = ['account.update_time']
def scrape_balances_for(self, address: str) -> frozendict[str, object]:
client = PbcClient(self.session)
balances = client.get_account_balances(address)
data_point = {
'account.address': address,
'account.update_time': balances.update_time,
}
for token, amount in balances.balances.items():
data_point['balance.' + token] = amount
del token, amount
2024-05-15 22:47:42 +00:00
return frozendict(data_point)
def scrape(self) -> Iterator[Mapping[str, object]]:
2024-05-21 21:37:59 +00:00
yield self.scrape_balances_for(secrets.PBC_ACCOUNT_ADDRESS)
PBC_FOUNDATION_CONTRACT_ADDRESSES = [
('012635f1c0a9bffd59853c6496e1c26ebda0e2b4da', 'Foundation Sales'),
('0135edec2c9fed33f45cf2538dc06ba139c4bb8f62', 'Foundation Team'),
('01ad44bb0277a8df16408006c375a6fa015bb22c97', 'Foundation Eco-System'),
]
@dataclasses.dataclass(frozen=True)
class PbcFoundationBalance(Scraper):
dataset_name = 'pbc_foundation_balances'
deduplicate_mode = DeduplicateMode.BY_ALL_COLUMNS
deduplicate_ignore_columns = [
'contract.update_time',
'contract.name',
'contract.state.balance',
]
def scrape(self) -> Iterator[Mapping[str, object]]:
client = PbcClient(self.session)
for address, contract_name in PBC_FOUNDATION_CONTRACT_ADDRESSES:
contract_state, update_time = client.get_contract_state(address)
yield {
'contract.update_time': update_time,
'contract.name': contract_name,
'contract.address': address,
'contract.state.nonce': contract_state['nonce'],
'contract.state.balance': contract_state['remainingTokens'],
}