@hashgraph/hedera-wallet-connect 1.3.7-canary.de9fb58.0 → 1.3.8-canary.09d9623.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/{src/lib → lib}/dapp/DAppSigner.d.ts +18 -2
  2. package/dist/{src/lib → lib}/dapp/DAppSigner.js +109 -30
  3. package/dist/{src/lib → lib}/dapp/index.d.ts +4 -0
  4. package/dist/{src/lib → lib}/dapp/index.js +39 -40
  5. package/dist/{src/lib → lib}/shared/logger.d.ts +1 -0
  6. package/dist/{src/lib → lib}/shared/logger.js +3 -0
  7. package/dist/{src/lib → lib}/shared/utils.d.ts +8 -2
  8. package/dist/{src/lib → lib}/shared/utils.js +10 -2
  9. package/package.json +4 -3
  10. package/dist/test/_helpers.d.ts +0 -38
  11. package/dist/test/_helpers.js +0 -95
  12. package/dist/test/dapp/DAppConnector.test.d.ts +0 -1
  13. package/dist/test/dapp/DAppConnector.test.js +0 -232
  14. package/dist/test/dapp/DAppSigner.test.d.ts +0 -1
  15. package/dist/test/dapp/DAppSigner.test.js +0 -625
  16. package/dist/test/shared/logger.test.d.ts +0 -1
  17. package/dist/test/shared/logger.test.js +0 -129
  18. package/dist/test/utils.test.d.ts +0 -1
  19. package/dist/test/utils.test.js +0 -201
  20. package/dist/test/wallet/methods/wallet-executeTransaction.test.d.ts +0 -1
  21. package/dist/test/wallet/methods/wallet-executeTransaction.test.js +0 -43
  22. package/dist/test/wallet/methods/wallet-getNodeAddresses.test.d.ts +0 -1
  23. package/dist/test/wallet/methods/wallet-getNodeAddresses.test.js +0 -40
  24. package/dist/test/wallet/methods/wallet-signAndExecuteQuery.test.d.ts +0 -1
  25. package/dist/test/wallet/methods/wallet-signAndExecuteQuery.test.js +0 -41
  26. package/dist/test/wallet/methods/wallet-signAndExecuteTransaction.test.d.ts +0 -1
  27. package/dist/test/wallet/methods/wallet-signAndExecuteTransaction.test.js +0 -48
  28. package/dist/test/wallet/methods/wallet-signMessage.test.d.ts +0 -1
  29. package/dist/test/wallet/methods/wallet-signMessage.test.js +0 -60
  30. package/dist/test/wallet/methods/wallet-signTransaction.test.d.ts +0 -1
  31. package/dist/test/wallet/methods/wallet-signTransaction.test.js +0 -47
  32. package/dist/test/wallet/wallet-init.test.d.ts +0 -1
  33. package/dist/test/wallet/wallet-init.test.js +0 -53
  34. /package/dist/{src/index.d.ts → index.d.ts} +0 -0
  35. /package/dist/{src/index.js → index.js} +0 -0
  36. /package/dist/{src/lib → lib}/index.d.ts +0 -0
  37. /package/dist/{src/lib → lib}/index.js +0 -0
  38. /package/dist/{src/lib → lib}/shared/chainIds.d.ts +0 -0
  39. /package/dist/{src/lib → lib}/shared/chainIds.js +0 -0
  40. /package/dist/{src/lib → lib}/shared/errors.d.ts +0 -0
  41. /package/dist/{src/lib → lib}/shared/errors.js +0 -0
  42. /package/dist/{src/lib → lib}/shared/events.d.ts +0 -0
  43. /package/dist/{src/lib → lib}/shared/events.js +0 -0
  44. /package/dist/{src/lib → lib}/shared/extensionController.d.ts +0 -0
  45. /package/dist/{src/lib → lib}/shared/extensionController.js +0 -0
  46. /package/dist/{src/lib → lib}/shared/index.d.ts +0 -0
  47. /package/dist/{src/lib → lib}/shared/index.js +0 -0
  48. /package/dist/{src/lib → lib}/shared/methods.d.ts +0 -0
  49. /package/dist/{src/lib → lib}/shared/methods.js +0 -0
  50. /package/dist/{src/lib → lib}/shared/payloads.d.ts +0 -0
  51. /package/dist/{src/lib → lib}/shared/payloads.js +0 -0
  52. /package/dist/{src/lib → lib}/wallet/index.d.ts +0 -0
  53. /package/dist/{src/lib → lib}/wallet/index.js +0 -0
  54. /package/dist/{src/lib → lib}/wallet/provider.d.ts +0 -0
  55. /package/dist/{src/lib → lib}/wallet/provider.js +0 -0
  56. /package/dist/{src/lib → lib}/wallet/types.d.ts +0 -0
  57. /package/dist/{src/lib → lib}/wallet/types.js +0 -0
