-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathstorage.ts
88 lines (73 loc) · 2.42 KB
/
storage.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { PersistedKeys } from '../loader'
import { Transaction } from './type'
import type { ChainId } from '@dcl/schemas/dist/dapps/chain-id'
const transactions = new Map<string, Transaction[]>()
function getKey(address: string, chainId: ChainId) {
return [PersistedKeys.Transactions, address, chainId].join('.')
}
// TODO(#323): remove on v6, use radash replaceOrAppend instead https://radash-docs.vercel.app/docs/array-replace-or-append
function injectTransaction(
transaction: Transaction,
transactions: Transaction[] = []
): Transaction[] {
if (transactions.length === 0) {
return [transaction]
}
let replaced = false
transactions = transactions.map((tx) => {
if (tx.hash === transaction.hash) {
replaced = true
return {
...transaction,
chainId:
typeof transaction.chainId === 'string'
? parseInt(transaction.chainId, 16)
: transaction.chainId,
}
}
return tx
})
return replaced ? transactions : [transaction, ...transactions]
}
export function storeTransactions(
address: string,
chainId: ChainId,
txs: Transaction[]
) {
const key = getKey(address, chainId)
let memoryTransasctions: Transaction[] = transactions.get(key) || []
let storageTransactions: Transaction[] = JSON.parse(
localStorage.getItem(key) || '[]'
)
for (const tx of txs) {
memoryTransasctions = injectTransaction(tx, memoryTransasctions)
storageTransactions = injectTransaction(tx, storageTransactions)
}
const filteredMemoryTransasctions = memoryTransasctions.filter(
(tx) => tx.chainId === chainId
)
if (memoryTransasctions.length !== filteredMemoryTransasctions.length) {
memoryTransasctions = filteredMemoryTransasctions
}
transactions.set(key, memoryTransasctions)
localStorage.setItem(key, JSON.stringify(storageTransactions))
return memoryTransasctions
}
export function restoreTransactions(
address: string,
chainId: ChainId
): Transaction[] {
const key = getKey(address, chainId)
if (!transactions.has(key)) {
const storedTransactions = JSON.parse(
localStorage.getItem(key) || '[]'
) as Transaction[]
transactions.set(key, storedTransactions)
}
return transactions.get(key)!.filter((tx) => tx.chainId === chainId)
}
export function clearTransactions(address: string, chainId: ChainId): void {
const key = getKey(address, chainId)
transactions.delete(key)
localStorage.removeItem(key)
}