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

feat: support () type in typegen #2122

Merged
merged 16 commits into from
Apr 23, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/polite-rabbits-care.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@fuel-ts/abi-typegen": patch
---

feat: support `()` type in typegen
50 changes: 28 additions & 22 deletions packages/abi-typegen/src/abi/functions/Function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { TargetEnum } from '../../types/enums/TargetEnum';
import type { IType } from '../../types/interfaces/IType';
import { findType } from '../../utils/findType';
import { parseTypeArguments } from '../../utils/parseTypeArguments';
import { EmptyType } from '../types/EmptyType';

export class Function implements IFunction {
public name: string;
Expand All @@ -26,33 +27,38 @@ export class Function implements IFunction {
const { types } = this;

// loop through all inputs
const inputs = this.rawAbiFunction.inputs.map((input) => {
const { name, type: typeId, typeArguments } = input;
const inputs = this.rawAbiFunction.inputs
.filter((input) => {
const type = findType({ types, typeId: input.type });
return type.rawAbiType.type !== EmptyType.swayType;
})
.map((input) => {
const { name, type: typeId, typeArguments } = input;

const type = findType({ types, typeId });
const type = findType({ types, typeId });

let typeDecl: string;
let typeDecl: string;

if (typeArguments) {
// recursively process child `typeArguments`
typeDecl = parseTypeArguments({
types,
target: TargetEnum.INPUT,
parentTypeId: typeId,
typeArguments,
});
} else {
// or just collect type declaration
typeDecl = type.attributes.inputLabel;
}
if (typeArguments) {
// recursively process child `typeArguments`
typeDecl = parseTypeArguments({
types,
target: TargetEnum.INPUT,
parentTypeId: typeId,
typeArguments,
});
} else {
// or just collect type declaration
typeDecl = type.attributes.inputLabel;
}

// assemble it in `[key: string]: <Type>` fashion
if (shouldPrefixParams) {
return `${name}: ${typeDecl}`;
}
// assemble it in `[key: string]: <Type>` fashion
if (shouldPrefixParams) {
return `${name}: ${typeDecl}`;
}

return typeDecl;
});
return typeDecl;
});

return inputs.join(', ');
}
Expand Down
20 changes: 20 additions & 0 deletions packages/abi-typegen/src/abi/types/EmptyType.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { EmptyType } from './EmptyType';

/**
* @group node
*/
describe('EmptyType.ts', () => {
test('should properly parse type attributes', () => {
const emptyType = new EmptyType({
rawAbiType: {
components: null,
typeParameters: null,
typeId: 0,
type: EmptyType.swayType,
},
});

expect(emptyType.attributes.inputLabel).toEqual('never');
expect(emptyType.attributes.outputLabel).toEqual('void');
});
});
32 changes: 32 additions & 0 deletions packages/abi-typegen/src/abi/types/EmptyType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { IRawAbiTypeRoot } from '../..';
import type { IType } from '../../types/interfaces/IType';

import { AType } from './AType';

export class EmptyType extends AType implements IType {
public static swayType = '()';

public name = 'empty';

static MATCH_REGEX: RegExp = /^\(\)$/m;

constructor(params: { rawAbiType: IRawAbiTypeRoot }) {
super(params);
this.attributes = {
/**
* The empty type is always ignored in function inputs. If it makes
* its way into a function's inputs list, it's a bug in the typegen.
*/
inputLabel: `never`,
outputLabel: `void`,
};
}

static isSuitableFor(params: { type: string }) {
return EmptyType.MATCH_REGEX.test(params.type);
}

public parseComponentsAttributes(_params: { types: IType[] }) {
return this.attributes;
}
}
4 changes: 1 addition & 3 deletions packages/abi-typegen/src/abi/types/EnumType.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ describe('EnumType.ts', () => {
abiContents: { types: rawTypes },
} = getTypegenForcProject(project);

const types = rawTypes
.filter((t) => t.type !== '()')
.map((rawAbiType: IRawAbiTypeRoot) => makeType({ rawAbiType }));
const types = rawTypes.map((rawAbiType: IRawAbiTypeRoot) => makeType({ rawAbiType }));

return { types };
}
Expand Down
7 changes: 4 additions & 3 deletions packages/abi-typegen/src/abi/types/EnumType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { extractStructName } from '../../utils/extractStructName';
import { findType } from '../../utils/findType';

import { AType } from './AType';
import { EmptyType } from './EmptyType';

export class EnumType extends AType implements IType {
public static swayType = 'enum MyEnumName';
Expand Down Expand Up @@ -43,10 +44,10 @@ export class EnumType extends AType implements IType {
public getNativeEnum(params: { types: IType[] }) {
const { types } = params;

const typeHash: { [key: number]: IType['rawAbiType'] } = types.reduce(
const typeHash: { [key: number]: IType['rawAbiType']['type'] } = types.reduce(
(hash, row) => ({
...hash,
[row.rawAbiType.typeId]: row,
[row.rawAbiType.typeId]: row.rawAbiType.type,
}),
{}
);
Expand All @@ -56,7 +57,7 @@ export class EnumType extends AType implements IType {
// `components` array guaranteed to always exist for structs/enums
const enumComponents = components as IRawAbiTypeComponent[];

if (!enumComponents.every(({ type }) => !typeHash[type])) {
if (!enumComponents.every(({ type }) => typeHash[type] === EmptyType.swayType)) {
return undefined;
}

Expand Down
4 changes: 1 addition & 3 deletions packages/abi-typegen/src/abi/types/OptionType.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ describe('OptionType.ts', () => {
const project = getTypegenForcProject(AbiTypegenProjectsEnum.OPTION_SIMPLE);
const rawTypes = project.abiContents.types;

const types = rawTypes
.filter((t) => t.type !== '()')
.map((rawAbiType: IRawAbiTypeRoot) => makeType({ rawAbiType }));
const types = rawTypes.map((rawAbiType: IRawAbiTypeRoot) => makeType({ rawAbiType }));

return { types };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ describe('parseTypeArguments.ts', () => {
test('should fallback to void for null outputs', () => {
const project = getTypegenForcProject(AbiTypegenProjectsEnum.FN_VOID);

const types = bundleTypes([]);
const types = bundleTypes(project.abiContents.types);
arboleya marked this conversation as resolved.
Show resolved Hide resolved
const typeArguments = [project.abiContents.functions[0].output];

// should fallback to void because `typeArguments.type` will be 0, and non-existent
Expand Down
11 changes: 2 additions & 9 deletions packages/abi-typegen/src/utils/parseTypeArguments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,10 @@ export function parseTypeArguments(params: {

// loop through all `typeArgument` items
typeArguments.forEach((typeArgument) => {
let currentLabel: string;

const currentTypeId = typeArgument.type;

try {
const currentType = findType({ types, typeId: currentTypeId });
currentLabel = currentType.attributes[attributeKey];
} catch (_err) {
// used for functions without output
currentLabel = 'void';
}
const currentType = findType({ types, typeId: currentTypeId });
const currentLabel = currentType.attributes[attributeKey];

if (typeArgument.typeArguments) {
// recursively process nested `typeArguments`
Expand Down
2 changes: 1 addition & 1 deletion packages/abi-typegen/src/utils/shouldSkipAbiType.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export function shouldSkipAbiType(params: { type: string }) {
const ignoreList = ['()', 'struct RawVec'];
const ignoreList = ['struct RawVec'];
const shouldSkip = ignoreList.indexOf(params.type) >= 0;
return shouldSkip;
}
1 change: 0 additions & 1 deletion packages/abi-typegen/src/utils/shouldSkipType.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { supportedTypes } from './supportedTypes';
*/
describe('types.ts', () => {
test('should always skip these types', () => {
expect(shouldSkipAbiType({ type: '()' })).toEqual(true);
expect(shouldSkipAbiType({ type: 'struct RawVec' })).toEqual(true);
});

Expand Down
2 changes: 1 addition & 1 deletion packages/abi-typegen/src/utils/supportedTypes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ import { supportedTypes } from './supportedTypes';
*/
describe('supportedTypes.ts', () => {
test('should export all supported types', () => {
expect(supportedTypes.length).toEqual(22);
expect(supportedTypes.length).toEqual(23);
});
});
2 changes: 2 additions & 0 deletions packages/abi-typegen/src/utils/supportedTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { B256Type } from '../abi/types/B256Type';
import { B512Type } from '../abi/types/B512Type';
import { BoolType } from '../abi/types/BoolType';
import { BytesType } from '../abi/types/BytesType';
import { EmptyType } from '../abi/types/EmptyType';
import { EnumType } from '../abi/types/EnumType';
import { EvmAddressType } from '../abi/types/EvmAddressType';
import { GenericType } from '../abi/types/GenericType';
Expand All @@ -22,6 +23,7 @@ import { U8Type } from '../abi/types/U8Type';
import { VectorType } from '../abi/types/VectorType';

export const supportedTypes = [
EmptyType,
ArrayType,
B256Type,
B512Type,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ struct StructWithSingleOption {
}

abi MyContract {
fn types_empty(x: ()) -> ();
fn types_empty_then_value(x: (), y: u8) -> ();
fn types_value_then_empty(x: u8, y: ()) -> ();
fn types_value_then_empty_then_value(x: u8, y: (), z: u8) -> ();
fn types_u8(x: u8) -> u8;
fn types_u16(x: u16) -> u16;
fn types_u32(x: u32) -> u32;
Expand All @@ -51,6 +55,19 @@ abi MyContract {
}

impl MyContract for Contract {
fn types_empty(x: ()) -> () {
x
}
fn types_empty_then_value(x: (), y: u8) -> () {
()
}
fn types_value_then_empty(x: u8, y: ()) -> () {
()
}
fn types_value_then_empty_then_value(x: u8, y: (), z: u8) -> () {
()
}

fn types_u8(x: u8) -> u8 {
255
}
Expand Down
16 changes: 16 additions & 0 deletions packages/abi-typegen/test/fixtures/templates/contract/dts.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ interface MyContractAbiInterface extends Interface {
types_b512: FunctionFragment;
types_bool: FunctionFragment;
types_bytes: FunctionFragment;
types_empty: FunctionFragment;
types_empty_then_value: FunctionFragment;
types_enum: FunctionFragment;
types_evm_address: FunctionFragment;
types_option: FunctionFragment;
Expand All @@ -60,6 +62,8 @@ interface MyContractAbiInterface extends Interface {
types_u32: FunctionFragment;
types_u64: FunctionFragment;
types_u8: FunctionFragment;
types_value_then_empty: FunctionFragment;
types_value_then_empty_then_value: FunctionFragment;
types_vector_geo: FunctionFragment;
types_vector_option: FunctionFragment;
types_vector_u8: FunctionFragment;
Expand All @@ -71,6 +75,8 @@ interface MyContractAbiInterface extends Interface {
encodeFunctionData(functionFragment: 'types_b512', values: [string]): Uint8Array;
encodeFunctionData(functionFragment: 'types_bool', values: [boolean]): Uint8Array;
encodeFunctionData(functionFragment: 'types_bytes', values: [Bytes]): Uint8Array;
encodeFunctionData(functionFragment: 'types_empty', values: []): Uint8Array;
encodeFunctionData(functionFragment: 'types_empty_then_value', values: [BigNumberish]): Uint8Array;
encodeFunctionData(functionFragment: 'types_enum', values: [MyEnumInput]): Uint8Array;
encodeFunctionData(functionFragment: 'types_evm_address', values: [EvmAddress]): Uint8Array;
encodeFunctionData(functionFragment: 'types_option', values: [Option<BigNumberish>]): Uint8Array;
Expand All @@ -85,6 +91,8 @@ interface MyContractAbiInterface extends Interface {
encodeFunctionData(functionFragment: 'types_u32', values: [BigNumberish]): Uint8Array;
encodeFunctionData(functionFragment: 'types_u64', values: [BigNumberish]): Uint8Array;
encodeFunctionData(functionFragment: 'types_u8', values: [BigNumberish]): Uint8Array;
encodeFunctionData(functionFragment: 'types_value_then_empty', values: [BigNumberish]): Uint8Array;
encodeFunctionData(functionFragment: 'types_value_then_empty_then_value', values: [BigNumberish, BigNumberish]): Uint8Array;
encodeFunctionData(functionFragment: 'types_vector_geo', values: [Vec<MyStructInput>]): Uint8Array;
encodeFunctionData(functionFragment: 'types_vector_option', values: [Vec<StructWithMultiOptionInput>]): Uint8Array;
encodeFunctionData(functionFragment: 'types_vector_u8', values: [Vec<BigNumberish>]): Uint8Array;
Expand All @@ -95,6 +103,8 @@ interface MyContractAbiInterface extends Interface {
decodeFunctionData(functionFragment: 'types_b512', data: BytesLike): DecodedValue;
decodeFunctionData(functionFragment: 'types_bool', data: BytesLike): DecodedValue;
decodeFunctionData(functionFragment: 'types_bytes', data: BytesLike): DecodedValue;
decodeFunctionData(functionFragment: 'types_empty', data: BytesLike): DecodedValue;
decodeFunctionData(functionFragment: 'types_empty_then_value', data: BytesLike): DecodedValue;
decodeFunctionData(functionFragment: 'types_enum', data: BytesLike): DecodedValue;
decodeFunctionData(functionFragment: 'types_evm_address', data: BytesLike): DecodedValue;
decodeFunctionData(functionFragment: 'types_option', data: BytesLike): DecodedValue;
Expand All @@ -109,6 +119,8 @@ interface MyContractAbiInterface extends Interface {
decodeFunctionData(functionFragment: 'types_u32', data: BytesLike): DecodedValue;
decodeFunctionData(functionFragment: 'types_u64', data: BytesLike): DecodedValue;
decodeFunctionData(functionFragment: 'types_u8', data: BytesLike): DecodedValue;
decodeFunctionData(functionFragment: 'types_value_then_empty', data: BytesLike): DecodedValue;
decodeFunctionData(functionFragment: 'types_value_then_empty_then_value', data: BytesLike): DecodedValue;
decodeFunctionData(functionFragment: 'types_vector_geo', data: BytesLike): DecodedValue;
decodeFunctionData(functionFragment: 'types_vector_option', data: BytesLike): DecodedValue;
decodeFunctionData(functionFragment: 'types_vector_u8', data: BytesLike): DecodedValue;
Expand All @@ -123,6 +135,8 @@ export class MyContractAbi extends Contract {
types_b512: InvokeFunction<[x: string], string>;
types_bool: InvokeFunction<[x: boolean], boolean>;
types_bytes: InvokeFunction<[x: Bytes], Bytes>;
types_empty: InvokeFunction<[], void>;
types_empty_then_value: InvokeFunction<[y: BigNumberish], void>;
types_enum: InvokeFunction<[x: MyEnumInput], MyEnumOutput>;
types_evm_address: InvokeFunction<[x: EvmAddress], EvmAddress>;
types_option: InvokeFunction<[x: Option<BigNumberish>], Option<number>>;
Expand All @@ -137,6 +151,8 @@ export class MyContractAbi extends Contract {
types_u32: InvokeFunction<[x: BigNumberish], number>;
types_u64: InvokeFunction<[x: BigNumberish], BN>;
types_u8: InvokeFunction<[x: BigNumberish], number>;
types_value_then_empty: InvokeFunction<[x: BigNumberish], void>;
types_value_then_empty_then_value: InvokeFunction<[x: BigNumberish, z: BigNumberish], void>;
types_vector_geo: InvokeFunction<[x: Vec<MyStructInput>], Vec<MyStructOutput>>;
types_vector_option: InvokeFunction<[x: Vec<StructWithMultiOptionInput>], Vec<StructWithMultiOptionOutput>>;
types_vector_u8: InvokeFunction<[x: Vec<BigNumberish>], Vec<number>>;
Expand Down