import fs from 'fs'; import path from 'path'; import { RustTypeMapper } from '../src/server-targets/rust/rust-type-mapper'; import { OpenRPCSpec } from '../src/types'; import { getSchemaForSolidityType } from '../src/solidity/parser'; describe('RustTypeMapper', () => { let testSpec: OpenRPCSpec; beforeAll(() => { // Load the test OpenRPC spec that's been generated from IComprehensiveTypes.sol const specPath = path.join( __dirname, 'fixtures', 'IComprehensiveTypes.openrpc.json' ); if (!fs.existsSync(specPath)) { throw new Error('Test spec not found.'); } testSpec = JSON.parse(fs.readFileSync(specPath, 'utf8')); }); describe('mapSolidityType', () => { let typeMapper: RustTypeMapper; beforeEach(() => { typeMapper = new RustTypeMapper(); }); it('should map basic Solidity types to Rust types', () => { expect(typeMapper.mapSolidityType('address')).toBe( 'alloy_primitives::Address' ); expect(typeMapper.mapSolidityType('uint256')).toBe( 'alloy_primitives::U256' ); expect(typeMapper.mapSolidityType('uint8')).toBe('u8'); expect(typeMapper.mapSolidityType('int256')).toBe( 'alloy_primitives::I256' ); expect(typeMapper.mapSolidityType('bytes')).toBe( 'alloy_primitives::Bytes' ); expect(typeMapper.mapSolidityType('string')).toBe('String'); expect(typeMapper.mapSolidityType('bool')).toBe('bool'); }); it('should handle array types', () => { expect(typeMapper.mapSolidityType('uint256[]')).toBe( 'Vec' ); expect(typeMapper.mapSolidityType('uint256[5]')).toBe( '[alloy_primitives::U256; 5]' ); expect(typeMapper.mapSolidityType('uint256[3][4]')).toMatch( /\[\[alloy_primitives::U256; 3\]; 4\]/ ); }); it('should handle fixed-size byte arrays', () => { expect(typeMapper.mapSolidityType('bytes1')).toBe( 'alloy_primitives::FixedBytes<1>' ); expect(typeMapper.mapSolidityType('bytes32')).toBe( 'alloy_primitives::FixedBytes<32>' ); }); it('should return null for unknown types', () => { expect(typeMapper.mapSolidityType('unknown')).toBe(null); }); }); describe('generateTypes', () => { let generatedTypes: string; beforeAll(() => { const typeMapper = new RustTypeMapper(); generatedTypes = typeMapper.generateTypes(testSpec); }); it('should generate valid Rust code structure for structs', () => { expect(generatedTypes).toMatch(/^use serde::\{Deserialize, Serialize\};/); expect(generatedTypes).toMatch(/use alloy_primitives::\{[^}]+\};/); }); it('should generate proper struct definitions from OpenRPC components', () => { // Should contain struct definitions expect(generatedTypes).toMatch( /#\[derive\(Debug, Clone, Serialize, Deserialize\)\]/ ); expect(generatedTypes).toMatch(/pub struct BasicStruct \{/); expect(generatedTypes).toMatch(/pub struct NestedStruct \{/); expect(generatedTypes).toMatch(/pub struct ComplexStruct \{/); // Should contain proper field types expect(generatedTypes).toMatch(/pub id: U256,/); expect(generatedTypes).toMatch(/pub name: String,/); expect(generatedTypes).toMatch(/pub active: bool,/); expect(generatedTypes).toMatch(/pub owner: Address,/); expect(generatedTypes).toMatch(/pub dynamic_array: Vec,/); expect(generatedTypes).toMatch(/pub fixed_array: \[U256; 5\],/); }); it('should only import used alloy primitives', () => { const importMatch = generatedTypes.match( /use alloy_primitives::\{([^}]+)\};/ ); expect(importMatch).toBeTruthy(); if (importMatch) { const imports = importMatch[1].split(',').map((s) => s.trim()); // Should include types used in structs expect(imports).toContain('U256'); expect(imports).toContain('Address'); expect(imports).toContain('FixedBytes'); // Should not contain duplicates expect(new Set(imports).size).toBe(imports.length); } }); it('should generate compilable Rust code', () => { // Basic syntax checks expect(generatedTypes).not.toMatch(/;;\s*$/m); // No double semicolons // Should have balanced brackets const openBrackets = (generatedTypes.match(/\[/g) || []).length; const closeBrackets = (generatedTypes.match(/\]/g) || []).length; expect(openBrackets).toBe(closeBrackets); // Should have balanced braces for Vec types and struct bodies const openBraces = (generatedTypes.match(/\{/g) || []).length; const closeBraces = (generatedTypes.match(/\}/g) || []).length; expect(openBraces).toBe(closeBraces); }); it('should handle nested struct types correctly', () => { // NestedStruct should reference BasicStruct expect(generatedTypes).toMatch(/pub basic: BasicStruct,/); // Should have proper Vec type for arrays expect(generatedTypes).toMatch(/pub numbers: Vec,/); }); it('should use snake_case for field names', () => { // Field names should be in snake_case expect(generatedTypes).toMatch(/pub dynamic_array:/); expect(generatedTypes).toMatch(/pub fixed_array:/); // Should not have camelCase in field names expect(generatedTypes).not.toMatch(/pub dynamicArray:/); expect(generatedTypes).not.toMatch(/pub fixedArray:/); }); }); describe('getRequiredImports', () => { it('should extract correct alloy imports from OpenRPC spec', () => { const typeMapper = new RustTypeMapper(); const imports = typeMapper.getRequiredImports(testSpec); expect(imports).toContain('Address'); expect(imports).toContain('U256'); expect(imports).toContain('Bytes'); // Should be sorted const sortedImports = [...imports].sort(); expect(imports).toEqual(sortedImports); // Should not contain duplicates expect(new Set(imports).size).toBe(imports.length); }); }); describe('Edge cases and error handling', () => { it('should return empty string when no struct components exist', () => { const minimalSpec: OpenRPCSpec = { openrpc: '1.2.6', info: { title: 'Test', version: '1.0.0' }, methods: [ { name: 'test', params: [ { name: 'param', schema: { type: 'string' }, // Basic type without components }, ], result: { schema: { type: 'boolean' } }, }, ], }; const typeMapper = new RustTypeMapper(); const types = typeMapper.generateTypes(minimalSpec); expect(types).toBe(''); // No types.rs needed for primitive-only specs }); it('should handle spec with components but no schemas', () => { const emptyComponentsSpec: OpenRPCSpec = { openrpc: '1.2.6', info: { title: 'Test', version: '1.0.0' }, methods: [], components: {}, // Empty components }; const typeMapper = new RustTypeMapper(); const types = typeMapper.generateTypes(emptyComponentsSpec); expect(types).toBe(''); }); it('should handle malformed struct schemas gracefully', () => { const malformedSpec: OpenRPCSpec = { openrpc: '1.2.6', info: { title: 'Test', version: '1.0.0' }, methods: [], components: { schemas: { BadStruct: { type: 'object', // Missing properties field }, }, }, }; const typeMapper = new RustTypeMapper(); const types = typeMapper.generateTypes(malformedSpec); // Should not crash and should return empty or minimal content expect(typeof types).toBe('string'); }); }); describe('Function type error handling', () => { it('should throw helpful error for function types', () => { expect(() => getSchemaForSolidityType( 'function(uint256) external pure returns (uint256)' ) ).toThrow(/Function types are not supported as parameters/); expect(() => getSchemaForSolidityType( 'function(uint256) external pure returns (uint256)' ) ).toThrow(/Function types cannot be serialized over JSON-RPC/); expect(() => getSchemaForSolidityType( 'function(uint256) external pure returns (uint256)' ) ).toThrow(/Pass a contract address and function selector instead/); }); it('should throw error for various function type formats', () => { const functionTypes = [ 'function(uint256) external pure returns (uint256)', 'function() external view returns (bool)', 'function(address,uint256) external payable', 'function external view returns (string memory)', ]; functionTypes.forEach((funcType) => { expect(() => getSchemaForSolidityType(funcType)).toThrow( /Function types are not supported/ ); }); }); }); });