Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
56 changes: 20 additions & 36 deletions src/integration/blockchain/cardano/cardano-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import {
Value,
Vkeywitnesses,
} from '@emurgo/cardano-serialization-lib-nodejs';
import { ApiVersion, CardanoRosetta, Network as TatumNetwork, TatumSDK } from '@tatumio/tatum';
import blake from 'blakejs';
import { Config } from 'src/config/config';
import { Asset } from 'src/shared/models/asset/asset.entity';
Expand All @@ -31,7 +30,13 @@ import { BlockchainClient } from '../shared/util/blockchain-client';
import { CardanoWallet } from './cardano-wallet';
import { CardanoUtil } from './cardano.util';
import { CardanoTransactionMapper } from './dto/cardano-transaction.mapper';
import { CardanoBlockResponse, CardanoTransactionDto, CardanoTransactionResponse } from './dto/cardano.dto';
import {
CardanoBalanceResponse,
CardanoBlockResponse,
CardanoInfoResponse,
CardanoTransactionDto,
CardanoTransactionResponse,
} from './dto/cardano.dto';

interface NetworkParameterStaticInfo {
min_fee_a: number;
Expand All @@ -41,9 +46,6 @@ interface NetworkParameterStaticInfo {
export class CardanoClient extends BlockchainClient {
private readonly wallet: CardanoWallet;

private readonly networkIdentifier = { blockchain: 'cardano', network: 'mainnet' };

private tatumSdk: CardanoRosetta;
private blockFrostApi: BlockFrostAPI;

private readonly networkParameterCache = new AsyncCache<NetworkParameterStaticInfo>(
Expand All @@ -61,25 +63,17 @@ export class CardanoClient extends BlockchainClient {
}

async getBlockHeight(): Promise<number> {
const tatumSdk = await this.getTatumSdk();
const networkStatus = await tatumSdk.rpc.getNetworkStatus({
networkIdentifier: this.networkIdentifier,
});
return networkStatus.current_block_identifier.index;
const info = await this.getNetworkInfo();
return info.tip;
}

async getNativeCoinBalance(): Promise<number> {
return this.getNativeCoinBalanceForAddress(this.walletAddress);
}

async getNativeCoinBalanceForAddress(address: string): Promise<number> {
const tatumSdk = await this.getTatumSdk();
const accountBalance = await tatumSdk.rpc.getAccountBalance({
networkIdentifier: this.networkIdentifier,
accountIdentifier: { address },
});

const adaBalance = accountBalance.balances.find((b) => b.currency.symbol === 'ADA');
const balances = await this.getAccountBalances(address);
const adaBalance = balances.find((b) => b.currency.symbol === 'ADA');
if (!adaBalance) return 0;

return CardanoUtil.fromLovelaceAmount(adaBalance.value, adaBalance.currency.decimals);
Expand All @@ -93,20 +87,12 @@ export class CardanoClient extends BlockchainClient {

async getTokenBalances(assets: Asset[], address?: string): Promise<BlockchainTokenBalance[]> {
const owner = address ?? this.walletAddress;

const tatumSdk = await this.getTatumSdk();
const accountBalance = await tatumSdk.rpc.getAccountBalance({
networkIdentifier: this.networkIdentifier,
accountIdentifier: { address: owner },
});
const balances = await this.getAccountBalances(owner);

const tokenBalances: BlockchainTokenBalance[] = [];

for (const asset of assets) {
// Cardano native tokens use policy_id.asset_name format
const tokenBalance = accountBalance.balances.find(
(b) => b.currency.symbol === asset.chainId || b.currency.metadata?.policyId === asset.chainId,
);
const tokenBalance = balances.find((b) => b.currency.symbol === asset.chainId);

if (tokenBalance) {
const balance = CardanoUtil.fromLovelaceAmount(tokenBalance.value, tokenBalance.currency.decimals);
Expand Down Expand Up @@ -333,16 +319,14 @@ export class CardanoClient extends BlockchainClient {
}

// --- HELPER METHODS --- //
private async getTatumSdk(): Promise<CardanoRosetta> {
if (!this.tatumSdk) {
this.tatumSdk = await TatumSDK.init<CardanoRosetta>({
version: ApiVersion.V3,
network: TatumNetwork.CARDANO_ROSETTA,
apiKey: Config.blockchain.cardano.cardanoTatumApiKey,
});
}
private async getNetworkInfo(): Promise<CardanoInfoResponse> {
const url = Config.blockchain.cardano.cardanoApiUrl;
return this.http.get<CardanoInfoResponse>(`${url}/info`, this.httpConfig());
}

return this.tatumSdk;
private async getAccountBalances(address: string): Promise<CardanoBalanceResponse[]> {
const url = Config.blockchain.cardano.cardanoApiUrl;
return this.http.get<CardanoBalanceResponse[]>(`${url}/account/${address}`, this.httpConfig());
}

private getBlockFrostAPI(): BlockFrostAPI {
Expand Down
13 changes: 13 additions & 0 deletions src/integration/blockchain/cardano/dto/cardano.dto.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
export interface CardanoInfoResponse {
testnet: boolean;
tip: number;
}

export interface CardanoBalanceResponse {
value: string;
currency: {
symbol: string;
decimals: number;
};
}

export interface CardanoBlockResponse {
hash: string;
number: number;
Expand Down
17 changes: 17 additions & 0 deletions src/integration/blockchain/tron/dto/tron.dto.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
export interface TronAccountResponse {
balance: number;
createTime: number;
trc10: { key: string; value: number }[];
trc20: Record<string, string>[];
freeNetLimit: number;
bandwidth: number;
}

export interface TronAddressBalance {
asset: string;
type: string;
balance: string;
decimals: number;
tokenAddress?: string;
}

export interface TronChainParameterDto {
bandwidthUnitPrice: number;
energyUnitPrice: number;
Expand Down
79 changes: 45 additions & 34 deletions src/integration/blockchain/tron/tron-client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { AddressBalance, ApiVersion, Network as TatumNetwork, TatumSDK, Tron } from '@tatumio/tatum';
import { TronWalletProvider } from '@tatumio/tron-wallet-provider';
import { Config } from 'src/config/config';
import { Asset } from 'src/shared/models/asset/asset.entity';
import { HttpRequestConfig, HttpService } from 'src/shared/services/http.service';
Expand All @@ -9,15 +7,19 @@ import { BlockchainSignedTransactionResponse } from '../shared/dto/signed-transa
import { WalletAccount } from '../shared/evm/domain/wallet-account';
import { BlockchainClient } from '../shared/util/blockchain-client';
import { TronTransactionMapper } from './dto/tron-transaction.mapper';
import { TronChainParameterDto, TronTransactionDto, TronTransactionResponse } from './dto/tron.dto';
import {
TronAccountResponse,
TronAddressBalance,
TronChainParameterDto,
TronTransactionDto,
TronTransactionResponse,
} from './dto/tron.dto';
import { TronWallet } from './tron-wallet';
import { TronUtil } from './tron.util';

export class TronClient extends BlockchainClient {
private readonly wallet: TronWallet;

private tatumSdk: Tron;

constructor(private readonly http: HttpService) {
super();

Expand All @@ -29,27 +31,19 @@ export class TronClient extends BlockchainClient {
}

async getBlockHeight(): Promise<number> {
const tatumSdk = await this.getTatumSdk();
return tatumSdk.rpc.getNowBlock().then((nb) => nb.block_header.raw_data.number);
const url = Config.blockchain.tron.tronApiUrl;
const info = await this.http.get<{ blockNumber: number }>(`${url}/info`, this.httpConfig());
return info.blockNumber;
}

async getNativeCoinBalance(): Promise<number> {
return this.getNativeCoinBalanceForAddress(this.walletAddress);
}

async getNativeCoinBalanceForAddress(address: string): Promise<number> {
const tatumSdk = await this.getTatumSdk();
const addressBalanceResponse = await tatumSdk.address.getBalance({ address });
if (addressBalanceResponse.error)
throw new Error(
`Cannot detect native coin balance of address ${address}: ${addressBalanceResponse.error.message.join('; ')}`,
);

const allAddressBalanceCoinData = addressBalanceResponse.data.filter(
(d) => d.asset === 'TRX' && Util.equalsIgnoreCase(d.type, 'native'),
);

return Util.sum(allAddressBalanceCoinData.map((d) => TronUtil.fromSunAmount(d.balance, d.decimals)));
const balances = await this.getAddressBalances(address);
const trxBalance = balances.find((d) => d.asset === 'TRX' && Util.equalsIgnoreCase(d.type, 'native'));
return trxBalance ? TronUtil.fromSunAmount(trxBalance.balance, trxBalance.decimals) : 0;
}

async getTokenBalance(asset: Asset, address?: string): Promise<number> {
Expand All @@ -60,13 +54,10 @@ export class TronClient extends BlockchainClient {

async getTokenBalances(assets: Asset[], address?: string): Promise<BlockchainTokenBalance[]> {
const owner = address ?? this.walletAddress;
const balances = await this.getAddressBalances(owner);

const tatumSdk = await this.getTatumSdk();
const addressBalanceResponse = await tatumSdk.address.getBalance({ address: owner });
if (addressBalanceResponse.error) throw new Error(`Cannot detect token balances of owner ${owner}`);

const allAddressBalanceTokenMap: Map<string, AddressBalance> = new Map(
addressBalanceResponse.data.filter((ab) => ab.tokenAddress).map((ab) => [ab.tokenAddress.toLowerCase(), ab]),
const allAddressBalanceTokenMap: Map<string, TronAddressBalance> = new Map(
balances.filter((ab) => ab.tokenAddress).map((ab) => [ab.tokenAddress.toLowerCase(), ab]),
);

const tokenBalances: BlockchainTokenBalance[] = [];
Expand Down Expand Up @@ -310,17 +301,37 @@ export class TronClient extends BlockchainClient {
}

// --- HELPER METHODS --- //
private async getTatumSdk(): Promise<Tron> {
if (!this.tatumSdk) {
this.tatumSdk = await TatumSDK.init<Tron>({
version: ApiVersion.V3,
network: TatumNetwork.TRON,
apiKey: Config.blockchain.tron.tronApiKey,
configureWalletProviders: [TronWalletProvider],
});
private async getAddressBalances(address: string): Promise<TronAddressBalance[]> {
const url = Config.blockchain.tron.tronApiUrl;
const response = await this.http.get<TronAccountResponse>(`${url}/account/${address}`, this.httpConfig());

const balances: TronAddressBalance[] = [];

// Native TRX balance (in SUN, 6 decimals)
balances.push({
asset: 'TRX',
type: 'native',
balance: response.balance?.toString() ?? '0',
decimals: 6,
});

// TRC10 tokens
if (response.trc10) {
for (const token of response.trc10) {
balances.push({ asset: token.key, type: 'trc10', balance: token.value.toString(), decimals: 0 });
}
}

// TRC20 tokens
if (response.trc20) {
for (const tokenObj of response.trc20) {
for (const [contractAddress, balance] of Object.entries(tokenObj)) {
balances.push({ asset: contractAddress, type: 'trc20', balance, decimals: 6, tokenAddress: contractAddress });
}
}
}

return this.tatumSdk;
return balances;
}

private httpConfig(): HttpRequestConfig {
Expand Down
6 changes: 6 additions & 0 deletions src/shared/i18n/de/invoice.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@
"title": "Rechnung Nr. {invoiceId}",
"credit_title": "Gutschrift Nr. {invoiceId}",
"receipt_title": "Transaktionsbestätigung Nr. {invoiceId}",
"multi_receipt_title": "Transaktionsbestätigung",
"section": {
"buy": "Käufe",
"sell": "Verkäufe"
},
"table": {
"headers": {
"quantity": "Menge",
"description": "Beschreibung",
"date": "Datum",
"total": "Gesamt"
},
"position_row": {
Expand Down
6 changes: 6 additions & 0 deletions src/shared/i18n/en/invoice.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@
"title": "Invoice No. {invoiceId}",
"credit_title": "Credit No. {invoiceId}",
"receipt_title": "Transaction Confirmation No. {invoiceId}",
"multi_receipt_title": "Transaction Confirmation",
"section": {
"buy": "Purchases",
"sell": "Sales"
},
"table": {
"headers": {
"quantity": "Quantity",
"description": "Description",
"date": "Date",
"total": "Total"
},
"position_row": {
Expand Down
6 changes: 6 additions & 0 deletions src/shared/i18n/fr/invoice.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@
"title": "Facture No. {invoiceId}",
"credit_title": "Crédit No. {invoiceId}",
"receipt_title": "Confirmation de Transaction No. {invoiceId}",
"multi_receipt_title": "Confirmation de Transaction",
"section": {
"buy": "Achats",
"sell": "Ventes"
},
"table": {
"headers": {
"quantity": "Quantité",
"description": "Description",
"date": "Date",
"total": "Total"
},
"position_row": {
Expand Down
6 changes: 6 additions & 0 deletions src/shared/i18n/it/invoice.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@
"title": "Fattura No. {invoiceId}",
"credit_title": "Credito No. {invoiceId}",
"receipt_title": "Conferma di Transazione No. {invoiceId}",
"multi_receipt_title": "Conferma di Transazione",
"section": {
"buy": "Acquisti",
"sell": "Vendite"
},
"table": {
"headers": {
"quantity": "Quantità",
"description": "Descrizione",
"date": "Data",
"total": "Totale"
},
"position_row": {
Expand Down
Loading
Loading