Skip to content

Commit

Permalink
Merge pull request #258 from docknetwork/DCKM-468-wallet-700-transact…
Browse files Browse the repository at this point in the history
…ion-history-is-not-fetched

Dckm 468 wallet 700 transaction history is not fetched
  • Loading branch information
maycon-mello authored May 1, 2024
2 parents 973be74 + 9420079 commit b975a32
Show file tree
Hide file tree
Showing 7 changed files with 92 additions and 78 deletions.
24 changes: 24 additions & 0 deletions integration-tests/subscan.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import {fetchTransactions} from '@docknetwork/wallet-sdk-wasm/src/core/subscan';

const accountAddress = '3HM9DYxHe5tAwh2cuErNHiLxSMDJhetxaVGCDTYXiwyuuHN6';

function validateSchema(item) {
expect(item.from).toBeDefined();
expect(item.to).toBeDefined();
expect(item.hash).toBeDefined();
expect(item.amount).toBeDefined();
expect(item.amount_v2).toBeDefined();
expect(item.fee).toBeDefined();
}

describe('subscan integration', () => {
it('should fetch transactions using subscan APIs', async () => {
const {items} = await fetchTransactions({
address: accountAddress,
});

expect(items.length > 0).toBe(true);

items.forEach(validateSchema);
});
});
19 changes: 19 additions & 0 deletions integration-tests/transactions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
getWallet,
setupEnvironent,
} from './helpers';
import {NetworkManager} from '@docknetwork/wallet-sdk-wasm/src/modules/network-manager';

describe('Transactions', () => {
let wallet;
Expand Down Expand Up @@ -39,5 +40,23 @@ describe('Transactions', () => {
expect(feeAmount > 0).toBeTruthy();
});

it('should fetch transaction history', async () => {
NetworkManager.getInstance().setNetworkId('mainnet');
const txModule = Transactions.getInstance();
const accountAddress = '3HM9DYxHe5tAwh2cuErNHiLxSMDJhetxaVGCDTYXiwyuuHN6';
await txModule.loadExternalTransactions(accountAddress);
const transactions = await txModule.loadTransactions(accountAddress);
console.log(`${transactions.length} Transactions fetched`);

expect(transactions.length >= 12).toBeTruthy();

const transaction = transactions.find(tx => tx.hash === '0x72bf313be160e6273a133ede20176e419af488d68826a478c02ff06b8db2888b');

expect(transaction).toBeDefined();
expect(transaction.amount).toBe(52981);
expect(transaction.feeAmount).toBe(2.085);
});


afterAll(() => closeWallet());
});
15 changes: 10 additions & 5 deletions packages/react-native/lib/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,18 @@ export async function getOrCreateWallet(params: DataStoreConfigs = {} as any) {

return wallet;
}

export const DEFAULT_WALLET_CONFIGS: any = {
databasePath: 'dock-wallet',
dbType: 'react-native',
testNetworkId: 'testnet',
mainNetworkId: 'mainnet',
documentNetworkResolver: dockDocumentNetworkResolver,
};

export async function initializeWallet(params: DataStoreConfigs = {} as any) {
const _wallet = await createWallet({
databasePath: 'dock-wallet',
dbType: 'react-native',
testNetworkId: 'testnet',
mainNetworkId: 'mainnet',
documentNetworkResolver: dockDocumentNetworkResolver,
...DEFAULT_WALLET_CONFIGS,
...params,
});

Expand Down
38 changes: 32 additions & 6 deletions packages/transactions/lib/transactions.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,16 @@ async function addTransaction(transaction) {
}
}

async function addTransactions(transactions) {
try {
const data = await getAllTransactions();
data.push(...transactions);
await getLocalStorage().setItem('transactions', JSON.stringify(data));
} catch (err) {
console.error(err);
}
}

