Розробка платформи крипто-бухгалтерії
Крипто-бухгалтерія складніша за традиційну через специфіку активів: токени не мають єдиної біржі, DeFi операції нестандартні, і кожна транзакція вимагає справедливої ринкової вартості на момент події. Платформа повинна автоматизувати весь цикл: імпорт транзакцій → класифікація → розрахунок собівартості → формування звітності.
Архітектура платформи
Багатоджерельний імпорт
class TransactionImportService {
async importFromSource(source: DataSource, accountId: string): Promise<ImportResult> {
switch (source.type) {
case "exchange_api":
return this.importFromExchangeAPI(source, accountId);
case "wallet_address":
return this.importFromBlockchain(source.address, source.blockchain, accountId);
case "csv_file":
return this.importFromCSV(source.file, source.format, accountId);
case "hardware_wallet":
return this.importFromHardwareWallet(source, accountId);
}
}
private async importFromExchangeAPI(source: ExchangeSource, accountId: string) {
const connector = this.getExchangeConnector(source.exchange);
// Отримуємо всі транзакції з моменту останнього імпорту
const lastImport = await db.getLastImportTime(accountId, source.exchange);
const transactions = await connector.getTransactions({ since: lastImport });
// Нормалізуємо до єдиного формату
const normalized = transactions.map(tx => this.normalizeTransaction(tx, source.exchange));
await db.saveTransactions(accountId, normalized);
return { imported: normalized.length, source: source.exchange };
}
private async importFromBlockchain(
address: string,
blockchain: string,
accountId: string
): Promise<ImportResult> {
// Використовуємо The Graph або Moralis для індексованих даних
const indexer = this.getBlockchainIndexer(blockchain);
const transactions = await indexer.getAddressTransactions(address);
// DeFi специфіка: розшифруємо calldata для розуміння що сталося
const decoded = await Promise.all(
transactions.map(tx => this.decodeDeFiTransaction(tx, blockchain))
);
await db.saveTransactions(accountId, decoded.flat());
return { imported: decoded.flat().length };
}
}
Коннектори бірж
class BinanceConnector implements ExchangeConnector {
async getTransactions(params: { since: Date }): Promise<RawTransaction[]> {
const results: RawTransaction[] = [];
// Binance має різні endpoints для різних типів
const [spot, futures, staking, savings] = await Promise.all([
this.binance.getSpotTrades(params.since),
this.binance.getFuturesTrades(params.since),
this.binance.getStakingHistory(params.since),
this.binance.getSavingsHistory(params.since),
]);
return [...spot, ...futures, ...staking, ...savings];
}
}
// Єдиний нормалізований формат
function normalizeBinanceTrade(trade: BinanceTrade): UnifiedTransaction {
return {
id: trade.id.toString(),
timestamp: new Date(trade.time),
type: trade.isBuyer ? TransactionType.BUY : TransactionType.SELL,
assetIn: trade.isBuyer ? trade.symbol.replace("USDT", "") : "USDT",
amountIn: trade.isBuyer ? parseFloat(trade.qty) : parseFloat(trade.quoteQty),
assetOut: trade.isBuyer ? "USDT" : trade.symbol.replace("USDT", ""),
amountOut: trade.isBuyer ? parseFloat(trade.quoteQty) : parseFloat(trade.qty),
fee: parseFloat(trade.commission),
feeCurrency: trade.commissionAsset,
exchange: "BINANCE",
};
}
Автоматична класифікація
class TransactionClassifier {
async classify(tx: UnifiedTransaction): Promise<ClassifiedTransaction> {
// Прості випадки
if (tx.assetOut === "USD" || tx.assetOut === "USDT" || tx.assetOut === "USDC") {
return { ...tx, taxCategory: TaxCategory.DISPOSAL, confidence: 0.95 };
}
if (tx.type === TransactionType.STAKING_REWARD || tx.type === TransactionType.INTEREST) {
return { ...tx, taxCategory: TaxCategory.INCOME, confidence: 0.95 };
}
if (tx.type === TransactionType.TRANSFER && await this.isSelfTransfer(tx)) {
return { ...tx, taxCategory: TaxCategory.NON_TAXABLE, confidence: 0.90 };
}
// DeFi операції — потрібен додатковий аналіз
if (tx.source === "defi") {
return this.classifyDeFiTransaction(tx);
}
// Обмін крипто-на-крипто
if (this.isCryptoSwap(tx)) {
return { ...tx, taxCategory: TaxCategory.DISPOSAL, subType: "SWAP", confidence: 0.85 };
}
// Вимагає ручної класифікації
return { ...tx, taxCategory: TaxCategory.UNCLASSIFIED, confidence: 0, requiresReview: true };
}
private async isSelfTransfer(tx: UnifiedTransaction): Promise<boolean> {
// Перевіряємо чи адреси відправника та отримувача належать одному користувачу
if (!tx.fromAddress || !tx.toAddress) return false;
const user = tx.userId;
const [fromOwned, toOwned] = await Promise.all([
db.isUserAddress(user, tx.fromAddress),
db.isUserAddress(user, tx.toAddress),
]);
return fromOwned && toOwned;
}
}
DeFi розшифровування
async function decodeDeFiTransaction(tx: BlockchainTx): Promise<UnifiedTransaction[]> {
// Розшифровуємо input data для відомих протоколів
const protocol = identifyProtocol(tx.to);
switch (protocol) {
case "UNISWAP_V3": {
const decoded = uniswapV3Interface.parseTransaction({ data: tx.data });
if (decoded.name === "exactInputSingle" || decoded.name === "exactInput") {
return [createSwapTransaction(tx, decoded)];
}
break;
}
case "AAVE_V3": {
const decoded = aaveV3Interface.parseTransaction({ data: tx.data });
if (decoded.name === "supply") {
return [createLendingDeposit(tx, decoded)];
}
if (decoded.name === "withdraw") {
return [createLendingWithdraw(tx, decoded), createInterestIncome(tx, decoded)];
}
break;
}
case "CURVE": {
return decodeCurveSwap(tx);
}
}
// Невідомий протокол — повертаємо raw
return [createRawTransaction(tx)];
}
Мультиюрисдикційна звітність
class TaxReportGenerator {
async generateReport(
accountId: string,
taxYear: number,
jurisdiction: string
): Promise<TaxReport> {
const events = await this.getTaxEvents(accountId, taxYear);
switch (jurisdiction) {
case "US": return this.generateUS8949(events, taxYear);
case "UK": return this.generateUKCGT(events, taxYear);
case "DE": return this.generateGermanReport(events, taxYear);
case "AU": return this.generateAUCGT(events, taxYear);
default: return this.generateGenericReport(events, taxYear);
}
}
private async generateUS8949(events: TaxEvent[], taxYear: number): Promise<TaxReport> {
// Формат IRS Form 8949
const shortTerm = events.filter(e => !e.isLongTerm);
const longTerm = events.filter(e => e.isLongTerm);
return {
format: "IRS-8949",
year: taxYear,
shortTermGains: shortTerm.reduce((sum, e) => sum + e.gainOrLoss, 0),
longTermGains: longTerm.reduce((sum, e) => sum + e.gainOrLoss, 0),
transactions: events.map(this.formatFor8949),
summary: this.generateScheduleD(shortTerm, longTerm),
};
}
}
Стек
| Компонент | Технологія |
|---|---|
| Коннектори бірж | Node.js + офіційні SDK |
| Індексування блокчейну | The Graph + Moralis |
| Двигун собівартості | PostgreSQL + TimescaleDB |
| Історія цін | CoinGecko API + власний кеш |
| Генерування звітів | PDFKit + ExcelJS + CSV |
| Frontend | React + Recharts (графіки) |
| Черга | BullMQ (асинхронні робочі місця імпорту) |
Повна платформа крипто-бухгалтерії з підтримкою 10+ бірж, DeFi розшифруванням та мультиюрисдикційними звітами: 3-4 місяці розробки.







