@aastar/sdk 0.16.22 → 0.17.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 (60) hide show
  1. package/README.md +1 -0
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.js +2 -0
  4. package/dist/utils/userOp.d.ts +11 -0
  5. package/dist/utils/userOp.js +43 -2
  6. package/package.json +11 -10
  7. package/dist/clients/ExperimentClient.test.d.ts +0 -1
  8. package/dist/clients/ExperimentClient.test.js +0 -53
  9. package/dist/clients/admin.test.d.ts +0 -1
  10. package/dist/clients/admin.test.js +0 -79
  11. package/dist/clients/clients.test.d.ts +0 -1
  12. package/dist/clients/clients.test.js +0 -91
  13. package/dist/clients/community.test.d.ts +0 -1
  14. package/dist/clients/community.test.js +0 -99
  15. package/dist/clients/endUser.test.d.ts +0 -1
  16. package/dist/clients/endUser.test.js +0 -188
  17. package/dist/clients/operator.test.d.ts +0 -1
  18. package/dist/clients/operator.test.js +0 -139
  19. package/dist/core/src/abis/BLSAggregator.json +0 -686
  20. package/dist/core/src/abis/BLSValidator.json +0 -42
  21. package/dist/core/src/abis/DVTValidator.json +0 -368
  22. package/dist/core/src/abis/EntryPoint.json +0 -1382
  23. package/dist/core/src/abis/GToken.json +0 -513
  24. package/dist/core/src/abis/GTokenStaking.json +0 -949
  25. package/dist/core/src/abis/MySBT.json +0 -1518
  26. package/dist/core/src/abis/Paymaster.json +0 -1143
  27. package/dist/core/src/abis/PaymasterFactory.json +0 -640
  28. package/dist/core/src/abis/Registry.json +0 -1942
  29. package/dist/core/src/abis/ReputationSystem.json +0 -699
  30. package/dist/core/src/abis/SimpleAccount.json +0 -560
  31. package/dist/core/src/abis/SimpleAccountFactory.json +0 -111
  32. package/dist/core/src/abis/SuperPaymaster.json +0 -1781
  33. package/dist/core/src/abis/xPNTsFactory.json +0 -718
  34. package/dist/core/src/abis/xPNTsToken.json +0 -1280
  35. package/dist/errors/AAStarError.d.ts +0 -26
  36. package/dist/errors/AAStarError.js +0 -32
  37. package/dist/errors/AAStarError.test.d.ts +0 -1
  38. package/dist/errors/AAStarError.test.js +0 -74
  39. package/dist/errors/decoder.test.d.ts +0 -1
  40. package/dist/errors/decoder.test.js +0 -90
  41. package/dist/node/index.d.ts +0 -7
  42. package/dist/node/index.js +0 -7
  43. package/dist/types/result.d.ts +0 -15
  44. package/dist/types/result.js +0 -23
  45. package/dist/utils/errorHandler.test.d.ts +0 -1
  46. package/dist/utils/errorHandler.test.js +0 -89
  47. package/dist/utils/eventDecoder.d.ts +0 -7
  48. package/dist/utils/eventDecoder.js +0 -54
  49. package/dist/utils/eventDecoder.test.d.ts +0 -1
  50. package/dist/utils/eventDecoder.test.js +0 -48
  51. package/dist/utils/funding.test.d.ts +0 -1
  52. package/dist/utils/funding.test.js +0 -105
  53. package/dist/utils/keys.test.d.ts +0 -1
  54. package/dist/utils/keys.test.js +0 -81
  55. package/dist/utils/roleData.test.d.ts +0 -1
  56. package/dist/utils/roleData.test.js +0 -74
  57. package/dist/utils/testScenarios.test.d.ts +0 -1
  58. package/dist/utils/testScenarios.test.js +0 -68
  59. package/dist/utils/userOp.test.d.ts +0 -1
  60. package/dist/utils/userOp.test.js +0 -152
