Skip to content

Commit

Permalink
Implement tzkt balance provider
Browse files Browse the repository at this point in the history
  • Loading branch information
maxima-net committed Aug 17, 2022
1 parent b701f70 commit 9915137
Show file tree
Hide file tree
Showing 11 changed files with 76 additions and 36 deletions.
7 changes: 4 additions & 3 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@
"cSpell.language": "en",
"cSpell.words": [
"atomex",
"tezos",
"outdir",
"esbuild",
"taquito"
"outdir",
"taquito",
"tezos",
"Tzkt"
]
}
1 change: 0 additions & 1 deletion src/clients/rest/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
export { HttpClient, type RequestOptions } from './httpClient';
export { RestAtomexClient, type RestAtomexClientOptions } from './restAtomexClient';
2 changes: 1 addition & 1 deletion src/clients/rest/restAtomexClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { AuthorizationManager } from '../../authorization/index';
import type { Transaction } from '../../blockchain/index';
import type { AtomexNetwork, CancelAllSide, CurrenciesProvider, Side } from '../../common/index';
import { EventEmitter } from '../../core';
import { HttpClient } from '../../core/index';
import {
Order, OrderBook, Quote, ExchangeSymbol, NewOrderRequest,
OrdersSelector, CancelOrderRequest,
Expand All @@ -17,7 +18,6 @@ import {
mapOrderBookDtoToOrderBook, mapOrderDtosToOrders, mapOrderDtoToOrder,
mapQuoteDtosToQuotes, mapSwapDtosToSwaps, mapSwapDtoToSwap, mapSymbolDtosToSymbols
} from '../helpers';
import { HttpClient } from './httpClient';

export interface RestAtomexClientOptions {
atomexNetwork: AtomexNetwork;
Expand Down
13 changes: 8 additions & 5 deletions src/clients/rest/httpClient.ts → src/core/httpClient.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import type { DeepRequired } from '../../core/index';

type QueryParams = { [key: string]: string | number | boolean | null | undefined };
type Payload = { [key: string]: unknown };

Expand All @@ -12,11 +10,16 @@ export interface RequestOptions {
}

export class HttpClient {
private static readonly defaultUndefinedResponseStatuses = [404];

constructor(
protected readonly baseUrl: string
) { }

async request<T>(options: RequestOptions): Promise<T | undefined> {
async request<T>(options: RequestOptions): Promise<T | undefined>;
async request<T>(options: RequestOptions, returnUndefinedOn404: true): Promise<T | undefined>;
async request<T>(options: RequestOptions, returnUndefinedOn404: false): Promise<T>;
async request<T>(options: RequestOptions, returnUndefinedOn404 = true): Promise<T | undefined> {
const url = new URL(options.urlPath, this.baseUrl);

if (options.params)
Expand All @@ -28,7 +31,7 @@ export class HttpClient {
body: options.payload ? JSON.stringify(options.payload) : undefined
});

if (response.status === 404)
if (returnUndefinedOn404 && response.status === 404)
return undefined;

if (!response.ok) {
Expand All @@ -39,7 +42,7 @@ export class HttpClient {
return await response.json();
}

private setSearchParams(url: URL, params: DeepRequired<RequestOptions['params']>) {
private setSearchParams(url: URL, params: RequestOptions['params']) {
for (const key in params) {
const value = params[key];
if (value !== null && value !== undefined)
Expand Down
1 change: 1 addition & 0 deletions src/core/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { EventEmitter } from './eventEmitter';
export { DeferredEventEmitter } from './deferredEventEmitter';
export { HttpClient, type RequestOptions } from './httpClient';

export type { Result, SuccessResult, ErrorResult } from './result';
export type { PublicEventEmitter, ToEventEmitter, ToEventEmitters } from './eventEmitter';
Expand Down
2 changes: 1 addition & 1 deletion src/tezos/balancesProviders/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { TezosBalancesProvider } from './tezosBalancesProvider';
export { TzktBalancesProvider } from './tzktBalancesProvider';
18 changes: 0 additions & 18 deletions src/tezos/balancesProviders/tezosBalancesProvider.ts

This file was deleted.

54 changes: 54 additions & 0 deletions src/tezos/balancesProviders/tzktBalancesProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type BigNumber from 'bignumber.js';

import type { BalancesProvider } from '../../blockchain/index';
import type { Currency } from '../../common/index';
import { HttpClient } from '../../core/index';
import { numberToTokensAmount } from '../../utils/converters';
import type { FA12TezosCurrency, FA2TezosCurrency, NativeTezosCurrency } from '../models/index';
import { isTezosCurrency } from '../utils/index';

export class TzktBalancesProvider implements BalancesProvider {
private readonly httpClient: HttpClient;

constructor(baseUrl: string) {
this.httpClient = new HttpClient(baseUrl);
}

async getBalance(address: string, currency: Currency): Promise<BigNumber> {
if (!isTezosCurrency(currency))
throw new Error('Not tezos blockchain currency provided');

switch (currency.type) {
case 'native':
return await this.getNativeTokenBalance(address, currency);

case 'fa1.2':
case 'fa2':
return await this.getTokenBalance(address, currency);
}
}

private async getNativeTokenBalance(address: string, currency: NativeTezosCurrency): Promise<BigNumber> {
const urlPath = `/v1/accounts/${address}/balance`;
const balance = await this.httpClient.request<number>({ urlPath }, false);

return numberToTokensAmount(balance, currency.decimals);
}

private async getTokenBalance(address: string, currency: FA12TezosCurrency | FA2TezosCurrency): Promise<BigNumber> {
const urlPath = '/v1/tokens/balances';
const params = {
'account': address,
'token.contract': currency.contractAddress,
'token.tokenId': currency.type === 'fa1.2' ? 0 : currency.tokenId,
'select': 'balance'
};

const balances = await this.httpClient.request<number[]>({ urlPath, params }, false);
const balance = balances[0];
if (balance === undefined)
throw new Error('Invalid response');

return numberToTokensAmount(balance, currency.decimals);
}
}
6 changes: 3 additions & 3 deletions src/tezos/config/defaultOptions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { AtomexBlockchainNetworkOptions, AtomexContext, AtomexCurrencyOptions } from '../../atomex/index';
import { FA12TezosTaquitoAtomexProtocolV1, FA2TezosTaquitoAtomexProtocolV1, TezosTaquitoAtomexProtocolV1 } from '../atomexProtocol';
import { TezosBalancesProvider } from '../balancesProviders/index';
import { TzktBalancesProvider } from '../balancesProviders/index';
import { TaquitoBlockchainToolkitProvider } from '../blockchainToolkitProviders/index';
import type { TezosCurrency } from '../models';
import { TezosSwapTransactionsProvider } from '../swapTransactionsProviders/index';
Expand Down Expand Up @@ -81,15 +81,15 @@ export const createDefaultTezosBlockchainOptions = (atomexContext: AtomexContext
currencies: tezosMainnetCurrencies,
currencyOptions: createCurrencyOptions(atomexContext, tezosMainnetCurrencies, mainnetTezosTaquitoAtomexProtocolV1Options),
blockchainToolkitProvider: new TaquitoBlockchainToolkitProvider(mainnetRpcUrl),
balancesProvider: new TezosBalancesProvider('https://api.mainnet.tzkt.io/'),
balancesProvider: new TzktBalancesProvider('https://api.mainnet.tzkt.io/'),
swapTransactionsProvider,
}
: {
rpcUrl: testNetRpcUrl,
currencies: tezosTestnetCurrencies,
currencyOptions: createCurrencyOptions(atomexContext, tezosTestnetCurrencies, testnetTezosTaquitoAtomexProtocolV1Options),
blockchainToolkitProvider: new TaquitoBlockchainToolkitProvider(testNetRpcUrl),
balancesProvider: new TezosBalancesProvider('https://api.ghostnet.tzkt.io/'),
balancesProvider: new TzktBalancesProvider('https://api.ghostnet.tzkt.io/'),
swapTransactionsProvider,
};

Expand Down
2 changes: 1 addition & 1 deletion src/tezos/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export { TaquitoBlockchainWallet } from './wallets/index';
export { TezosTaquitoAtomexProtocolV1, FA12TezosTaquitoAtomexProtocolV1, FA2TezosTaquitoAtomexProtocolV1 } from './atomexProtocol/index';
export { TezosBalancesProvider } from './balancesProviders';
export { TzktBalancesProvider } from './balancesProviders';
export { TezosSwapTransactionsProvider } from './swapTransactionsProviders';
export { TaquitoBlockchainToolkitProvider } from './blockchainToolkitProviders';
export { tezosMainnetCurrencies, tezosTestnetCurrencies, createDefaultTezosBlockchainOptions } from './config/index';
Expand Down
6 changes: 3 additions & 3 deletions tests/blockchain/atomexBlockchainProvider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
} from '../../src/ethereum/index';
import { Web3BlockchainToolkitProvider } from '../../src/evm/index';
import {
TezosBalancesProvider, TaquitoBlockchainToolkitProvider, TezosCurrency, TezosSwapTransactionsProvider
TzktBalancesProvider, TaquitoBlockchainToolkitProvider, TezosCurrency, TezosSwapTransactionsProvider
} from '../../src/tezos/index';

describe('Atomex Blockchain Provider', () => {
Expand Down Expand Up @@ -41,7 +41,7 @@ describe('Atomex Blockchain Provider', () => {
test('applies blockchain options and returns them', () => {
const tezosNetworkOptions: AtomexBlockchainNetworkOptions = {
rpcUrl: '',
balancesProvider: new TezosBalancesProvider(),
balancesProvider: new TzktBalancesProvider(''),
blockchainToolkitProvider: new TaquitoBlockchainToolkitProvider(''),
swapTransactionsProvider: new TezosSwapTransactionsProvider(),
currencies: [tezosNativeCurrency],
Expand Down Expand Up @@ -79,7 +79,7 @@ describe('Atomex Blockchain Provider', () => {
try {
const networkOptions: AtomexBlockchainNetworkOptions = {
rpcUrl: '',
balancesProvider: new TezosBalancesProvider(),
balancesProvider: new TzktBalancesProvider(''),
blockchainToolkitProvider: new TaquitoBlockchainToolkitProvider(''),
swapTransactionsProvider: new TezosSwapTransactionsProvider(),
currencies: [tezosNativeCurrency],
Expand Down

0 comments on commit 9915137

Please sign in to comment.