Skip to content
Merged
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
150 changes: 150 additions & 0 deletions src/plugins/contract-erc20/__tests__/unit/symbol.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import type { AliasService, CommandHandlerArgs, CoreApi } from '@/core';
import type { ContractErc20CallSymbolOutput } from '@/plugins/contract-erc20/commands/symbol/output';

import { ZodError } from 'zod';

import { makeArgs, makeLogger } from '@/__tests__/mocks/mocks';
import { Status } from '@/core/shared/constants';
import { symbol as erc20SymbolHandler } from '@/plugins/contract-erc20/commands/symbol/handler';
import { ContractErc20CallSymbolInputSchema } from '@/plugins/contract-erc20/commands/symbol/input';

jest.mock('@hashgraph/sdk', () => ({
ContractId: {
fromString: jest.fn(() => ({
toEvmAddress: jest.fn(() => 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'),
})),
},
TokenType: {
NonFungibleUnique: 'NonFungibleUnique',
FungibleCommon: 'FungibleCommon',
},
}));

const mockEncodeFunctionData = jest.fn().mockReturnValue('0xencoded');
const mockDecodeFunctionResult = jest
.fn()
.mockReturnValue(['HBAR'] as unknown[]);

jest.mock('@/plugins/contract-erc20/utils/erc20-abi-resolver', () => ({
getAbiErc20Interface: jest.fn(() => ({
encodeFunctionData: mockEncodeFunctionData,
decodeFunctionResult: mockDecodeFunctionResult,
})),
}));

jest.mock('@/core/utils/contract-resolver', () => ({
resolveContractId: jest.fn(() => '0.0.1234'),
}));

describe('contract-erc20 plugin - symbol command (unit)', () => {
let api: CommandHandlerArgs['api'];
let logger: ReturnType<typeof makeLogger>;

beforeEach(() => {
jest.clearAllMocks();

logger = makeLogger();

api = {
network: {
getCurrentNetwork: jest.fn(() => 'testnet'),
},
alias: {} as unknown as AliasService,
mirror: {
postContractCall: jest.fn(),
},
} as unknown as CoreApi;
});

test('calls ERC-20 symbol successfully and returns expected output', async () => {
(api.mirror.postContractCall as jest.Mock).mockResolvedValue({
result: '0xencodedResult',
});

const args = makeArgs(api, logger, {
contract: 'some-alias-or-id',
});

const result = await erc20SymbolHandler(args);

expect(result.status).toBe(Status.Success);
expect(result.outputJson).toBeDefined();

const parsed = JSON.parse(
result.outputJson as string,
) as ContractErc20CallSymbolOutput;

expect(parsed.contractId).toBe('0.0.1234');
expect(parsed.contractSymbol).toBe('HBAR');
expect(parsed.network).toBe('testnet');

expect(mockEncodeFunctionData).toHaveBeenCalledWith('symbol');
expect(api.mirror.postContractCall).toHaveBeenCalledWith({
to: `0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`,
data: '0xencoded',
});
expect(mockDecodeFunctionResult).toHaveBeenCalledWith(
'symbol',
'0xencodedResult',
);
expect(logger.info).toHaveBeenCalledWith(
'Calling ERC-20 "symbol" function on contract 0.0.1234 (network: testnet)',
);
});

test('returns failure when mirror returns no result', async () => {
(api.mirror.postContractCall as jest.Mock).mockResolvedValue({});

const args = makeArgs(api, logger, {
contract: 'some-alias-or-id',
});

const result = await erc20SymbolHandler(args);

expect(result.status).toBe(Status.Failure);
expect(result.errorMessage).toContain(
'There was a problem with calling contract 0.0.1234 "symbol" function',
);
});

test('returns failure when decodeFunctionResult returns empty array', async () => {
(api.mirror.postContractCall as jest.Mock).mockResolvedValue({
result: '0xencodedResult',
});
mockDecodeFunctionResult.mockReturnValueOnce([]);

const args = makeArgs(api, logger, {
contract: 'some-alias-or-id',
});

const result = await erc20SymbolHandler(args);

expect(result.status).toBe(Status.Failure);
expect(result.errorMessage).toContain(
'There was a problem with decoding contract 0.0.1234 "symbol" function result',
);
});

test('returns failure when postContractCall throws', async () => {
(api.mirror.postContractCall as jest.Mock).mockRejectedValue(
new Error('mirror node error'),
);

const args = makeArgs(api, logger, {
contract: 'some-alias-or-id',
});

const result = await erc20SymbolHandler(args);

expect(result.status).toBe(Status.Failure);
expect(result.errorMessage).toContain(
'Failed to call "symbol" function: mirror node error',
);
});

test('schema validation fails when contract is missing', () => {
expect(() => {
ContractErc20CallSymbolInputSchema.parse({});
}).toThrow(ZodError);
});
});
72 changes: 72 additions & 0 deletions src/plugins/contract-erc20/commands/symbol/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* Contract ERC20 symbol Command Handler
*/
import type { CommandExecutionResult, CommandHandlerArgs } from '@/core';
import type { ContractErc20CallSymbolOutput } from '@/plugins/contract-erc20/commands/symbol/output';

import { ContractId } from '@hashgraph/sdk';

import { Status } from '@/core/shared/constants';
import { resolveContractId } from '@/core/utils/contract-resolver';
import { formatError } from '@/core/utils/errors';
import { getAbiErc20Interface } from '@/plugins/contract-erc20/utils/erc20-abi-resolver';

import { ContractErc20CallSymbolInputSchema } from './input';

const ERC_20_FUNCTION_NAME = 'symbol';

export async function symbol(
args: CommandHandlerArgs,
): Promise<CommandExecutionResult> {
const { logger, api } = args;
try {
const validArgs = ContractErc20CallSymbolInputSchema.parse(args.args);
const contract = validArgs.contract;

const network = api.network.getCurrentNetwork();

const contractId = resolveContractId(contract, api.alias, network);
logger.info(
`Calling ERC-20 "symbol" function on contract ${contractId} (network: ${network})`,
);
const erc20Interface = getAbiErc20Interface();
const data = erc20Interface.encodeFunctionData(ERC_20_FUNCTION_NAME);

const response = await api.mirror.postContractCall({
to: `0x${ContractId.fromString(contractId).toEvmAddress()}`,
data: data,
});

if (!response || !response.result) {
throw new Error(
`There was a problem with calling contract ${contractId} "symbol" function`,
);
}
const decodedParameter = erc20Interface.decodeFunctionResult(
ERC_20_FUNCTION_NAME,
response.result,
);
if (!decodedParameter || !decodedParameter[0]) {
throw new Error(
`There was a problem with decoding contract ${contractId} "symbol" function result`,
);
}
const contractSymbol = String(decodedParameter[0]);

const outputData: ContractErc20CallSymbolOutput = {
contractId,
contractSymbol,
network,
};

return {
status: Status.Success,
outputJson: JSON.stringify(outputData),
};
} catch (error: unknown) {
return {
status: Status.Failure,
errorMessage: formatError('Failed to call "symbol" function', error),
};
}
}
10 changes: 10 additions & 0 deletions src/plugins/contract-erc20/commands/symbol/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Contract ERC20 Symbol Command Exports
* For use by tests and external consumers
*/
export { symbol } from './handler';
export type { ContractErc20CallSymbolOutput } from './output';
export {
CONTRACT_ERC20_CALL_SYMBOL_CREATE_TEMPLATE,
ContractErc20CallSymbolOutputSchema,
} from './output';
10 changes: 10 additions & 0 deletions src/plugins/contract-erc20/commands/symbol/input.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { z } from 'zod';

import { EntityReferenceSchema } from '@/core/schemas';

/**
* Input schema for contract erc20 call symbol command
*/
export const ContractErc20CallSymbolInputSchema = z.object({
contract: EntityReferenceSchema.describe('Contract identifier (ID or alias)'),
});
19 changes: 19 additions & 0 deletions src/plugins/contract-erc20/commands/symbol/output.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { z } from 'zod';

import { EntityIdSchema, TokenSymbolSchema } from '@/core/schemas';
import { SupportedNetwork } from '@/core/types/shared.types';

export const ContractErc20CallSymbolOutputSchema = z.object({
contractId: EntityIdSchema,
contractSymbol: TokenSymbolSchema,
network: SupportedNetwork,
});

export type ContractErc20CallSymbolOutput = z.infer<
typeof ContractErc20CallSymbolOutputSchema
>;

export const CONTRACT_ERC20_CALL_SYMBOL_CREATE_TEMPLATE = `
✅ Contract ({{hashscanLink contractId "contract" network}}) function "symbol" called successfully!
Contract symbol: {{contractSymbol}}
`.trim();
1 change: 1 addition & 0 deletions src/plugins/contract-erc20/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
* Exports the config plugin manifest
*/
export { name } from './commands/name';
export { symbol } from './commands/symbol';
export { contractErc20PluginManifest } from './manifest';
25 changes: 25 additions & 0 deletions src/plugins/contract-erc20/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ import {
ContractErc20CallNameOutputSchema,
name,
} from '@/plugins/contract-erc20/commands/name';
import {
CONTRACT_ERC20_CALL_SYMBOL_CREATE_TEMPLATE,
ContractErc20CallSymbolOutputSchema,
symbol,
} from '@/plugins/contract-erc20/commands/symbol';

export const contractErc20PluginManifest: PluginManifest = {
name: 'contract-erc20',
Expand Down Expand Up @@ -37,6 +42,26 @@ export const contractErc20PluginManifest: PluginManifest = {
humanTemplate: CONTRACT_ERC20_CALL_NAME_CREATE_TEMPLATE,
},
},
{
name: 'symbol',
summary: 'Call symbol function',
description: 'Command for calling ERC-20 symbol function',
options: [
{
name: 'contract',
short: 'c',
type: OptionType.STRING,
required: true,
description:
'Smart contract ID represented by alias or contract ID. Option required',
},
],
handler: symbol,
output: {
schema: ContractErc20CallSymbolOutputSchema,
humanTemplate: CONTRACT_ERC20_CALL_SYMBOL_CREATE_TEMPLATE,
},
},
],
};

Expand Down
Loading