async function upsertTransaction(transaction) {
try {
const data = await getAllTransactions();
Expand Down Expand Up @@ -137,6 +147,10 @@ async function removeTransaction(transactionId) {
}
}

function isV1Transaction(tx) {
return typeof tx.amount === 'string';
}

/** Transactions */
export class Transactions {
constructor(accounts: Accounts) {
Expand Down Expand Up @@ -213,16 +227,26 @@ export class Transactions {
dbTransactions = [];
}

const handleTransaction = tx => {
const v1Transactions = dbTransactions.filter(isV1Transaction);

if (v1Transactions.length) {
dbTransactions = [];
// Remove all transactions from cache in case v1 items are found
// It will force a re-fetch using v2 API
await getLocalStorage().setItem('transactions', JSON.stringify([]));
}

const parseTransaction = tx => {
if (tx.from !== address && tx.to !== address) {
return;
}
if (dbTransactions.find(item => item.hash === tx.hash)) {
const txExists = dbTransactions.find(item => item.hash === tx.hash);
if (txExists) {
return;
}
const newTx = {
amount: tx.amount,
feeAmount: tx.fee,
amount: parseFloat(tx.amount),
feeAmount: parseInt(tx.fee, 10) / 1000000,
recipientAddress: tx.to,
fromAddress: tx.from,
id: tx.hash,
Expand All @@ -231,14 +255,16 @@ export class Transactions {
status: 'complete',
date: new Date(parseInt(tx.block_timestamp + '000', 10)),
};
addTransaction(newTx);

return newTx;
};
let data;
let page = 0;
do {
try {
data = await fetchTransactions({address, page});
data.items.forEach(handleTransaction);
const transactionsToAdd = data.items.map(parseTransaction).filter(Boolean);
await addTransactions(transactionsToAdd);
Wallet.getInstance().eventManager.emit(
TransactionEvents.added,
address,
Expand Down
7 changes: 3 additions & 4 deletions packages/wasm/src/core/subscan.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,11 @@ axiosRetry(axios, {
});

const SUBSCAN_URL = 'https://dock.api.subscan.io';
export const SUBSCAN_TRANSFER_URL = `${SUBSCAN_URL}/api/v2/scan/transfers`;

const queue = new TaskQueue(global.Promise, 1);

function doFetchTransactions({address, page = 0, itemsPerPage = 50}) {
const url = `${SUBSCAN_URL}/api/scan/transfers`;

assert(typeof address === 'string', 'address must be a string');
assert(typeof page === 'number', 'page must be a number');
assert(typeof itemsPerPage === 'number', 'itemsPerPage must be a number');
Expand All @@ -32,13 +31,13 @@ function doFetchTransactions({address, page = 0, itemsPerPage = 50}) {
};

Logger.info(
`Fetching transactions from subscan ${url} with body ${JSON.stringify(
`Fetching transactions from subscan ${SUBSCAN_TRANSFER_URL} with body ${JSON.stringify(
body,
)}`,
);

return axios
.post(url, body, {})
.post(SUBSCAN_TRANSFER_URL, body, {})
.then(res => {
const {data, message} = res.data;

Expand Down
13 changes: 4 additions & 9 deletions packages/wasm/src/test/axiosMocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,18 @@ import MockAdapter from 'axios-mock-adapter';
import successData from './fixtures/subscan-success.json';
import paramsFailure from './fixtures/subscan-failure.json';
import requestFailure from './fixtures/subscan-too-many-requests.json';
import {SUBSCAN_TRANSFER_URL} from '../core/subscan';

const mockAdapter = new MockAdapter(axios);

export function mockSubscanSuccess() {
mockAdapter
.onPost('https://dock.api.subscan.io/api/scan/transfers')
.replyOnce(200, successData);
mockAdapter.onPost(SUBSCAN_TRANSFER_URL).replyOnce(200, successData);
}

export function mockSubscanParamsFailure() {
mockAdapter
.onPost('https://dock.api.subscan.io/api/scan/transfers')
.replyOnce(200, paramsFailure);
mockAdapter.onPost(SUBSCAN_TRANSFER_URL).replyOnce(200, paramsFailure);
}

export function mockSubscanRequestFailure() {
mockAdapter
.onPost('https://dock.api.subscan.io/api/scan/transfers')
.replyOnce(429, requestFailure);
mockAdapter.onPost(SUBSCAN_TRANSFER_URL).replyOnce(429, requestFailure);
}
54 changes: 0 additions & 54 deletions packages/wasm/src/test/subscan-mock.test.js

This file was deleted.

0 comments on commit b975a32

Please sign in to comment.