Skip to content
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

test: util unit tests #4

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ package-lock.json
/.rpcrelay.env
/logger.json
/rpcrelay
/nyc-report
/nyc-tmp
9 changes: 9 additions & 0 deletions nyc.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const nycConfig = {
all: false,
'check-coverage': false,
reporter: ['lcov', 'text'],
'report-dir': 'nyc-report',
'temp-dir': 'nyc-tmp',
};

module.exports = nycConfig;
9 changes: 7 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"update-from-base-template": "npx github:hedera-dev/hedera-tutorial-demo-base-template update",
"scaffold-task-from-base-template": "npx github:hedera-dev/hedera-tutorial-demo-base-template scaffold-task",
"format": "prettier . --write --cache",
"test": "echo \"Error: no test specified\" && exit 1",
"test": "tape --ignore-pattern 'node_modules/**' '**/*.test.js'",
"cover": "nyc tape --ignore-pattern 'node_modules/**' '**/*.test.js' | tap-nyc",
"prepare": "husky"
},
"bin": {
Expand All @@ -34,6 +35,10 @@
},
"devDependencies": {
"husky": "9.1.4",
"prettier": "3.3.3"
"nyc": "17.0.0",
"prettier": "3.3.3",
"tap": "21.0.1",
"tap-nyc": "1.0.3",
"tape": "5.8.1"
}
}
59 changes: 59 additions & 0 deletions util/util-abi.unit.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const tape = require('tape');
const { getAbiSummary } = require('./util.js');

tape('[[group]] unit / util / getAbiSummary', (testGroup) => {
testGroup.test('should return abi summary for a valid ABI', (t) => {
const abi = [
{ type: 'function', name: 'transfer' },
{ type: 'constructor', name: 'constructor' },
{ type: 'event', name: 'Transfer' },
];

const expectedSummary =
'function (1): transfer\nconstructor (1): constructor\nevent (1): Transfer';

const result = getAbiSummary(abi);

t.equal(
result,
expectedSummary,
'ABI summary should match expected output',
);
t.end();
});

testGroup.test('should return abi summary with unnamed items', (t) => {
const abi = [
{ type: 'function' },
{ type: 'constructor' },
{ type: 'event', name: 'Transfer' },
];

const expectedSummary =
'function (1): (unnamed)\nconstructor (1): (unnamed)\nevent (1): Transfer';

const result = getAbiSummary(abi);

t.equal(
result,
expectedSummary,
'ABI summary should include unnamed items',
);
t.end();
});

testGroup.test('should handle empty abi array', (t) => {
const abi = [];

const expectedSummary = '';

const result = getAbiSummary(abi);

t.equal(
result,
expectedSummary,
'ABI summary for empty array should be an empty string',
);
t.end();
});
});
261 changes: 261 additions & 0 deletions util/util-data-conversion.unit.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
const tape = require('tape');
const {
convertTransactionIdForMirrorNodeApi,
queryAccountByEvmAddress,
queryAccountByPrivateKey,
isHexPrivateKey,
calculateTransactionFeeFromViem,
} = require('./util.js');

tape(
'[[group]] unit / util / convertTransactionIdForMirrorNodeApi',
(testGroup) => {
// Test: should convert transaction id for mirror node api
testGroup.test('should convert transaction id for mirror node api', (t) => {
const transactionId = '[email protected]';
const expected = '0.0.123-1624435347-123456789';

const result = convertTransactionIdForMirrorNodeApi(transactionId);

t.equal(result, expected, 'Transaction ID should be converted correctly');
t.end();
});

// Test: should error when converting transaction id for mirror node api for invalid input
testGroup.test(
'should error when converting transaction id for mirror node api for invalid input',
(t) => {
try {
const invalidTransactionId = 'invalid-transaction-id';
convertTransactionIdForMirrorNodeApi(invalidTransactionId);
t.fail('Expected error not thrown for invalid transaction ID');
} catch (error) {
t.pass('Error thrown as expected for invalid transaction ID');
}
t.end();
},
);
},
);

tape('[[group]] unit / util / queryAccountByEvmAddress', (testGroup) => {
// Test: should query account by evm address
testGroup.test('should query account by evm address', async (t) => {
const mockEvmAddress = '0x0000000000000000000000000000000000000000';

// Mock `fetch`
const mockFetch = t.capture(global, 'fetch', async () => ({
json: async () => ({
account: '0.0.123',
balance: { balance: 1000 },
evm_address: mockEvmAddress,
}),
}));

const result = await queryAccountByEvmAddress(mockEvmAddress);

const mockFetchInvocation0 = mockFetch()?.[0];

t.equal(
mockFetchInvocation0?.args?.[0],
'https://testnet.mirrornode.hedera.com/api/v1/accounts/0x0000000000000000000000000000000000000000?limit=1&order=asc&transactiontype=cryptotransfer&transactions=false',
);

t.equal(
result.accountId,
'0.0.123',
'Account ID should match the mock response',
);
t.equal(
result.accountBalance,
1000,
'Account balance should match the mock response',
);
t.equal(
result.accountEvmAddress,
mockEvmAddress,
'EVM address should match the mock response',
);
t.end();
});

// Test: should error when querying account by evm address and mirror node api responds with error
testGroup.test(
'should error when querying account by evm address and mirror node api responds with error',
async (t) => {
const mockEvmAddress = '0x0000000000000000000000000000000000000000';

// Mock `fetch`
const mockFetch = t.capture(global, 'fetch');

const result = await queryAccountByEvmAddress(mockEvmAddress);

const mockFetchInvocation0 = mockFetch()?.[0];

t.equal(
mockFetchInvocation0?.args?.[0],
'https://testnet.mirrornode.hedera.com/api/v1/accounts/0x0000000000000000000000000000000000000000?limit=1&order=asc&transactiontype=cryptotransfer&transactions=false',
);

t.notOk(
result.accountId,
'Account ID should be undefined for invalid response',
);
t.notOk(
result.accountBalance,
'Account balance should be undefined for invalid response',
);
t.notOk(
result.accountEvmAddress,
'EVM address should be undefined for invalid response',
);
t.end();
},
);
});

