-
Notifications
You must be signed in to change notification settings - Fork 3
feat: Add pending transaction reconcile max attempt and max age in TransactionService #136
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
stanleyyconsensys
wants to merge
3
commits into
main
Choose a base branch
from
feat/txn-reconcile
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
203 changes: 203 additions & 0 deletions
203
packages/snap/src/services/transaction/TransactionRepository.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,203 @@ | ||
| import { TransactionStatus } from '@metamask/keyring-api'; | ||
|
|
||
| import { KnownCaip2ChainId } from '../../api'; | ||
| import { AppConfig } from '../../config'; | ||
| import { generateMockTransactions } from './__mocks__/transaction.fixtures'; | ||
| import type { StellarKeyringTransaction } from './api'; | ||
| import type { TransactionStateValue } from './TransactionRepository'; | ||
| import { TransactionRepository } from './TransactionRepository'; | ||
| import { getSnapProvider } from '../../utils/snap'; | ||
| import { State } from '../state/State'; | ||
|
|
||
| jest.mock('../../utils/snap'); | ||
|
|
||
| describe('TransactionRepository', () => { | ||
| const scope = KnownCaip2ChainId.Mainnet; | ||
| const accountId = 'account-1'; | ||
|
|
||
| const defaultState: TransactionStateValue = { | ||
| transactions: {}, | ||
| lastScanTokens: {}, | ||
| }; | ||
|
|
||
| const recentTimestampSeconds = () => Math.floor(Date.now() / 1000); | ||
|
|
||
| const expiredTimestampSeconds = () => | ||
| Math.floor( | ||
| (Date.now() - AppConfig.transaction.maxPendingTransactionAge - 1000) / | ||
| 1000, | ||
| ); | ||
|
|
||
| let mockState: TransactionStateValue; | ||
|
|
||
| const createRepository = () => | ||
| new TransactionRepository( | ||
| new State({ | ||
| encrypted: false, | ||
| defaultState, | ||
| }), | ||
| ); | ||
|
|
||
| beforeEach(() => { | ||
| mockState = structuredClone(defaultState); | ||
| const snapProvider = getSnapProvider() as { request: jest.Mock }; | ||
| snapProvider.request.mockImplementation(async ({ method, params }) => { | ||
| if (method === 'snap_getState') { | ||
| if (params.key) { | ||
| return mockState[params.key as keyof TransactionStateValue]; | ||
| } | ||
| return mockState; | ||
| } | ||
|
|
||
| if (method === 'snap_manageState' && params.operation === 'update') { | ||
| mockState = params.newState as TransactionStateValue; | ||
| } | ||
|
|
||
| return null; | ||
| }); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| (getSnapProvider() as { request: jest.Mock }).request.mockReset(); | ||
| }); | ||
|
|
||
| it('removes confirmed incoming transactions from snap state', async () => { | ||
| const repository = createRepository(); | ||
| const pendingTransaction = generateMockTransactions(1, { | ||
| id: 'tx-hash-1', | ||
| account: accountId, | ||
| scope, | ||
| status: TransactionStatus.Unconfirmed, | ||
| })[0] as StellarKeyringTransaction; | ||
|
|
||
| await repository.saveMany([pendingTransaction]); | ||
|
|
||
| const confirmedTransaction = generateMockTransactions(1, { | ||
| id: 'tx-hash-1', | ||
| account: accountId, | ||
| scope, | ||
| status: TransactionStatus.Confirmed, | ||
| })[0] as StellarKeyringTransaction; | ||
|
|
||
| await repository.saveMany([confirmedTransaction]); | ||
|
|
||
| const stored = await repository.findStellarTransactionsByAccountIds([ | ||
| accountId, | ||
| ]); | ||
| expect(stored).toStrictEqual([]); | ||
| }); | ||
|
|
||
| it('keeps incoming pending over existing when reconcileAttemptCount is higher', async () => { | ||
| const repository = createRepository(); | ||
| const pendingTransaction = generateMockTransactions(1, { | ||
| id: 'tx-hash-1', | ||
| account: accountId, | ||
| scope, | ||
| status: TransactionStatus.Unconfirmed, | ||
| timestamp: 100, | ||
| })[0] as StellarKeyringTransaction; | ||
|
|
||
| await repository.saveMany([ | ||
| { | ||
| ...pendingTransaction, | ||
| reconcileAttemptCount: 1, | ||
| } as StellarKeyringTransaction, | ||
| ]); | ||
|
|
||
| await repository.saveMany([ | ||
| { | ||
| ...pendingTransaction, | ||
| reconcileAttemptCount: 2, | ||
| } as StellarKeyringTransaction, | ||
| ]); | ||
|
|
||
| const stored = await repository.findStellarTransactionsByAccountIds([ | ||
| accountId, | ||
| ]); | ||
| expect(stored).toStrictEqual([ | ||
| expect.objectContaining({ | ||
| id: 'tx-hash-1', | ||
| reconcileAttemptCount: 2, | ||
| }), | ||
| ]); | ||
| }); | ||
|
|
||
| it('drops pending transactions when reconcile attempts and max age are both exceeded', async () => { | ||
| const repository = createRepository(); | ||
| const pendingTransaction = generateMockTransactions(1, { | ||
| id: 'tx-hash-1', | ||
| account: accountId, | ||
| scope, | ||
| status: TransactionStatus.Unconfirmed, | ||
| timestamp: expiredTimestampSeconds(), | ||
| })[0] as StellarKeyringTransaction; | ||
|
|
||
| await repository.saveMany([ | ||
| { | ||
| ...pendingTransaction, | ||
| reconcileAttemptCount: 5, | ||
| } as StellarKeyringTransaction, | ||
| ]); | ||
|
|
||
| const stored = await repository.findStellarTransactionsByAccountIds([ | ||
| accountId, | ||
| ]); | ||
| expect(stored).toStrictEqual([]); | ||
| }); | ||
|
|
||
| it('keeps pending transactions when reconcile attempts exceeded but max age is not', async () => { | ||
| const repository = createRepository(); | ||
| const pendingTransaction = generateMockTransactions(1, { | ||
| id: 'tx-hash-1', | ||
| account: accountId, | ||
| scope, | ||
| status: TransactionStatus.Unconfirmed, | ||
| timestamp: recentTimestampSeconds(), | ||
| })[0] as StellarKeyringTransaction; | ||
|
|
||
| await repository.saveMany([ | ||
| { | ||
| ...pendingTransaction, | ||
| reconcileAttemptCount: 5, | ||
| } as StellarKeyringTransaction, | ||
| ]); | ||
|
|
||
| const stored = await repository.findStellarTransactionsByAccountIds([ | ||
| accountId, | ||
| ]); | ||
| expect(stored).toStrictEqual([ | ||
| expect.objectContaining({ | ||
| id: 'tx-hash-1', | ||
| reconcileAttemptCount: 5, | ||
| }), | ||
| ]); | ||
| }); | ||
|
|
||
| it('keeps pending transactions when max age exceeded but reconcile attempts are not', async () => { | ||
| const repository = createRepository(); | ||
| const pendingTransaction = generateMockTransactions(1, { | ||
| id: 'tx-hash-1', | ||
| account: accountId, | ||
| scope, | ||
| status: TransactionStatus.Unconfirmed, | ||
| timestamp: expiredTimestampSeconds(), | ||
| })[0] as StellarKeyringTransaction; | ||
|
|
||
| await repository.saveMany([ | ||
| { | ||
| ...pendingTransaction, | ||
| reconcileAttemptCount: 1, | ||
| } as StellarKeyringTransaction, | ||
| ]); | ||
|
|
||
| const stored = await repository.findStellarTransactionsByAccountIds([ | ||
| accountId, | ||
| ]); | ||
| expect(stored).toStrictEqual([ | ||
| expect.objectContaining({ | ||
| id: 'tx-hash-1', | ||
| reconcileAttemptCount: 1, | ||
| }), | ||
| ]); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,12 +3,17 @@ import { groupBy } from 'lodash'; | |
| import sortBy from 'lodash/sortBy'; | ||
| import uniqBy from 'lodash/uniqBy'; | ||
|
|
||
| import { isPendingTransactionStatus } from './utils'; | ||
| import type { StellarKeyringTransaction } from './api'; | ||
| import { | ||
| isPendingTransactionStatus, | ||
| shouldDropPendingTransaction, | ||
| toKeyringTransactions, | ||
| } from './utils'; | ||
| import type { KnownCaip2ChainId } from '../../api'; | ||
| import type { State } from '../state/State'; | ||
|
|
||
| export type TransactionStateValue = { | ||
| transactions: Record<string, KeyringTransaction[]>; | ||
| transactions: Record<string, StellarKeyringTransaction[]>; | ||
| lastScanTokens: Record<string, Record<KnownCaip2ChainId, string | null>>; | ||
| }; | ||
|
|
||
|
|
@@ -28,18 +33,29 @@ export class TransactionRepository { | |
| TransactionStateValue['transactions'] | ||
| >(this.#stateKey); | ||
|
|
||
| return Object.values(transactionsByAccount ?? {}).flat(); | ||
| return toKeyringTransactions( | ||
| Object.values(transactionsByAccount ?? {}).flat(), | ||
| ); | ||
| } | ||
|
|
||
| async findByAccountIds( | ||
| accountIds: string[], | ||
| scope?: KnownCaip2ChainId, | ||
| ): Promise<KeyringTransaction[]> { | ||
| return toKeyringTransactions( | ||
| await this.findStellarTransactionsByAccountIds(accountIds, scope), | ||
| ); | ||
| } | ||
|
|
||
| async findStellarTransactionsByAccountIds( | ||
|
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this is the only method, we return in StellarKeyringTransaction sharp, becoz there is a use case to read the attempt count for a txn |
||
| accountIds: string[], | ||
| scope?: KnownCaip2ChainId, | ||
| ): Promise<StellarKeyringTransaction[]> { | ||
| const transactionsByAccount = await this.#state.getKey< | ||
| TransactionStateValue['transactions'] | ||
| >(this.#stateKey); | ||
|
|
||
| const transactions: KeyringTransaction[] = []; | ||
| const transactions: StellarKeyringTransaction[] = []; | ||
| for (const accountId of accountIds) { | ||
| const accountTransactions = transactionsByAccount?.[accountId] ?? []; | ||
| transactions.push( | ||
|
|
@@ -58,7 +74,7 @@ export class TransactionRepository { | |
| TransactionStateValue['transactions'] | ||
| >(this.#stateKey); | ||
|
|
||
| return transactionsByAccount?.[accountId] ?? []; | ||
| return toKeyringTransactions(transactionsByAccount?.[accountId] ?? []); | ||
| } | ||
|
|
||
| async findLastScanTokenByAccountIds( | ||
|
|
@@ -78,7 +94,7 @@ export class TransactionRepository { | |
| return lastScanTokenByAccountId; | ||
| } | ||
|
|
||
| async save(transaction: KeyringTransaction): Promise<void> { | ||
| async save(transaction: StellarKeyringTransaction): Promise<void> { | ||
| await this.saveMany([transaction]); | ||
| } | ||
|
|
||
|
|
@@ -87,13 +103,14 @@ export class TransactionRepository { | |
| * | ||
| * Submitted transactions are upserted locally. Confirmed and failed transactions | ||
| * remove any matching id from snap state — durable history lives in the controller | ||
| * after AccountTransactionsUpdated is emitted. | ||
| * after AccountTransactionsUpdated is emitted. Pending transactions that exceed both | ||
| * `maxReconcileAttempts` and `maxPendingTransactionAge` are also evicted. | ||
| * | ||
| * @param transactions - Transactions to reconcile into snap state. | ||
| * @param lastScanTokens - Optional scan cursors to persist per account and scope. | ||
| */ | ||
| async saveMany( | ||
| transactions: KeyringTransaction[], | ||
| transactions: StellarKeyringTransaction[], | ||
| lastScanTokens?: Record<string, Record<KnownCaip2ChainId, string | null>>, | ||
| ): Promise<void> { | ||
| if (transactions.length === 0 && !lastScanTokens) { | ||
|
|
@@ -142,16 +159,31 @@ export class TransactionRepository { | |
| } | ||
|
|
||
| #applyTransactionUpdate( | ||
| existingTransactions: KeyringTransaction[], | ||
| incomingTransactions: KeyringTransaction[], | ||
| ): KeyringTransaction[] { | ||
| existingTransactions: StellarKeyringTransaction[], | ||
| incomingTransactions: StellarKeyringTransaction[], | ||
| ): StellarKeyringTransaction[] { | ||
| const merged = [...incomingTransactions, ...existingTransactions]; | ||
| // Merge the transactions based on transaction id and keep the latest one | ||
| // Merge the transactions based on transaction id and choose the incoming one if there are duplicates | ||
| // Sort it by timestamp in descending order | ||
| // Filter out the completed transactions | ||
| // Filter out completed transactions and pending txs eligible for eviction | ||
| return sortBy( | ||
| uniqBy(merged, 'id'), | ||
| (item) => -(item.timestamp ?? 0), | ||
| ).filter((transaction) => isPendingTransactionStatus(transaction.status)); | ||
| ).filter((transaction) => this.#canSave(transaction)); | ||
| } | ||
|
|
||
| /** | ||
| * Checks if the transaction can be saved to snap state. | ||
| * | ||
| * Keeps pending transactions unless both reconcile attempts and max age are exceeded. | ||
| * | ||
| * @param transaction - The transaction to check. | ||
| * @returns Whether the transaction can be saved to snap state. | ||
| */ | ||
| #canSave(transaction: StellarKeyringTransaction): boolean { | ||
| return ( | ||
| isPendingTransactionStatus(transaction.status) && | ||
| !shouldDropPendingTransaction(transaction) | ||
| ); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
most of the method, we will re-sharp the result to KeyringTransaction
with that we can avoid too much change on handler side