Skip to content
Open
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
3 changes: 2 additions & 1 deletion packages/coin-support-near/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
"@cypherock/sdk-utils": "^0.0.17",
"axios": "^1.4.0",
"lodash": "^4.17.21",
"rxjs": "^7.8.1"
"rxjs": "^7.8.1",
"zod": "^3.21.4"
},
"lint-staged": {
"*.{ts,tsx}": [
Expand Down
5 changes: 3 additions & 2 deletions packages/coin-support-near/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
IGetExplorerLink,
ISignMessageEvent,
IFormatAddressParams,
ISyncAccountsParams,
} from '@cypherock/coin-support-interfaces';
import { ITransaction } from '@cypherock/db-interfaces';
import { nearApiJsLibType, setNearApiJs } from '@cypherock/sdk-app-near';
Expand All @@ -37,8 +38,8 @@ export class NearSupport implements CoinSupport {
return operations.createAccounts(params);
}

public syncAccount(): Observable<void> {
throw new Error('Not implemented');
public syncAccount(params: ISyncAccountsParams): Observable<void> {
return operations.syncAccount(params);
}

public async initializeTransaction(): Promise<IPreparedTransaction> {
Expand Down
1 change: 1 addition & 0 deletions packages/coin-support-near/src/operations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ export * from './syncPriceHistories';
export * from './getCoinAllocations';
export * from './createAccounts';
export * from './receive';
export * from './syncAccount';
export * from './getAccountHistory';
export * from './getExplorerLink';
133 changes: 133 additions & 0 deletions packages/coin-support-near/src/operations/syncAccount/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import {
createSyncAccountsObservable,
IGetAddressDetails,
} from '@cypherock/coin-support-utils';
import {
IAccount,
ITransaction,
TransactionStatusMap,
TransactionTypeMap,
} from '@cypherock/db-interfaces';
import { getTransactions } from '../../services';

import { BigNumber } from '@cypherock/cysync-utils';
import lodash from 'lodash';
import { ISyncNearAccountsParams } from './types';

const PER_PAGE_TXN_LIMIT = 100;

interface GetTransactionParserParams {
address: string;
account: IAccount;
}

const getTransactionParser = (
_params: GetTransactionParserParams,
): ((transaction: any) => ITransaction) => {
const myAddress = _params.address;
const { account } = _params;

return (transaction: any): ITransaction => {
const fromAddr = transaction.predecessor_account_id;
const toAddr = transaction.receiver_account_id;
const amount = new BigNumber(transaction.actions_agg.deposit).toFixed();
const fees = new BigNumber(
transaction.outcomes_agg.transaction_fee,
).toFixed();
const timestamp = new BigNumber(transaction.block_timestamp)
.dividedBy(1_000_000)
.toNumber();

const txn: ITransaction = {
hash: transaction.transaction_hash,
accountId: account.__id ?? '',
walletId: account.walletId,
assetId: account.parentAssetId,
parentAssetId: account.parentAssetId,
familyId: account.familyId,
amount,
fees,
confirmations: 1,
status: transaction.outcomes.status
? TransactionStatusMap.success
: TransactionStatusMap.failed,
type:
myAddress === fromAddr
? TransactionTypeMap.send
: TransactionTypeMap.receive,
timestamp,
blockHeight: transaction.block.block_height,
inputs: [
{
address: fromAddr,
amount,
isMine: myAddress === fromAddr,
},
],
outputs: [
{
address: toAddr,
amount,
isMine: myAddress === toAddr,
},
],
extraData: {
receiptId: transaction.receipt_id,
includedInBlockHash: transaction.included_in_block_hash,
actions: transaction.actions,
logs: transaction.logs,
},
};

return txn;
};
};

const getAddressDetails: IGetAddressDetails<{
page: number;
perPage: number;
transactionsInDb: ITransaction[];
}> = async ({ db, account, iterationContext }) => {
const page = iterationContext?.page ?? 1;
const perPage = iterationContext?.perPage ?? PER_PAGE_TXN_LIMIT;
const transactionsInDb =
iterationContext?.transactionsInDb ??
(await db.transaction.getAll({
accountId: account.__id,
assetId: account.parentAssetId,
}));

const response = await getTransactions({
address: account.xpubOrAddress,
assetId: account.parentAssetId,
page: iterationContext?.page ?? page,
perPage: iterationContext?.perPage ?? perPage,
order: 'desc',
});

const transactionParser = getTransactionParser({
address: account.xpubOrAddress,
account,
});

const transactions = response.transactions.map(transactionParser);
const hasMore =
lodash.intersectionBy(transactionsInDb, transactions, 'hash').length > 0;

return {
hasMore,
nextIterationContext: {
page: page + 1,
perPage,
transactionsInDb,
},
transactions,
updatedAccountInfo: {},
};
};

export const syncAccount = (params: ISyncNearAccountsParams) =>
createSyncAccountsObservable({
...params,
getAddressDetails,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { ISyncAccountsParams } from '@cypherock/coin-support-interfaces';

export type ISyncNearAccountsParams = ISyncAccountsParams;
62 changes: 45 additions & 17 deletions packages/coin-support-near/src/services/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { nearCoinList } from '@cypherock/coins';
import axios from 'axios';

import { ServerError, ServerErrorType } from '@cypherock/coin-support-utils';
import { config } from '../config';
import { NearTransactionsApiResponseSchema } from '../validators';

const baseURL = `${config.API_CYPHEROCK}/near`;
const baseURL = `${config.API_CYPHEROCK}/v2/near`;

export const getBalance = async (
address: string,
Expand All @@ -17,7 +19,6 @@ export const getBalance = async (
const response = await axios.post(url, {
address,
network: nearCoinList[assetId].network,
responseType: 'v2',
});

const { balance, nativeBalance, reservedStorage } = response.data;
Expand All @@ -29,34 +30,61 @@ export const getBalance = async (
};
};

export const getTransactions = async (
address: string,
assetId: string,
from?: number,
limit?: number,
) => {
interface GetTransactionsParams {
address: string;
assetId: string;
page: number;
perPage: number;
order: 'desc' | 'asc';
}

export const getTransactions = async ({
address,
assetId,
page,
perPage,
order,
}: GetTransactionsParams) => {
const url = `${baseURL}/transaction/history`;
const response = await axios.post(url, {
address,
network: nearCoinList[assetId].network,
responseType: 'v2',
limit,
from,
page,
perPage,
order,
});

const parseResult = NearTransactionsApiResponseSchema.safeParse(
response.data,
);

if (parseResult.success === false) {
throw new ServerError(
ServerErrorType.INVALID_RESPONSE,
'Invalid Response for Near Transactions',
{
responseBody: response.data,
url,
status: response.status,
},
);
}

const hasMore = parseResult.data.length === perPage;
return {
transactions: response.data.data,
hasMore: response.data.more,
transactions: parseResult.data,
hasMore,
};
};

export const getTransactionCount = async (address: string, assetId: string) => {
const { transactions } = await getTransactions(
const { transactions } = await getTransactions({
address,
assetId,
undefined,
1,
);
page: 1,
perPage: 1,
order: 'asc',
});

const isUsed = transactions && transactions.length > 0;

Expand Down
9 changes: 9 additions & 0 deletions packages/coin-support-near/src/validators/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { AxiosError } from 'axios';

export class ApiResponseValidationError extends AxiosError {
public isApiResponseValidationError = true;

constructor(message?: string) {
super(message ?? 'Invalid response from server');
}
}
2 changes: 2 additions & 0 deletions packages/coin-support-near/src/validators/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './transactionsApiResponse';
export * from './error';
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { z } from 'zod';

const Action = z.object({
action: z.string(),
method: z.string().nullable(),
});

const Outcome = z.object({
status: z.boolean(),
});

const Block = z.object({
block_height: z.number(),
});

const OutcomesAgg = z.object({
transaction_fee: z.number(),
});

const ActionsAgg = z.object({
deposit: z.number(),
});

const Receipt = z.object({
transaction_hash: z.string(),
outcomes: Outcome,
predecessor_account_id: z.string(),
receiver_account_id: z.string(),
actions_agg: ActionsAgg,
outcomes_agg: OutcomesAgg,
block_timestamp: z.string(),
block: Block,
receipt_id: z.string(),
included_in_block_hash: z.string(),
actions: z.array(Action),
logs: z.array(z.string()),
});

export const NearTransactionsApiResponseSchema = z.array(Receipt);
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export enum ServerErrorType {
UNKNOWN_ERROR = 'SER_0000',
CONNOT_CONNECT = 'SER_0001',
INVALID_RESPONSE = 'SER_0002',
}

type CodeToErrorMap = {
Expand All @@ -16,6 +17,9 @@ export const serverErrorTypeDetails: CodeToErrorMap = {
[ServerErrorType.CONNOT_CONNECT]: {
message: 'Cannot connect to the server',
},
[ServerErrorType.INVALID_RESPONSE]: {
message: 'Invalid response from server',
},
};

export interface ServerErrorDetails {
Expand Down
17 changes: 9 additions & 8 deletions packages/coin-support-utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
export * from './createAccount';
export * from './receive';
export * from './common';
export * from './syncAccount';
export * from './unit';
export * from './createAccount';
export * from './db';
export * from './signTransaction';
export * from './errors';
export * from './getAccountHistory';
export * from './getCoinAllocations';
export * from './receive';
export * from './signMessage';
export * from './syncPrices';
export * from './signTransaction';
export * from './syncAccount';
export * from './syncPriceHistories';
export * from './getCoinAllocations';
export * from './getAccountHistory';
export * from './syncPrices';
export * from './unit';
export { updateLogger } from './utils/logger';
4 changes: 3 additions & 1 deletion packages/cysync-core/src/constants/errors/serverError.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ServerErrorType } from '~/errors';
import { ServerErrorType } from '@cypherock/coin-support-utils';
import { ILangState } from '~/store';

import { createErrorHandlingDetailsGenerator } from './helpers';
Expand All @@ -18,6 +18,8 @@ export const getServerErrorHandlingDetails = (
> = {
[ServerErrorType.UNKNOWN_ERROR]: generateErrorHandlingDetails.report(),
[ServerErrorType.CONNOT_CONNECT]: generateErrorHandlingDetails.retry(),
[ServerErrorType.INVALID_RESPONSE]:
generateErrorHandlingDetails.retryWithReport(),
};

return serverErrorHandlingDetailsMap[errorCode];
Expand Down
Loading