tape('[[group]] unit / util / queryAccountByPrivateKey', (testGroup) => {
// Test: should query account by private key
testGroup.test('should query account by private key', async (t) => {
const mockPrivateKey =
'0x6cd0462cd96ccaaec7e5fe514a670661a2b3c886b782830e2f2cc32ccb40980c';

// Mock `fetch`
const mockFetch = t.capture(global, 'fetch', async () => ({
json: async () => ({
accounts: [
{
account: '0.0.456',
balance: { balance: 2000 },
evm_address: '0x0000000000000000000000000000000000000001',
},
],
}),
}));

const result = await queryAccountByPrivateKey(mockPrivateKey);

const mockFetchInvocation0 = mockFetch()?.[0];

t.equal(
mockFetchInvocation0?.args?.[0],
'https://testnet.mirrornode.hedera.com/api/v1/accounts?account.publickey=0x0282da859e28f46b36ea4f9068f2bb34c19923cf6de540540d148bc7288ac4d997&balance=true&limit=1&order=desc',
);

t.equal(
result.accountId,
'0.0.456',
'Account ID should match the mock response',
);
t.equal(
result.accountBalance,
2000,
'Account balance should match the mock response',
);
t.equal(
result.accountEvmAddress,
'0x0000000000000000000000000000000000000001',
'EVM address should match the mock response',
);
t.end();
});

// Test: should error when querying account by private key and mirror node api responds with error
testGroup.test(
'should error when querying account by private key and mirror node api responds with error',
async (t) => {
const mockPrivateKey =
'0x6cd0462cd96ccaaec7e5fe514a670661a2b3c886b782830e2f2cc32ccb40980c';

// Mock `fetch`
const mockFetch = t.capture(global, 'fetch', async () => ({
json: async () => ({
accounts: [],
}),
}));

const result = await queryAccountByPrivateKey(mockPrivateKey);

const mockFetchInvocation0 = mockFetch()?.[0];

t.equal(
mockFetchInvocation0?.args?.[0],
'https://testnet.mirrornode.hedera.com/api/v1/accounts?account.publickey=0x0282da859e28f46b36ea4f9068f2bb34c19923cf6de540540d148bc7288ac4d997&balance=true&limit=1&order=desc',
);

t.notOk(
result.accountId,
'Account ID should be undefined for invalid response',
);
t.notOk(
result.accountBalance,
'Account balance should be undefined for invalid response',
);
t.notOk(
result.accountEvmAddress,
'EVM address should be undefined for invalid response',
);
t.end();
},
);
});

tape('[[group]] unit / util / isHexPrivateKey', (testGroup) => {
// Test: should identify valid hex private key
testGroup.test('should identify valid hex private key', (t) => {
const validKey =
'0x4bc72bb28d9ab751fef3e3d76241b5ff56b0ad2f240ac671fbaeb9f82d8545de';

t.ok(
isHexPrivateKey(validKey),
'Valid hex private key should be identified correctly',
);
t.end();
});

// Test: should identify invalid hex private keys
testGroup.test('should identify invalid hex private keys', (t) => {
const invalidKey1 =
'4bc72bb28d9ab751fef3e3d76241b5ff56b0ad2f240ac671fbaeb9f82d8545de';
const invalidKey2 = '0x123';
const invalidKey3 =
'0xZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ';

t.notOk(
isHexPrivateKey(invalidKey1),
'Key without "0x" prefix should be identified as invalid',
);
t.notOk(
isHexPrivateKey(invalidKey2),
'Key with too few characters should be identified as invalid',
);
t.notOk(
isHexPrivateKey(invalidKey3),
'Key with invalid characters should be identified as invalid',
);
t.end();
});
});

tape('[[group]] unit / util / calculateTransactionFeeFromViem', (testGroup) => {
// Test: should calculate transaction fee from viem receipt
testGroup.test('should calculate transaction fee from viem receipt', (t) => {
const receipt = {
gasUsed: '21000',
effectiveGasPrice: '50000000000000',
};

// 50,000,000,000,000 weibar = 5,000 tinybar
// 21,000 gas * 5,000 tinybar/gas = 105,000,000 tinybar = 1.05 hbar
const expectedFee = '1.05 ℏ';

const result = calculateTransactionFeeFromViem(receipt);

t.equal(
result,
expectedFee,
'Transaction fee should be calculated correctly from viem receipt',
);
t.end();
});
});