@@ -1,625 +0,0 @@
1
- /*
2
- *
3
- * Hedera Wallet Connect
4
- *
5
- * Copyright (C) 2023 Hedera Hashgraph, LLC
6
- *
7
- * Licensed under the Apache License, Version 2.0 (the "License");
8
- * you may not use this file except in compliance with the License.
9
- * You may obtain a copy of the License at
10
- *
11
- * http://www.apache.org/licenses/LICENSE-2.0
12
- *
13
- * Unless required by applicable law or agreed to in writing, software
14
- * distributed under the License is distributed on an "AS IS" BASIS,
15
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
- * See the License for the specific language governing permissions and
17
- * limitations under the License.
18
- *
19
- */
20
- import { AccountBalanceQuery, AccountCreateTransaction, AccountId, AccountInfoQuery, AccountRecordsQuery, AccountUpdateTransaction, LedgerId, PrivateKey, TokenAssociateTransaction, TokenCreateTransaction, TopicCreateTransaction, TransactionId, Client, TransactionReceiptQuery, TransactionRecordQuery, AccountInfo, TransactionRecord, TransactionReceipt, AccountBalance, FileInfoQuery, } from '@hashgraph/sdk';
21
- import { proto } from '@hashgraph/proto';
22
- import { DAppConnector, HederaJsonRpcMethod, transactionToBase64String, DAppSigner, Uint8ArrayToBase64String, base64StringToQuery, } from '../../src';
23
- import { projectId, dAppMetadata, useJsonFixture, prepareTestTransaction, prepareTestQuery, } from '../_helpers';
24
- import Long from 'long';
25
- jest.mock('../../src/lib/shared/extensionController', () => ({
26
- extensionOpen: jest.fn(),
27
- }));
28
- jest.mock('../../src/lib/shared/utils', () => (Object.assign(Object.assign({}, jest.requireActual('../../src/lib/shared/utils')), { findExtensions: jest.fn() })));
29
- describe('DAppSigner', () => {
30
- let connector;
31
- const fakeSession = useJsonFixture('fakeSession');
32
- let signer;
33
- let mockSignClient;
34
- const testAccountId = AccountId.fromString('0.0.123');
35
- const testTopic = 'test-topic';
36
- const testExtensionId = 'test-extension-id';
37
- beforeEach(() => {
38
- connector = new DAppConnector(dAppMetadata, LedgerId.TESTNET, projectId);
39
- // @ts-ignore
40
- connector.signers = connector.createSigners(fakeSession);
41
- signer = connector.signers[0];
42
- mockSignClient = {
43
- request: jest.fn(),
44
- metadata: dAppMetadata,
45
- };
46
- signer = new DAppSigner(testAccountId, mockSignClient, testTopic, LedgerId.TESTNET, testExtensionId);
47
- });
48
- afterEach(() => {
49
- global.gc && global.gc();
50
- });
51
- describe(DAppSigner.prototype.call, () => {
52
- let signerRequestSpy;
53
- beforeEach(async () => {
54
- signerRequestSpy = jest.spyOn(signer, 'request');
55
- signerRequestSpy.mockImplementation((request) => {
56
- const { method } = request;
57
- if (method === HederaJsonRpcMethod.SignAndExecuteTransaction) {
58
- const response = {
59
- transactionId: TransactionId.generate('0.0.999').toString(),
60
- nodeId: '0.0.3',
61
- transactionHash: '0x',
62
- };
63
- return Promise.resolve(response);
64
- }
65
- else if (method === HederaJsonRpcMethod.ExecuteTransaction) {
66
- const response = {
67
- transactionId: TransactionId.generate('0.0.999').toString(),
68
- nodeId: '0.0.3',
69
- transactionHash: '0x',
70
- };
71
- return Promise.resolve(response);
72
- }
73
- else if (method === HederaJsonRpcMethod.SignAndExecuteQuery) {
74
- const query = base64StringToQuery(request.params.query);
75
- let queryResponse = 'ERROR: Unsupported query type';
76
- if (query instanceof AccountBalanceQuery) {
77
- queryResponse = Uint8ArrayToBase64String(proto.CryptoGetAccountBalanceResponse.encode({
78
- balance: Long.fromNumber(0),
79
- }).finish());
80
- }
81
- else if (query instanceof AccountInfoQuery) {
82
- queryResponse = Uint8ArrayToBase64String(proto.CryptoGetInfoResponse.AccountInfo.encode({
83
- accountID: {
84
- shardNum: Long.fromNumber(0),
85
- realmNum: Long.fromNumber(0),
86
- accountNum: Long.fromNumber(3),
87
- },
88
- contractAccountID: AccountId.fromString('0.0.3').toSolidityAddress(),
89
- key: {
90
- ed25519: PrivateKey.generate().publicKey.toBytes(),
91
- },
92
- expirationTime: { seconds: Long.fromNumber(0), nanos: 1 },
93
- }).finish());
94
- }
95
- else if (query instanceof AccountRecordsQuery) {
96
- queryResponse = Uint8ArrayToBase64String(proto.TransactionGetRecordResponse.encode({
97
- transactionRecord: {
98
- alias: proto.Key.encode(PrivateKey.generate().publicKey._toProtobufKey()).finish(),
99
- receipt: {
100
- status: proto.ResponseCodeEnum.OK,
101
- accountID: {
102
- shardNum: Long.fromNumber(0),
103
- realmNum: Long.fromNumber(0),
104
- accountNum: Long.fromNumber(3),
105
- },
106
- },
107
- consensusTimestamp: { seconds: Long.fromNumber(0), nanos: 1 },
108
- transactionID: {
109
- accountID: {
110
- shardNum: Long.fromNumber(0),
111
- realmNum: Long.fromNumber(0),
112
- accountNum: Long.fromNumber(3),
113
- },
114
- transactionValidStart: { seconds: Long.fromNumber(0), nanos: 1 },
115
- nonce: 1,
116
- },
117
- },
118
- }).finish());
119
- }
120
- const response = {
121
- response: queryResponse,
122
- };
123
- return Promise.resolve(response);
124
- }
125
- });
126
- });
127
- afterEach(() => {
128
- if (signerRequestSpy) {
129
- signerRequestSpy.mockRestore();
130
- }
131
- });
132
- it.each([
133
- { name: AccountCreateTransaction.name, ExecutableType: AccountCreateTransaction },
134
- { name: AccountUpdateTransaction.name, ExecutableType: AccountUpdateTransaction },
135
- { name: TopicCreateTransaction.name, ExecutableType: TopicCreateTransaction },
136
- { name: TokenAssociateTransaction.name, ExecutableType: TokenAssociateTransaction },
137
- { name: TokenCreateTransaction.name, ExecutableType: TokenCreateTransaction },
138
- ])('can execute $name transaction', async ({ name, ExecutableType }) => {
139
- const transaction = prepareTestTransaction(new ExecutableType(), { freeze: true });
140
- const params = {
141
- signerAccountId: 'hedera:testnet:' + signer.getAccountId().toString(),
142
- transactionList: transactionToBase64String(transaction),
143
- };
144
- await signer.call(transaction);
145
- expect(signerRequestSpy).toHaveBeenCalled();
146
- expect(signerRequestSpy).toHaveBeenCalledTimes(1);
147
- expect(signerRequestSpy).toHaveBeenCalledWith({
148
- method: HederaJsonRpcMethod.SignAndExecuteTransaction,
149
- params,
150
- });
151
- });
152
- it.each([
153
- { name: AccountBalanceQuery.name, ExecutableType: AccountBalanceQuery },
154
- { name: AccountInfoQuery.name, ExecutableType: AccountInfoQuery },
155
- { name: AccountRecordsQuery.name, ExecutableType: AccountRecordsQuery },
156
- ])('can execute $name query', async ({ name, ExecutableType }) => {
157
- const query = prepareTestQuery(new ExecutableType());
158
- const params = {
159
- signerAccountId: 'hedera:testnet:' + signer.getAccountId().toString(),
160
- query: Uint8ArrayToBase64String(query.toBytes()),
161
- };
162
- await signer.call(query);
163
- expect(signerRequestSpy).toHaveBeenCalled();
164
- expect(signerRequestSpy).toHaveBeenCalledTimes(1);
165
- expect(signerRequestSpy).toHaveBeenCalledWith({
166
- method: HederaJsonRpcMethod.SignAndExecuteQuery,
167
- params,
168
- });
169
- });
170
- });
171
- describe('sign', () => {
172
- let signerRequestSpy;
173
- beforeEach(() => {
174
- signerRequestSpy = jest.spyOn(signer, 'request');
175
- });
176
- afterEach(() => {
177
- signerRequestSpy.mockRestore();
178
- });
179
- it('should sign a message', async () => {
180
- const mockPublicKey = PrivateKey.generate().publicKey;
181
- const mockSignature = new Uint8Array([1, 2, 3]);
182
- signerRequestSpy.mockImplementation(() => Promise.resolve({
183
- signatureMap: Uint8ArrayToBase64String(proto.SignatureMap.encode({
184
- sigPair: [
185
- {
186
- pubKeyPrefix: mockPublicKey.toBytes(),
187
- ed25519: mockSignature,
188
- },
189
- ],
190
- }).finish()),
191
- }));
192
- const message = new Uint8Array([4, 5, 6]);
193
- const signatures = await signer.sign([message]);
194
- expect(signatures).toHaveLength(1);
195
- expect(signatures[0].accountId.toString()).toBe(signer.getAccountId().toString());
196
- expect(Array.from(signatures[0].signature)).toEqual(Array.from(mockSignature));
197
- expect(signerRequestSpy).toHaveBeenCalledWith({
198
- method: HederaJsonRpcMethod.SignMessage,
199
- params: {
200
- signerAccountId: 'hedera:testnet:' + signer.getAccountId().toString(),
201
- message: Uint8ArrayToBase64String(message),
202
- },
203
- });
204
- });
205
- });
206
- describe('signTransaction', () => {
207
- let signerRequestSpy;
208
- beforeEach(() => {
209
- signerRequestSpy = jest.spyOn(signer, 'request');
210
- });
211
- afterEach(() => {
212
- signerRequestSpy.mockRestore();
213
- });
214
- it('should sign a transaction', async () => {
215
- const mockPublicKey = PrivateKey.generate().publicKey;
216
- const mockSignature = new Uint8Array([1, 2, 3]);
217
- signerRequestSpy.mockImplementation(() => Promise.resolve({
218
- signatureMap: Uint8ArrayToBase64String(proto.SignatureMap.encode({
219
- sigPair: [
220
- {
221
- pubKeyPrefix: mockPublicKey.toBytes(),
222
- ed25519: mockSignature,
223
- },
224
- ],
225
- }).finish()),
226
- }));
227
- const transaction = prepareTestTransaction(new AccountCreateTransaction(), {
228
- freeze: true,
229
- });
230
- const signedTx = await signer.signTransaction(transaction);
231
- expect(signedTx).toBeDefined();
232
- expect(signerRequestSpy).toHaveBeenCalledWith({
233
- method: HederaJsonRpcMethod.SignTransaction,
234
- params: expect.objectContaining({
235
- signerAccountId: 'hedera:testnet:' + signer.getAccountId().toString(),
236
- transactionBody: expect.any(String),
237
- }),
238
- });
239
- });
240
- });
241
- describe('getAccountKey()', () => {
242
- let signerRequestSpy;
243
- beforeEach(() => {
244
- signerRequestSpy = jest.spyOn(signer, 'request');
245
- });
246
- afterEach(() => {
247
- signerRequestSpy.mockRestore();
248
- });
249
- it('should throw error as method is not implemented', () => {
250
- expect(() => signer.getAccountKey()).toThrow('Method not implemented.');
251
- });
252
- });
253
- describe('network configuration', () => {
254
- let signerRequestSpy;
255
- beforeEach(() => {
256
- signerRequestSpy = jest.spyOn(signer, 'request');
257
- });
258
- afterEach(() => {
259
- signerRequestSpy.mockRestore();
260
- });
261
- it('should return network configuration from client', () => {
262
- const network = signer.getNetwork();
263
- expect(network).toBeDefined();
264
- expect(Object.keys(network).length).toBeGreaterThan(0);
265
- });
266
- it('should return mirror network configuration from client', () => {
267
- const mirrorNetwork = signer.getMirrorNetwork();
268
- expect(Array.isArray(mirrorNetwork)).toBe(true);
269
- });
270
- });
271
- describe('getMetadata()', () => {
272
- let signerRequestSpy;
273
- beforeEach(() => {
274
- signerRequestSpy = jest.spyOn(signer, 'request');
275
- });
276
- afterEach(() => {
277
- signerRequestSpy.mockRestore();
278
- });
279
- it('should return dApp metadata', () => {
280
- const metadata = signer.getMetadata();
281
- expect(metadata).toEqual(dAppMetadata);
282
- });
283
- });
284
- describe('_getHederaClient', () => {
285
- it('should create and cache client for ledger', () => {
286
- const client1 = signer._getHederaClient();
287
- const client2 = signer._getHederaClient();
288
- expect(client1).toBe(client2);
289
- expect(client1).toBeInstanceOf(Client);
290
- });
291
- });
292
- describe('_getRandomNodes', () => {
293
- it('should return random subset of nodes', () => {
294
- const nodes = signer._getRandomNodes(3);
295
- expect(nodes).toHaveLength(3);
296
- expect(nodes[0]).toBeInstanceOf(AccountId);
297
- });
298
- });
299
- describe('checkTransaction', () => {
300
- it('should throw not implemented error', async () => {
301
- await expect(signer.checkTransaction({})).rejects.toThrow('Method not implemented.');
302
- });
303
- });
304
- describe('populateTransaction', () => {
305
- it('should populate transaction with node accounts and transaction id', async () => {
306
- const mockTx = {
307
- setNodeAccountIds: jest.fn().mockReturnThis(),
308
- setTransactionId: jest.fn().mockReturnThis(),
309
- };
310
- const result = await signer.populateTransaction(mockTx);
311
- expect(mockTx.setNodeAccountIds).toHaveBeenCalled();
312
- expect(mockTx.setTransactionId).toHaveBeenCalled();
313
- expect(result).toBe(mockTx);
314
- });
315
- });
316
- describe('_parseQueryResponse', () => {
317
- it('should handle all supported query types', async () => {
318
- // Test AccountBalanceQuery
319
- const mockAccountBalance = proto.CryptoGetAccountBalanceResponse.encode({
320
- header: {
321
- nodeTransactionPrecheckCode: proto.ResponseCodeEnum.OK,
322
- },
323
- balance: Long.fromNumber(100),
324
- tokenBalances: [],
325
- }).finish();
326
- const balanceQuery = new AccountBalanceQuery();
327
- const balanceResponse = Uint8ArrayToBase64String(mockAccountBalance);
328
- const balanceResult = await signer._parseQueryResponse(balanceQuery, balanceResponse);
329
- expect(balanceResult).toBeDefined();
330
- expect(balanceResult).toBeInstanceOf(AccountBalance);
331
- // Test AccountInfoQuery
332
- const mockAccountInfo = proto.CryptoGetInfoResponse.AccountInfo.encode({
333
- accountID: {
334
- shardNum: Long.fromNumber(0),
335
- realmNum: Long.fromNumber(0),
336
- accountNum: Long.fromNumber(123),
337
- },
338
- contractAccountID: '',
339
- deleted: false,
340
- proxyAccountID: null,
341
- proxyReceived: Long.ZERO,
342
- key: {
343
- ed25519: PrivateKey.generate().publicKey.toBytes(),
344
- },
345
- balance: Long.fromNumber(100),
346
- receiverSigRequired: false,
347
- expirationTime: { seconds: Long.fromNumber(Date.now() / 1000 + 7776000) },
348
- autoRenewPeriod: { seconds: Long.fromNumber(7776000) },
349
- memo: '',
350
- maxAutomaticTokenAssociations: 0,
351
- alias: new Uint8Array([]),
352
- ledgerId: new Uint8Array([]),
353
- ethereumNonce: Long.fromNumber(0),
354
- stakingInfo: null,
355
- }).finish();
356
- const infoQuery = new AccountInfoQuery();
357
- const infoResponse = Uint8ArrayToBase64String(mockAccountInfo);
358
- const infoResult = await signer._parseQueryResponse(infoQuery, infoResponse);
359
- expect(infoResult).toBeDefined();
360
- expect(infoResult).toBeInstanceOf(AccountInfo);
361
- // Test AccountRecordsQuery
362
- const mockTransactionRecord = proto.TransactionGetRecordResponse.encode({
363
- header: {
364
- nodeTransactionPrecheckCode: proto.ResponseCodeEnum.OK,
365
- },
366
- transactionRecord: {
367
- receipt: {
368
- status: proto.ResponseCodeEnum.SUCCESS,
369
- accountID: {
370
- shardNum: Long.fromNumber(0),
371
- realmNum: Long.fromNumber(0),
372
- accountNum: Long.fromNumber(123),
373
- },
374
- },
375
- transactionHash: new Uint8Array([1, 2, 3]),
376
- consensusTimestamp: { seconds: Long.fromNumber(Date.now() / 1000) },
377
- transactionID: {
378
- transactionValidStart: { seconds: Long.fromNumber(Date.now() / 1000) },
379
- accountID: {
380
- shardNum: Long.fromNumber(0),
381
- realmNum: Long.fromNumber(0),
382
- accountNum: Long.fromNumber(123),
383
- },
384
- },
385
- memo: '',
386
- transactionFee: Long.fromNumber(100000),
387
- },
388
- }).finish();
389
- const recordsQuery = new AccountRecordsQuery();
390
- const recordsResponse = Uint8ArrayToBase64String(mockTransactionRecord);
391
- const recordsResult = await signer._parseQueryResponse(recordsQuery, recordsResponse);
392
- expect(recordsResult).toBeDefined();
393
- expect(Array.isArray(recordsResult)).toBe(true);
394
- // Test TransactionReceiptQuery
395
- const mockTransactionReceipt = proto.TransactionGetReceiptResponse.encode({
396
- header: {
397
- nodeTransactionPrecheckCode: proto.ResponseCodeEnum.OK,
398
- },
399
- receipt: {
400
- status: proto.ResponseCodeEnum.SUCCESS,
401
- accountID: {
402
- shardNum: Long.fromNumber(0),
403
- realmNum: Long.fromNumber(0),
404
- accountNum: Long.fromNumber(123),
405
- },
406
- topicRunningHash: new Uint8Array([1, 2, 3]),
407
- topicSequenceNumber: Long.fromNumber(1),
408
- exchangeRate: {
409
- currentRate: {
410
- hbarEquiv: 1,
411
- centEquiv: 12,
412
- expirationTime: { seconds: Long.fromNumber(Date.now() / 1000) },
413
- },
414
- },
415
- },
416
- }).finish();
417
- const receiptQuery = new TransactionReceiptQuery();
418
- const receiptResponse = Uint8ArrayToBase64String(mockTransactionReceipt);
419
- const receiptResult = await signer._parseQueryResponse(receiptQuery, receiptResponse);
420
- expect(receiptResult).toBeDefined();
421
- expect(receiptResult).toBeInstanceOf(TransactionReceipt);
422
- // Test TransactionRecordQuery
423
- const txRecordQuery = new TransactionRecordQuery();
424
- const txRecordResponse = Uint8ArrayToBase64String(mockTransactionRecord);
425
- const txRecordResult = await signer._parseQueryResponse(txRecordQuery, txRecordResponse);
426
- expect(txRecordResult).toBeDefined();
427
- expect(txRecordResult).toBeInstanceOf(TransactionRecord);
428
- });
429
- it('should throw error when query type is not supported', async () => {
430
- const unsupportedQuery = new FileInfoQuery();
431
- await expect(signer._parseQueryResponse(unsupportedQuery, '')).rejects.toThrow('Unsupported query type');
432
- });
433
- });
434
- describe('call', () => {
435
- it('should throw error when both transaction and query execution fail', async () => {
436
- const mockRequest = {
437
- toBytes: () => new Uint8Array([1, 2, 3]),
438
- };
439
- mockSignClient.request
440
- .mockRejectedValueOnce(new Error('Transaction failed'))
441
- .mockRejectedValueOnce(new Error('Query failed'));
442
- await expect(signer.call(mockRequest)).rejects.toThrow(/Error executing transaction or query/);
443
- });
444
- });
445
- describe('signTransaction', () => {
446
- it('should handle transaction without node account ids', async () => {
447
- // Create valid protobuf-encoded transaction
448
- const mockTxBody = proto.TransactionBody.encode({
449
- transactionID: {
450
- accountID: { accountNum: Long.fromNumber(800) },
451
- transactionValidStart: {
452
- seconds: Long.fromNumber(Date.now() / 1000),
453
- nanos: 0,
454
- },
455
- },
456
- nodeAccountID: { accountNum: Long.fromNumber(3) },
457
- transactionFee: Long.fromNumber(100000),
458
- transactionValidDuration: { seconds: Long.fromNumber(120) },
459
- cryptoCreateAccount: {
460
- key: { ed25519: PrivateKey.generate().publicKey.toBytes() },
461
- },
462
- }).finish();
463
- const mockTx = {
464
- nodeAccountIds: [],
465
- toBytes: () => new Uint8Array([1, 2, 3]),
466
- _signedTransactions: {
467
- current: {
468
- bodyBytes: mockTxBody,
469
- },
470
- },
471
- };
472
- const key = PrivateKey.generate();
473
- mockSignClient.request.mockResolvedValueOnce({
474
- signatureMap: Uint8ArrayToBase64String(proto.SignatureMap.encode({
475
- sigPair: [
476
- {
477
- pubKeyPrefix: key.publicKey.toBytes(),
478
- ed25519: key.toBytes(),
479
- },
480
- ],
481
- }).finish()),
482
- });
483
- await signer.signTransaction(mockTx);
484
- expect(mockSignClient.request).toHaveBeenCalledWith({
485
- topic: testTopic,
486
- request: {
487
- method: HederaJsonRpcMethod.SignTransaction,
488
- params: expect.any(Object),
489
- },
490
- chainId: expect.any(String),
491
- });
492
- });
493
- it('should throw error when transaction body serialization fails', async () => {
494
- const mockTx = {
495
- nodeAccountIds: [AccountId.fromString('0.0.3')],
496
- _signedTransactions: {
497
- current: {}, // This will cause bodyBytes to be undefined
498
- },
499
- };
500
- await expect(signer.signTransaction(mockTx)).rejects.toThrow('Failed to serialize transaction body');
501
- });
502
- });
503
- describe('request', () => {
504
- it('should call extensionOpen when extensionId is provided', async () => {
505
- const mockRequest = {
506
- method: 'test-method',
507
- params: { test: 'params' },
508
- };
509
- const { extensionOpen } = require('../../src/lib/shared/extensionController');
510
- await signer.request(mockRequest);
511
- expect(extensionOpen).toHaveBeenCalledWith(testExtensionId);
512
- });
513
- });
514
- describe('account queries', () => {
515
- let signerRequestSpy;
516
- beforeEach(() => {
517
- signerRequestSpy = jest.spyOn(signer, 'request');
518
- });
519
- afterEach(() => {
520
- signerRequestSpy.mockRestore();
521
- });
522
- it('should get account balance', async () => {
523
- const mockBalance = proto.CryptoGetAccountBalanceResponse.encode({
524
- header: {
525
- nodeTransactionPrecheckCode: proto.ResponseCodeEnum.OK,
526
- },
527
- balance: Long.fromNumber(100),
528
- tokenBalances: [],
529
- }).finish();
530
- signerRequestSpy.mockResolvedValueOnce({
531
- response: Uint8ArrayToBase64String(mockBalance),
532
- });
533
- const balance = await signer.getAccountBalance();
534
- expect(balance).toBeInstanceOf(AccountBalance);
535
- expect(signerRequestSpy).toHaveBeenCalledWith({
536
- method: HederaJsonRpcMethod.SignAndExecuteQuery,
537
- params: expect.objectContaining({
538
- signerAccountId: 'hedera:testnet:' + signer.getAccountId().toString(),
539
- }),
540
- });
541
- });
542
- it('should get ledger id', async () => {
543
- const ledgerId = await signer.getLedgerId();
544
- expect(ledgerId).toBeDefined();
545
- expect(ledgerId.toString()).toBe('testnet');
546
- });
547
- it('should get account info', async () => {
548
- const mockInfo = proto.CryptoGetInfoResponse.AccountInfo.encode({
549
- accountID: {
550
- shardNum: Long.fromNumber(0),
551
- realmNum: Long.fromNumber(0),
552
- accountNum: Long.fromNumber(123),
553
- },
554
- contractAccountID: null,
555
- deleted: false,
556
- proxyAccountID: null,
557
- proxyReceived: Long.ZERO,
558
- key: {
559
- ed25519: PrivateKey.generate().publicKey.toBytes(),
560
- },
561
- balance: Long.fromNumber(100),
562
- receiverSigRequired: false,
563
- expirationTime: { seconds: Long.fromNumber(Date.now() / 1000 + 7776000) },
564
- autoRenewPeriod: { seconds: Long.fromNumber(7776000) },
565
- memo: '',
566
- maxAutomaticTokenAssociations: 0,
567
- alias: new Uint8Array([]),
568
- ledgerId: new Uint8Array([]),
569
- ethereumNonce: Long.fromNumber(0),
570
- stakingInfo: null,
571
- }).finish();
572
- signerRequestSpy.mockResolvedValueOnce({
573
- response: Uint8ArrayToBase64String(mockInfo),
574
- });
575
- const info = await signer.getAccountInfo();
576
- expect(info).toBeInstanceOf(AccountInfo);
577
- expect(signerRequestSpy).toHaveBeenCalledWith({
578
- method: HederaJsonRpcMethod.SignAndExecuteQuery,
579
- params: expect.objectContaining({
580
- signerAccountId: 'hedera:testnet:' + signer.getAccountId().toString(),
581
- }),
582
- });
583
- });
584
- it('should get account records', async () => {
585
- const mockRecords = proto.TransactionGetRecordResponse.encode({
586
- header: {
587
- nodeTransactionPrecheckCode: proto.ResponseCodeEnum.OK,
588
- },
589
- transactionRecord: {
590
- receipt: {
591
- status: proto.ResponseCodeEnum.SUCCESS,
592
- accountID: {
593
- shardNum: Long.fromNumber(0),
594
- realmNum: Long.fromNumber(0),
595
- accountNum: Long.fromNumber(123),
596
- },
597
- },
598
- transactionHash: new Uint8Array([1, 2, 3]),
599
- consensusTimestamp: { seconds: Long.fromNumber(Date.now() / 1000) },
600
- transactionID: {
601
- transactionValidStart: { seconds: Long.fromNumber(Date.now() / 1000) },
602
- accountID: {
603
- shardNum: Long.fromNumber(0),
604
- realmNum: Long.fromNumber(0),
605
- accountNum: Long.fromNumber(123),
606
- },
607
- },
608
- memo: '',
609
- transactionFee: Long.fromNumber(100000),
610
- },
611
- }).finish();
612
- signerRequestSpy.mockResolvedValueOnce({
613
- response: Uint8ArrayToBase64String(mockRecords),
614
- });
615
- const records = await signer.getAccountRecords();
616
- expect(Array.isArray(records)).toBe(true);
617
- expect(signerRequestSpy).toHaveBeenCalledWith({
618
- method: HederaJsonRpcMethod.SignAndExecuteQuery,
619
- params: expect.objectContaining({
620
- signerAccountId: 'hedera:testnet:' + signer.getAccountId().toString(),
621
- }),
622
- });
623
- });
624
- });
625
- });
@@ -1 +0,0 @@
1
- export {};