-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathkeyring-wrapper.test.ts
More file actions
319 lines (261 loc) · 9.36 KB
/
Copy pathkeyring-wrapper.test.ts
File metadata and controls
319 lines (261 loc) · 9.36 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import type { Keyring, AccountId } from '@metamask/keyring-utils';
import type { Hex, Json } from '@metamask/utils';
import { v4 as uuidv4 } from 'uuid';
import { KeyringWrapper } from './keyring-wrapper';
import type { KeyringAccount } from '../../account';
import type { KeyringCapabilities } from '../keyring-capabilities';
import { KeyringVersion } from '../keyring-capabilities';
import { KeyringType } from '../keyring-type';
class TestKeyringWrapper extends KeyringWrapper<TestKeyring> {
async getAccounts(): Promise<KeyringAccount[]> {
const addresses = await this.inner.getAccounts();
const scopes = this.capabilities.scopes ?? ['eip155:1'];
return addresses.map((address) => {
// Check if already in registry
const existingId = this.registry.getAccountId(address);
if (existingId) {
const cached = this.registry.get(existingId);
if (cached) {
return cached;
}
}
const id = this.registry.register(address);
const account: KeyringAccount = {
id,
type: 'eip155:eoa',
address,
scopes,
options: {},
methods: [],
};
this.registry.set(account);
return account;
});
}
public deletedAccountIds: AccountId[] = [];
async createAccounts(): Promise<KeyringAccount[]> {
return this.getAccounts();
}
async deleteAccount(accountId: AccountId): Promise<void> {
this.deletedAccountIds.push(accountId);
this.registry.delete(accountId);
}
async submitRequest(): Promise<any> {
return {};
}
}
/**
* A test wrapper that does NOT cache accounts in getAccounts().
* This is used to test the fallback path in KeyringWrapper.getAccount().
*/
class NoCacheTestKeyringWrapper extends KeyringWrapper<TestKeyring> {
async getAccounts(): Promise<KeyringAccount[]> {
const addresses = await this.inner.getAccounts();
const scopes = this.capabilities.scopes ?? ['eip155:1'];
return addresses.map((address) => {
const id = this.registry.register(address);
const account: KeyringAccount = {
id,
type: 'eip155:eoa',
address,
scopes,
options: {},
methods: [],
};
// NOTE: We intentionally do NOT call this.registry.set(account) here
// to test the fallback path in KeyringWrapper.getAccount()
return account;
});
}
async createAccounts(): Promise<KeyringAccount[]> {
return this.getAccounts();
}
async deleteAccount(): Promise<void> {
// no-op
}
async submitRequest(): Promise<any> {
return {};
}
}
class TestKeyring implements Keyring {
static type = 'Test Keyring';
public type = TestKeyring.type;
readonly #accounts: Hex[];
public lastDeserializedState: Json | undefined;
constructor(addresses: Hex[] = []) {
this.#accounts = addresses;
}
async serialize(): Promise<Json> {
return { accounts: this.#accounts };
}
async deserialize(state: Json): Promise<void> {
this.lastDeserializedState = state;
}
async getAccounts(): Promise<Hex[]> {
return this.#accounts;
}
async addAccounts(_numberOfAccounts = 1): Promise<Hex[]> {
return this.#accounts;
}
}
const capabilities: KeyringCapabilities = {
versions: [KeyringVersion.V2],
scopes: ['eip155:10'],
};
describe('KeyringWrapper', () => {
it('serializes and deserializes via the inner keyring', async () => {
const inner = new TestKeyring(['0x1']);
const wrapper = new TestKeyringWrapper({
inner,
type: KeyringType.Hd,
capabilities,
});
const state = await wrapper.serialize();
expect(state).toStrictEqual({ accounts: ['0x1'] });
await wrapper.deserialize(state);
expect(inner.lastDeserializedState).toStrictEqual(state);
});
it('returns accounts with stable IDs and correct addresses', async () => {
const addresses = ['0x1' as const, '0x2' as const];
const inner = new TestKeyring(addresses);
const wrapper = new TestKeyringWrapper({
inner,
type: KeyringType.Hd,
capabilities,
});
const accounts = await wrapper.getAccounts();
expect(accounts).toHaveLength(addresses.length);
const ids = new Set<string>();
accounts.forEach((account: KeyringAccount, index) => {
expect(account.address).toBe(addresses[index]);
expect(account.type).toBe('eip155:eoa');
expect(account.scopes).toStrictEqual(capabilities.scopes);
expect(account.options).toStrictEqual({});
expect(account.methods).toStrictEqual([]);
ids.add(account.id);
});
// Ensure IDs are unique
expect(ids.size).toBe(addresses.length);
// getAccount should resolve by ID
const [firstAccount] = accounts;
expect(firstAccount).toBeDefined();
if (!firstAccount) {
throw new Error('Expected at least one account from the wrapper');
}
const resolved = await wrapper.getAccount(firstAccount.id);
expect(resolved.address).toBe(firstAccount.address);
// Should return the exact same object from cache
expect(resolved).toBe(firstAccount);
});
it('returns cached account on subsequent getAccount calls (O(1) lookup)', async () => {
const addresses = ['0x1' as const];
const inner = new TestKeyring(addresses);
const wrapper = new TestKeyringWrapper({
inner,
type: KeyringType.Hd,
capabilities,
});
// First call populates the registry
const accounts = await wrapper.getAccounts();
const firstAccount = accounts[0];
expect(firstAccount).toBeDefined();
// Second call should hit the cache and return the same object
const cachedAccount = await wrapper.getAccount(
firstAccount?.id as AccountId,
);
expect(cachedAccount).toBe(firstAccount);
});
it('populates registry and returns account when not initially cached', async () => {
const addresses = ['0x1' as const];
const inner = new TestKeyring(addresses);
const wrapper = new TestKeyringWrapper({
inner,
type: KeyringType.Hd,
capabilities,
});
// Manually register an address to get a consistent account ID
// but DON'T call registry.set() to store the full account
const address = addresses[0];
// eslint-disable-next-line jest/no-if
if (!address) {
throw new Error('Expected at least one address');
}
// eslint-disable-next-line dot-notation
const accountId = wrapper['registry'].register(address);
// Now getAccount should:
// 1. Not find the account in cache (line 131-133 fails)
// 2. Call getAccounts() to prime (line 136)
// 3. Find the account in cache after priming (line 139-142)
// 4. Return the cached result (line 144)
const resolvedAccount = await wrapper.getAccount(accountId);
expect(resolvedAccount.address).toBe(address);
expect(resolvedAccount.id).toBe(accountId);
});
it('throws when getAccounts does not populate the registry', async () => {
const addresses = ['0x1' as const];
const inner = new TestKeyring(addresses);
const wrapper = new NoCacheTestKeyringWrapper({
inner,
type: KeyringType.Hd,
capabilities,
});
// Get account by calling getAccounts first to know the ID
const accounts = await wrapper.getAccounts();
const firstAccount = accounts[0];
expect(firstAccount).toBeDefined();
// The NoCacheTestKeyringWrapper doesn't cache accounts via registry.set(),
// so getAccount will fail because the registry doesn't have the full account
await expect(
wrapper.getAccount(firstAccount?.id as AccountId),
).rejects.toThrow('Account not found for id');
});
it('throws when requesting an unknown account', async () => {
const inner = new TestKeyring([]);
const wrapper = new TestKeyringWrapper({
inner,
type: KeyringType.Hd,
capabilities,
});
await expect(wrapper.getAccount(uuidv4())).rejects.toThrow(
'Account not found for id',
);
});
it('throws when account mapping exists but account object cannot be found', async () => {
const addresses = ['0x1' as const];
const inner = new TestKeyring(addresses);
const wrapper = new TestKeyringWrapper({
inner,
type: KeyringType.Hd,
capabilities,
});
// Prime the registry by calling getAccounts once
const accounts = await wrapper.getAccounts();
const firstAccount = accounts[0];
expect(firstAccount).toBeDefined();
// Now, simulate a missing account by creating a new wrapper with empty inner
// but the registry won't have any accounts since it's a new instance
const emptyInner = new TestKeyring([] as Hex[]);
const inconsistentWrapper = new TestKeyringWrapper({
inner: emptyInner,
type: KeyringType.Hd,
capabilities,
});
// Use the account ID from the first wrapper - the new wrapper won't have it
await expect(
inconsistentWrapper.getAccount(firstAccount?.id as AccountId),
).rejects.toThrow('Account not found for id');
});
it('falls back to mainnet scope when capabilities.scopes is not set', async () => {
const addresses = ['0x1' as const];
const inner = new TestKeyring(addresses);
const wrapper = new TestKeyringWrapper({
inner,
type: KeyringType.Hd,
// Explicitly omit scopes to exercise the default fallback.
capabilities: {} as KeyringCapabilities,
});
const accounts = await wrapper.getAccounts();
expect(accounts).toHaveLength(1);
expect(accounts[0]?.scopes).toStrictEqual(['eip155:1']);
});
});