@@ -1,26 +0,0 @@
1
- export declare enum AAStarErrorCode {
2
- VALIDATION_ERROR = "VALIDATION_ERROR",
3
- CONTRACT_ERROR = "CONTRACT_ERROR",
4
- NETWORK_ERROR = "NETWORK_ERROR",
5
- CONFIGURATION_ERROR = "CONFIGURATION_ERROR",
6
- INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS",
7
- PERMISSION_DENIED = "PERMISSION_DENIED",
8
- OPERATION_FAILED = "OPERATION_FAILED",
9
- UNKNOWN_ERROR = "UNKNOWN_ERROR"
10
- }
11
- export declare class AAStarError extends Error {
12
- readonly code: AAStarErrorCode;
13
- readonly details?: any;
14
- constructor(message: string, code?: AAStarErrorCode, details?: any);
15
- }
16
- /**
17
- * Error factory functions for consistent error creation
18
- */
19
- export declare const createError: {
20
- validation: (field: string, reason: string) => AAStarError;
21
- contract: (contract: string, reason: string) => AAStarError;
22
- network: (operation: string, reason: string) => AAStarError;
23
- insufficientFunds: (required: string, available: string) => AAStarError;
24
- permissionDenied: (operation: string, reason: string) => AAStarError;
25
- operationFailed: (operation: string, reason: string) => AAStarError;
26
- };
@@ -1,32 +0,0 @@
1
- export var AAStarErrorCode;
2
- (function (AAStarErrorCode) {
3
- AAStarErrorCode["VALIDATION_ERROR"] = "VALIDATION_ERROR";
4
- AAStarErrorCode["CONTRACT_ERROR"] = "CONTRACT_ERROR";
5
- AAStarErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR";
6
- AAStarErrorCode["CONFIGURATION_ERROR"] = "CONFIGURATION_ERROR";
7
- AAStarErrorCode["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS";
8
- AAStarErrorCode["PERMISSION_DENIED"] = "PERMISSION_DENIED";
9
- AAStarErrorCode["OPERATION_FAILED"] = "OPERATION_FAILED";
10
- AAStarErrorCode["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
11
- })(AAStarErrorCode || (AAStarErrorCode = {}));
12
- export class AAStarError extends Error {
13
- code;
14
- details;
15
- constructor(message, code = AAStarErrorCode.UNKNOWN_ERROR, details) {
16
- super(message);
17
- this.name = 'AAStarError';
18
- this.code = code;
19
- this.details = details;
20
- }
21
- }
22
- /**
23
- * Error factory functions for consistent error creation
24
- */
25
- export const createError = {
26
- validation: (field, reason) => new AAStarError(`Validation failed for ${field}: ${reason}`, AAStarErrorCode.VALIDATION_ERROR, { field, reason }),
27
- contract: (contract, reason) => new AAStarError(`Contract ${contract} error: ${reason}`, AAStarErrorCode.CONTRACT_ERROR, { contract, reason }),
28
- network: (operation, reason) => new AAStarError(`Network error during ${operation}: ${reason}`, AAStarErrorCode.NETWORK_ERROR, { operation, reason }),
29
- insufficientFunds: (required, available) => new AAStarError(`Insufficient funds: required ${required}, available ${available}`, AAStarErrorCode.INSUFFICIENT_FUNDS, { required, available }),
30
- permissionDenied: (operation, reason) => new AAStarError(`Permission denied for ${operation}: ${reason}`, AAStarErrorCode.PERMISSION_DENIED, { operation, reason }),
31
- operationFailed: (operation, reason) => new AAStarError(`Operation ${operation} failed: ${reason}`, AAStarErrorCode.OPERATION_FAILED, { operation, reason }),
32
- };
@@ -1 +0,0 @@
1
- export {};
@@ -1,74 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { AAStarError, AAStarErrorCode } from './AAStarError.js';
3
- describe('AAStarError', () => {
4
- describe('Error Creation', () => {
5
- it('should create VALIDATION_ERROR', () => {
6
- const error = new AAStarError('Invalid address format', AAStarErrorCode.VALIDATION_ERROR);
7
- expect(error).toBeInstanceOf(Error);
8
- expect(error).toBeInstanceOf(AAStarError);
9
- expect(error.code).toBe(AAStarErrorCode.VALIDATION_ERROR);
10
- expect(error.message).toContain('Invalid address format');
11
- expect(error.name).toBe('AAStarError');
12
- });
13
- it('should create CONTRACT_ERROR', () => {
14
- const error = new AAStarError('Execution reverted', AAStarErrorCode.CONTRACT_ERROR);
15
- expect(error.code).toBe(AAStarErrorCode.CONTRACT_ERROR);
16
- expect(error.message).toContain('Execution reverted');
17
- });
18
- it('should create NETWORK_ERROR', () => {
19
- const error = new AAStarError('Network timeout', AAStarErrorCode.NETWORK_ERROR);
20
- expect(error.code).toBe(AAStarErrorCode.NETWORK_ERROR);
21
- expect(error.message).toContain('Network timeout');
22
- });
23
- it('should create CONFIGURATION_ERROR', () => {
24
- const error = new AAStarError('Missing RPC URL', AAStarErrorCode.CONFIGURATION_ERROR);
25
- expect(error.code).toBe(AAStarErrorCode.CONFIGURATION_ERROR);
26
- expect(error.message).toContain('Missing RPC URL');
27
- });
28
- it('should create UNKNOWN_ERROR', () => {
29
- const error = new AAStarError('Unexpected error');
30
- expect(error.code).toBe(AAStarErrorCode.UNKNOWN_ERROR);
31
- });
32
- });
33
- describe('Error Properties', () => {
34
- it('should have correct error name', () => {
35
- const error = new AAStarError('Test error', AAStarErrorCode.VALIDATION_ERROR);
36
- expect(error.name).toBe('AAStarError');
37
- });
38
- it('should maintain stack trace', () => {
39
- const error = new AAStarError('Test error', AAStarErrorCode.CONTRACT_ERROR);
40
- expect(error.stack).toBeDefined();
41
- expect(error.stack).toContain('AAStarError');
42
- });
43
- it('should preserve original message', () => {
44
- const originalMessage = 'Detailed error description';
45
- const error = new AAStarError(originalMessage, AAStarErrorCode.NETWORK_ERROR);
46
- expect(error.message).toBe(originalMessage);
47
- });
48
- });
49
- describe('Error Codes Enumeration', () => {
50
- it('should have all expected error codes', () => {
51
- expect(AAStarErrorCode.VALIDATION_ERROR).toBe('VALIDATION_ERROR');
52
- expect(AAStarErrorCode.CONTRACT_ERROR).toBe('CONTRACT_ERROR');
53
- expect(AAStarErrorCode.NETWORK_ERROR).toBe('NETWORK_ERROR');
54
- expect(AAStarErrorCode.CONFIGURATION_ERROR).toBe('CONFIGURATION_ERROR');
55
- expect(AAStarErrorCode.UNKNOWN_ERROR).toBe('UNKNOWN_ERROR');
56
- });
57
- });
58
- describe('instanceof checks', () => {
59
- it('should be instance of Error', () => {
60
- const error = new AAStarError('Test', AAStarErrorCode.VALIDATION_ERROR);
61
- expect(error instanceof Error).toBe(true);
62
- });
63
- it('should be instance of AAStarError', () => {
64
- const error = new AAStarError('Test', AAStarErrorCode.CONTRACT_ERROR);
65
- expect(error instanceof AAStarError).toBe(true);
66
- });
67
- it('should differentiate from standard Error', () => {
68
- const aastarError = new AAStarError('Test', AAStarErrorCode.VALIDATION_ERROR);
69
- const standardError = new Error('Test');
70
- expect(aastarError instanceof AAStarError).toBe(true);
71
- expect(standardError instanceof AAStarError).toBe(false);
72
- });
73
- });
74
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,90 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { decodeContractError } from './decoder.js';
3
- import * as viem from 'viem';
4
- vi.mock('viem', async () => {
5
- const actual = await vi.importActual('viem');
6
- return {
7
- ...actual,
8
- decodeErrorResult: vi.fn()
9
- };
10
- });
11
- describe('ErrorDecoder', () => {
12
- beforeEach(() => {
13
- vi.resetAllMocks();
14
- });
15
- it('should extract data from viem error walk', () => {
16
- const mockError = {
17
- walk: (fn) => {
18
- const e = { data: '0x123' };
19
- return fn(e) ? e : null;
20
- }
21
- };
22
- viem.decodeErrorResult.mockReturnValue({
23
- errorName: 'Unauthorized',
24
- args: []
25
- });
26
- const result = decodeContractError(mockError);
27
- expect(result).toContain('Unauthorized');
28
- });
29
- it('should extract data from cause', () => {
30
- const mockError = {
31
- cause: { data: '0x123' }
32
- };
33
- viem.decodeErrorResult.mockReturnValue({
34
- errorName: 'InsufficientBalance',
35
- args: [100n, 500n]
36
- });
37
- const result = decodeContractError(mockError);
38
- expect(result).toContain('InsufficientBalance');
39
- expect(result).toContain('Available 100, Required 500');
40
- });
41
- it('should handle specialized formatting for RoleNotConfigured', () => {
42
- viem.decodeErrorResult.mockReturnValue({
43
- errorName: 'RoleNotConfigured',
44
- args: ['0x1', false]
45
- });
46
- const result = decodeContractError({ data: '0x123' });
47
- expect(result).toContain('Role 0x1 is INACTIVE');
48
- });
49
- it('should fallback to unknown error message if decoding fails', () => {
50
- viem.decodeErrorResult.mockImplementation(() => { throw new Error('mismatch'); });
51
- const result = decodeContractError({ data: '0x1234567890' });
52
- expect(result).toContain('Unknown Error (data: 0x12345678...)');
53
- });
54
- it('should handle raw revert messages', () => {
55
- const result = decodeContractError({ message: 'execution reverted: CustomError' });
56
- expect(result).toBe('execution reverted: CustomError');
57
- });
58
- it('should return null for non-error input', () => {
59
- expect(decodeContractError(null)).toBeNull();
60
- });
61
- it('should extract data from nested object structure', () => {
62
- // Case A: { data: { data: "0x..." } }
63
- const errorA = { data: { data: '0xA1' } };
64
- viem.decodeErrorResult.mockReturnValue({ errorName: 'TestA', args: [] });
65
- expect(decodeContractError(errorA)).toContain('TestA');
66
- // Case B: { data: { object: "0x..." } }
67
- const errorB = { data: { object: '0xB1' } };
68
- viem.decodeErrorResult.mockReturnValue({ errorName: 'TestB', args: [] });
69
- expect(decodeContractError(errorB)).toContain('TestB');
70
- });
71
- it('should format all known error types', () => {
72
- const testCases = [
73
- { name: 'RoleAlreadyGranted', args: ['0xRole', '0xUser'], expected: 'User 0xUser already has role 0xRole' },
74
- { name: 'InsufficientStake', args: [100n, 200n], expected: 'Provided 100, Required 200' },
75
- { name: 'InvalidParameter', args: ['BadInput'], expected: 'InvalidParameter: BadInput' },
76
- { name: 'RoleNotGranted', args: ['0xRole', '0xUser'], expected: 'User 0xUser does not have role 0xRole' },
77
- { name: 'UnknownCustom', args: [123n], expected: 'UnknownCustom: ["123"]' }
78
- ];
79
- for (const { name, args, expected } of testCases) {
80
- viem.decodeErrorResult.mockReturnValue({ errorName: name, args });
81
- const result = decodeContractError({ data: '0x1' });
82
- expect(result).toContain(expected);
83
- }
84
- });
85
- it('should handle non-string unknown data', () => {
86
- viem.decodeErrorResult.mockImplementation(() => { throw new Error('fail'); });
87
- const result = decodeContractError({ data: { complex: true } });
88
- expect(result).toContain('non-string data');
89
- });
90
- });
@@ -1,7 +0,0 @@
1
- /**
2
- * Node.js specific utilities
3
- * ⚠️ NOT COMPATIBLE WITH BROWSER ENVIRONMENTS
4
- */
5
- export { KeyManager, type KeyPair } from '../utils/keys.js';
6
- export { FundingManager, type FundingParams } from '../utils/funding.js';
7
- export * from '../utils/testScenarios.js';
@@ -1,7 +0,0 @@
1
- /**
2
- * Node.js specific utilities
3
- * ⚠️ NOT COMPATIBLE WITH BROWSER ENVIRONMENTS
4
- */
5
- export { KeyManager } from '../utils/keys.js';
6
- export { FundingManager } from '../utils/funding.js';
7
- export * from '../utils/testScenarios.js';
@@ -1,15 +0,0 @@
1
- import { AAStarError } from '../errors/AAStarError.js';
2
- export type SDKResult<T> = {
3
- success: true;
4
- data: T;
5
- } | {
6
- success: false;
7
- error: AAStarError;
8
- };
9
- export declare function success<T>(data: T): SDKResult<T>;
10
- export declare function failure<T>(error: AAStarError): SDKResult<T>;
11
- /**
12
- * Utility to wrap a Promise in an SDKResult.
13
- * Handles AAStarError explicitly, and wraps unknown errors.
14
- */
15
- export declare function safeSDKCall<T>(promise: Promise<T>): Promise<SDKResult<T>>;
@@ -1,23 +0,0 @@
1
- import { AAStarError } from '../errors/AAStarError.js';
2
- export function success(data) {
3
- return { success: true, data };
4
- }
5
- export function failure(error) {
6
- return { success: false, error };
7
- }
8
- /**
9
- * Utility to wrap a Promise in an SDKResult.
10
- * Handles AAStarError explicitly, and wraps unknown errors.
11
- */
12
- export async function safeSDKCall(promise) {
13
- try {
14
- const data = await promise;
15
- return success(data);
16
- }
17
- catch (e) {
18
- if (e instanceof AAStarError) {
19
- return failure(e);
20
- }
21
- return failure(new AAStarError(e.message || 'Unknown error occurred', undefined, e));
22
- }
23
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,89 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { handleContractError } from './errorHandler.js';
3
- describe('ErrorHandler', () => {
4
- const MOCK_CTX = {
5
- operation: 'test operation',
6
- roleId: '0xRole',
7
- account: '0xUser'
8
- };
9
- it('should enhance known contract errors', () => {
10
- const error = new Error('Execution reverted: Error: RoleNotGranted(0xabc, 0xdef)');
11
- const enhanced = handleContractError(error, MOCK_CTX);
12
- expect(enhanced.message).toContain('does not have role');
13
- expect(enhanced.message).toContain('Please register for this role first');
14
- });
15
- it('should use context if args missing', () => {
16
- const error = new Error('Execution reverted: Error: RoleNotGranted()');
17
- const enhanced = handleContractError(error, MOCK_CTX);
18
- expect(enhanced.message).toContain('0xUser does not have role 0xRole');
19
- });
20
- it('should extract error from message if data.errorName is missing', () => {
21
- // Simulate an error where data.errorName is missing but message contains relevant info
22
- const error = {
23
- message: 'Error: Registry: Role "0xRole" is not configured in the Registry'
24
- };
25
- const enhanced = handleContractError(error, MOCK_CTX);
26
- expect(enhanced.message).toContain('is not configured in the Registry');
27
- });
28
- it('should handle all known contract errors', () => {
29
- const errors = [
30
- { name: 'RoleNotGranted', args: ['0xRole', '0xUser'], match: 'does not have role' },
31
- { name: 'InsufficientBalance', args: [], match: 'Insufficient balance' },
32
- { name: 'InvalidParameter', args: ['BadParam'], match: 'Invalid parameter' },
33
- { name: 'Unauthorized', args: [], match: 'Unauthorized operation' },
34
- { name: 'OwnableUnauthorizedAccount', args: ['0xUser'], match: 'not authorized' },
35
- { name: 'RoleNotConfigured', args: ['0xRole'], match: 'not configured' }
36
- ];
37
- for (const { name, args, match } of errors) {
38
- const error = {
39
- data: { errorName: name, args },
40
- message: `Error: ${name}(...`
41
- };
42
- const enhanced = handleContractError(error, MOCK_CTX);
43
- expect(enhanced.message).toContain(match);
44
- }
45
- });
46
- it('should fallback to stringify matching', () => {
47
- // The implementation checks if JSON.stringify(error) includes known keys
48
- const weirdError = {
49
- inner: 'RoleNotConfigured'
50
- };
51
- const enhanced = handleContractError(weirdError, MOCK_CTX);
52
- expect(enhanced.message).toContain('not configured');
53
- });
54
- it('should fallback for unknown error', () => {
55
- const error = new Error('Random connection failed');
56
- const enhanced = handleContractError(error, MOCK_CTX);
57
- expect(enhanced.message).toContain('Random connection failed');
58
- });
59
- it('should handle empty error object', () => {
60
- const enhanced = handleContractError({}, MOCK_CTX);
61
- expect(enhanced.message).toBe('Failed to test operation: Unknown error');
62
- });
63
- it('should prioritize args over context for RoleAlreadyGranted', () => {
64
- const enhanced = handleContractError({
65
- data: { errorName: 'RoleAlreadyGranted', args: ['0xArgRole', '0xArgUser'] }
66
- }, MOCK_CTX);
67
- expect(enhanced.message).toContain('Account 0xArgUser already has this role (0xArgRole)');
68
- });
69
- it('should use context if args missing for RoleAlreadyGranted', () => {
70
- const enhanced = handleContractError({
71
- data: { errorName: 'RoleAlreadyGranted', args: [] }
72
- }, MOCK_CTX);
73
- expect(enhanced.message).toContain(`Account ${MOCK_CTX.account} already has this role (${MOCK_CTX.roleId})`);
74
- });
75
- it('should prioritize args for InsufficientStake', () => {
76
- const enhanced = handleContractError({
77
- data: { errorName: 'InsufficientStake', args: [100n, 200n] }
78
- }, MOCK_CTX);
79
- expect(enhanced.message).toContain('Required: 100');
80
- expect(enhanced.message).toContain('Actual: 200');
81
- });
82
- it('should handle missing args for InsufficientStake', () => {
83
- const enhanced = handleContractError({
84
- data: { errorName: 'InsufficientStake', args: [] } // Missing args
85
- }, MOCK_CTX);
86
- expect(enhanced.message).toContain('Insufficient stake for this operation.');
87
- expect(enhanced.message).not.toContain('Required:');
88
- });
89
- });
@@ -1,7 +0,0 @@
1
- export interface DecodedEvent {
2
- contractName: string;
3
- eventName: string;
4
- args: any;
5
- }
6
- export declare function decodeContractEvents(logs: any[]): DecodedEvent[];
7
- export declare function logDecodedEvents(events: DecodedEvent[]): void;
@@ -1,54 +0,0 @@
1
- import { decodeEventLog } from 'viem';
2
- import { RegistryABI, SuperPaymasterABI, GTokenStakingABI, MySBTABI, xPNTsTokenABI, PaymasterFactoryABI } from '../index.js';
3
- const ABIS_TO_TRY = [
4
- { name: 'Registry', abi: RegistryABI },
5
- { name: 'SuperPaymaster', abi: SuperPaymasterABI },
6
- { name: 'GTokenStaking', abi: GTokenStakingABI },
7
- { name: 'MySBT', abi: MySBTABI },
8
- { name: 'xPNTsToken', abi: xPNTsTokenABI },
9
- { name: 'PaymasterFactory', abi: PaymasterFactoryABI }
10
- ];
11
- export function decodeContractEvents(logs) {
12
- const decodedEvents = [];
13
- for (const log of logs) {
14
- if (typeof log.data !== 'string' || !log.data.startsWith('0x')) {
15
- console.warn(' ⚠️ Skipping log with invalid data:', log);
16
- continue;
17
- }
18
- for (const { name, abi } of ABIS_TO_TRY) {
19
- try {
20
- const decoded = decodeEventLog({
21
- abi: abi,
22
- data: log.data,
23
- topics: log.topics
24
- });
25
- if (decoded && decoded.eventName) {
26
- decodedEvents.push({
27
- contractName: name,
28
- eventName: decoded.eventName,
29
- args: decoded.args
30
- });
31
- break; // Found the right ABI for this log
32
- }
33
- }
34
- catch (e) {
35
- // Ignore mismatch errors, but log weird ones
36
- if (e.message && Object.values(e.message).some((m) => m?.includes?.('slice'))) {
37
- console.warn(` ⚠️ decodeEventLog failed (slice error) for ${name}:`, e.message);
38
- }
39
- }
40
- }
41
- }
42
- return decodedEvents;
43
- }
44
- export function logDecodedEvents(events) {
45
- for (const event of events) {
46
- console.log(`📡 [${event.contractName}] Event: ${event.eventName}`);
47
- if (event.args) {
48
- Object.entries(event.args).forEach(([key, value]) => {
49
- const displayValue = typeof value === 'bigint' ? value.toString() : value;
50
- console.log(` └─ ${key}: ${displayValue}`);
51
- });
52
- }
53
- }
54
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,48 +0,0 @@
1
- import { describe, it, expect, vi } from 'vitest';
2
- import { decodeContractEvents, logDecodedEvents } from './eventDecoder.js';
3
- import { keccak256, encodeAbiParameters, stringToBytes } from 'viem';
4
- describe('eventDecoder', () => {
5
- it('should decode known events', () => {
6
- // Manual topic construction for RoleGranted(bytes32,address,address)
7
- const ROLE_GRANTED_SIG = keccak256(stringToBytes('RoleGranted(bytes32,address,address)'));
8
- const roleId = keccak256(stringToBytes('COMMUNITY'));
9
- const account = '0x0000000000000000000000000000000000000001';
10
- const sender = '0x0000000000000000000000000000000000000002';
11
- const topics = [
12
- ROLE_GRANTED_SIG,
13
- roleId,
14
- encodeAbiParameters([{ type: 'address' }], [account]),
15
- encodeAbiParameters([{ type: 'address' }], [sender])
16
- ];
17
- const logs = [{
18
- data: '0x',
19
- topics: topics
20
- }];
21
- const decoded = decodeContractEvents(logs);
22
- expect(decoded).toHaveLength(1);
23
- expect(decoded[0].contractName).toBe('Registry');
24
- expect(decoded[0].eventName).toBe('RoleGranted');
25
- });
26
- it('should skip invalid logs', () => {
27
- const logs = [{ data: 'invalid', topics: [] }];
28
- const decoded = decodeContractEvents(logs);
29
- expect(decoded).toHaveLength(0);
30
- });
31
- it('should handle decoding errors gracefully', () => {
32
- const logs = [{ data: '0x123', topics: ['0x0000000000000000000000000000000000000000000000000000000000000000'] }];
33
- const decoded = decodeContractEvents(logs);
34
- expect(decoded).toHaveLength(0);
35
- });
36
- it('should log decoded events', () => {
37
- const consoleSpy = vi.spyOn(console, 'log');
38
- const events = [{
39
- contractName: 'Test',
40
- eventName: 'Event',
41
- args: { amount: 100n, user: '0x0000000000000000000000000000000000000001' }
42
- }];
43
- logDecodedEvents(events);
44
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('[Test] Event: Event'));
45
- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('amount: 100'));
46
- consoleSpy.mockRestore();
47
- });
48
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,105 +0,0 @@
1
- import { describe, it, expect, vi } from 'vitest';
2
- import { FundingManager } from './funding.js';
3
- import { parseEther } from 'viem';
4
- vi.mock('viem', async () => {
5
- const actual = await vi.importActual('viem');
6
- return {
7
- ...actual,
8
- createPublicClient: vi.fn(() => ({
9
- getBalance: vi.fn().mockResolvedValue(parseEther('1')),
10
- readContract: vi.fn().mockResolvedValue(parseEther('100')),
11
- simulateContract: vi.fn().mockResolvedValue({ request: {} }),
12
- waitForTransactionReceipt: vi.fn().mockResolvedValue({ status: 'success' })
13
- })),
14
- createWalletClient: vi.fn(() => ({
15
- sendTransaction: vi.fn().mockResolvedValue('0xhash'),
16
- writeContract: vi.fn().mockResolvedValue('0xhash'),
17
- account: { address: '0xsupplier' }
18
- })),
19
- http: vi.fn()
20
- };
21
- });
22
- describe('FundingManager', () => {
23
- const params = {
24
- rpcUrl: 'http://localhost:8545',
25
- chain: { id: 1 },
26
- supplierKey: '0x1234567890123456789012345678901234567890123456789012345678901234',
27
- targetAddress: '0x1111111111111111111111111111111111111111'
28
- };
29
- it('should fund with ETH', async () => {
30
- const result = await FundingManager.fundWithETH({ ...params, amount: '0.1' });
31
- expect(result.success).toBe(true);
32
- expect(result.txHash).toBe('0xhash');
33
- });
34
- it('should fund with Token', async () => {
35
- const result = await FundingManager.fundWithToken({
36
- ...params,
37
- tokenAddress: '0x2222222222222222222222222222222222222222',
38
- amount: '100'
39
- });
40
- expect(result.success).toBe(true);
41
- });
42
- it('should ensure funding when below threshold', async () => {
43
- const results = await FundingManager.ensureFunding({
44
- ...params,
45
- minETH: '2.0',
46
- targetETH: '1.0'
47
- });
48
- expect(results[0].txHash).toBe('0xhash');
49
- });
50
- it('should batch fund ETH', async () => {
51
- const results = await FundingManager.batchFundETH(params, [
52
- { address: '0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', amount: '0.1' },
53
- { address: '0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB', amount: '0.2' }
54
- ]);
55
- expect(results).toHaveLength(2);
56
- expect(results[0].success).toBe(true);
57
- });
58
- it('should get ETH balance', async () => {
59
- const balance = await FundingManager.getETHBalance(params);
60
- expect(balance).toBe(parseEther('1'));
61
- });
62
- it('should get Token balance', async () => {
63
- const balance = await FundingManager.getTokenBalance(params, '0x2222222222222222222222222222222222222222');
64
- expect(balance).toBe(parseEther('100'));
65
- });
66
- it('should batch fund Token', async () => {
67
- const results = await FundingManager.batchFundToken(params, '0x2222222222222222222222222222222222222222', [
68
- { address: '0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', amount: '100' },
69
- { address: '0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB', amount: '200' }
70
- ]);
71
- expect(results).toHaveLength(2);
72
- });
73
- it('should handle ensure funding with token', async () => {
74
- const results = await FundingManager.ensureFunding({
75
- ...params,
76
- minETH: '0.5',
77
- targetETH: '1.0',
78
- token: {
79
- address: '0x2222222222222222222222222222222222222222',
80
- minBalance: '50',
81
- targetAmount: '100'
82
- }
83
- });
84
- expect(results.length).toBeGreaterThan(0);
85
- });
86
- it('should handle ETH funding errors', async () => {
87
- vi.spyOn(FundingManager, 'createClients').mockReturnValueOnce({
88
- publicClient: {},
89
- walletClient: { sendTransaction: vi.fn().mockRejectedValue(new Error('Network error')) },
90
- account: {}
91
- });
92
- const result = await FundingManager.fundWithETH({ ...params, amount: '0.1' });
93
- expect(result.success).toBe(false);
94
- expect(result.error).toContain('Network error');
95
- });
96
- it('should handle Token funding errors', async () => {
97
- vi.spyOn(FundingManager, 'createClients').mockReturnValueOnce({
98
- publicClient: { simulateContract: vi.fn().mockRejectedValue(new Error('Insufficient balance')) },
99
- walletClient: {},
100
- account: {}
101
- });
102
- const result = await FundingManager.fundWithToken({ ...params, tokenAddress: '0x2222222222222222222222222222222222222222', amount: '100' });
103
- expect(result.success).toBe(false);
104
- });
105
- });
@@ -1 +0,0 @@
1
- export {};