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

Create token-specific entities #2309

Open
wants to merge 3 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
59 changes: 45 additions & 14 deletions src/domain/tokens/__tests__/token.builder.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,52 @@
import { faker } from '@faker-js/faker';
import type { IBuilder } from '@/__tests__/builder';
import { Builder } from '@/__tests__/builder';
import type { Token } from '@/domain/tokens/entities/token.entity';
import { TokenType } from '@/domain/tokens/entities/token.entity';
import type {
Erc20Token,
Erc721Token,
NativeToken,
Token,
} from '@/domain/tokens/entities/token.entity';
import { getAddress } from 'viem';

export function nativeTokenBuilder(): IBuilder<NativeToken> {
return new Builder<NativeToken>()
.with('type', 'NATIVE_TOKEN')
.with('decimals', faker.number.int({ min: 0, max: 18 }))
.with('address', getAddress(faker.finance.ethereumAddress()))
.with('logoUri', faker.internet.url({ appendSlash: false }))
.with('name', faker.word.sample())
.with('symbol', faker.finance.currencySymbol())
.with('trusted', faker.datatype.boolean());
}

export function erc20TokenBuilder(): IBuilder<Erc20Token> {
return new Builder<Erc20Token>()
.with('type', 'ERC20')
.with('decimals', faker.number.int({ min: 0, max: 18 }))
.with('address', getAddress(faker.finance.ethereumAddress()))
.with('logoUri', faker.internet.url({ appendSlash: false }))
.with('name', faker.word.sample())
.with('symbol', faker.finance.currencySymbol())
.with('trusted', faker.datatype.boolean());
}

export function erc721TokenBuilder(): IBuilder<Erc721Token> {
return new Builder<Erc721Token>()
.with('type', 'ERC721')
.with('decimals', 0)
.with('trusted', true)
.with('address', getAddress(faker.finance.ethereumAddress()))
.with('logoUri', faker.internet.url({ appendSlash: false }))
.with('name', faker.word.sample())
.with('symbol', faker.finance.currencySymbol())
.with('trusted', faker.datatype.boolean());
}

export function tokenBuilder(): IBuilder<Token> {
return (
new Builder<Token>()
.with('address', getAddress(faker.finance.ethereumAddress()))
// min/max boundaries are set here in order to prevent overflows on balances calculation.
// See: https://github.com/safe-global/safe-client-gateway/blob/65364f9ad31fc9832b32248f74356c4f6660787e/src/datasources/balances-api/safe-balances-api.service.ts#L173
.with('decimals', faker.number.int({ min: 0, max: 32 }))
.with('logoUri', faker.internet.url({ appendSlash: false }))
.with('name', faker.word.sample())
.with('symbol', faker.finance.currencySymbol())
.with('type', faker.helpers.arrayElement(Object.values(TokenType)))
.with('trusted', faker.datatype.boolean())
);
return faker.helpers.arrayElement([
nativeTokenBuilder,
erc20TokenBuilder,
erc721TokenBuilder,
])();
}
92 changes: 92 additions & 0 deletions src/domain/tokens/entities/__tests__/token.entity.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import {
erc20TokenBuilder,
erc721TokenBuilder,
nativeTokenBuilder,
tokenBuilder,
} from '@/domain/tokens/__tests__/token.builder';
import { TokenSchema } from '@/domain/tokens/entities/token.entity';
import type { Token } from '@/domain/tokens/entities/token.entity';
import { faker } from '@faker-js/faker';
import { getAddress } from 'viem';

describe('Token', () => {
it('should validate a token', () => {
const token = tokenBuilder().build();

const result = TokenSchema.safeParse(token);

expect(result.success).toBe(true);
});

it('should checksum address', () => {
const nonChecksummedAddress = faker.finance
.ethereumAddress()
.toLowerCase() as `0x${string}`;
const token = tokenBuilder().with('address', nonChecksummedAddress).build();

const result = TokenSchema.safeParse(token);

expect(result.success && result.data['address']).toBe(
getAddress(nonChecksummedAddress),
);
});

it.each<keyof Token>([
'address',
'logoUri',
'name',
'symbol',
'type',
'trusted',
])('should not allow %s to be undefined', (key) => {
const token = tokenBuilder().build();
delete token[key];

const result = TokenSchema.safeParse(token);

expect(
!result.success &&
result.error.issues.length === 1 &&
result.error.issues[0].path.length === 1 &&
result.error.issues[0].path[0] === key,
).toBe(true);
});

it('should not allow native tokens to have undefined decimals', () => {
const token = nativeTokenBuilder().build();
// @ts-expect-error - inferred type does not allow undefined decimals
delete token.decimals;

const result = TokenSchema.safeParse(token);

expect(!result.success && result.error.issues).toStrictEqual([
{
code: 'invalid_type',
expected: 'number',
message: 'Required',
path: ['decimals'],
received: 'undefined',
},
]);
});

it('should default ERC-20 decimals to 0', () => {
const token = erc20TokenBuilder().build();
// @ts-expect-error - inferred type does not allow undefined decimals
delete token.decimals;

const result = TokenSchema.safeParse(token);

expect(result.success && result.data.decimals).toBe(0);
});

it('should default ERC-721 decimals to 0', () => {
const token = erc721TokenBuilder().build();
// @ts-expect-error - inferred type does not allow undefined decimals
delete token.decimals;

const result = TokenSchema.safeParse(token);

expect(result.success && result.data.decimals).toBe(0);
});
});

This file was deleted.

16 changes: 0 additions & 16 deletions src/domain/tokens/entities/schemas/token.schema.ts

This file was deleted.

59 changes: 51 additions & 8 deletions src/domain/tokens/entities/token.entity.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,53 @@
import type { TokenSchema } from '@/domain/tokens/entities/schemas/token.schema';
import type { z } from 'zod';

export enum TokenType {
Erc721 = 'ERC721',
Erc20 = 'ERC20',
NativeToken = 'NATIVE_TOKEN',
}
import { z } from 'zod';
import { buildPageSchema } from '@/domain/entities/schemas/page.schema.factory';
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the "core" change, from which everything else implemented.

import { AddressSchema } from '@/validation/entities/schemas/address.schema';

/**
* ERC-20 decimals are optional
* @see https://eips.ethereum.org/EIPS/eip-20#decimals
*/
const DEFAULT_ERC20_DECIMALS = 0;
/**
* ERC-721 decimals should return uint8(0) or be optional
* @see https://eips.ethereum.org/EIPS/eip-721#backwards-compatibility
*/
const DEFAULT_ERC721_DECIMALS = 0;

const BaseTokenSchema = z.object({
address: AddressSchema,
logoUri: z.string().url(),
name: z.string(),
symbol: z.string(),
trusted: z.boolean(),
});

const NativeTokenSchema = BaseTokenSchema.extend({
type: z.literal('NATIVE_TOKEN'),
decimals: z.number(),
});

const Erc20TokenSchema = BaseTokenSchema.extend({
type: z.literal('ERC20'),
decimals: z.number().catch(DEFAULT_ERC20_DECIMALS),
});

const Erc721TokenSchema = BaseTokenSchema.extend({
type: z.literal('ERC721'),
decimals: z.number().catch(DEFAULT_ERC721_DECIMALS),
Comment on lines +25 to +35
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

String types are now preferred due to type complaints when using different enums from the domain vs. route layers.

});

export const TokenSchema = z.discriminatedUnion('type', [
NativeTokenSchema,
Erc20TokenSchema,
Erc721TokenSchema,
]);

export const TokenPageSchema = buildPageSchema(TokenSchema);

export type NativeToken = z.infer<typeof NativeTokenSchema>;

export type Erc20Token = z.infer<typeof Erc20TokenSchema>;

export type Erc721Token = z.infer<typeof Erc721TokenSchema>;

export type Token = z.infer<typeof TokenSchema>;
2 changes: 1 addition & 1 deletion src/domain/tokens/token.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ITokenRepository } from '@/domain/tokens/token.repository.interface';
import {
TokenPageSchema,
TokenSchema,
} from '@/domain/tokens/entities/schemas/token.schema';
} from '@/domain/tokens/entities/token.entity';

@Injectable()
export class TokenRepository implements ITokenRepository {
Expand Down
9 changes: 6 additions & 3 deletions src/routes/balances/balances.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import { IChainsRepository } from '@/domain/chains/chains.repository.interface';
import { NativeCurrency } from '@/domain/chains/entities/native.currency.entity';
import { Balance } from '@/routes/balances/entities/balance.entity';
import { Balances } from '@/routes/balances/entities/balances.entity';
import { TokenType } from '@/routes/balances/entities/token-type.entity';
import {
NativeToken,
Erc20Token,
} from '@/routes/balances/entities/token.entity';
import { NULL_ADDRESS } from '@/routes/common/constants';
import orderBy from 'lodash/orderBy';
import { getNumberString } from '@/domain/common/utils/utils';
Expand Down Expand Up @@ -50,8 +53,8 @@ export class BalancesService {
nativeCurrency: NativeCurrency,
): Balance {
const tokenAddress = balance.tokenAddress;
const tokenType =
tokenAddress === null ? TokenType.NativeToken : TokenType.Erc20;
const tokenType: (NativeToken | Erc20Token)['type'] =
tokenAddress === null ? 'NATIVE_TOKEN' : 'ERC20';

const tokenMetaData =
tokenAddress === null
Expand Down
19 changes: 15 additions & 4 deletions src/routes/balances/entities/balance.entity.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
import { ApiProperty } from '@nestjs/swagger';
import { Token } from '@/routes/balances/entities/token.entity';
import { ApiExtraModels, ApiProperty, getSchemaPath } from '@nestjs/swagger';
import {
NativeToken,
Erc20Token,
Erc721Token,
} from '@/routes/balances/entities/token.entity';

@ApiExtraModels(NativeToken, Erc20Token, Erc721Token)
export class Balance {
@ApiProperty()
balance!: string;
@ApiProperty()
fiatBalance!: string;
@ApiProperty()
fiatConversion!: string;
@ApiProperty()
tokenInfo!: Token;
@ApiProperty({
oneOf: [
{ $ref: getSchemaPath(NativeToken) },
{ $ref: getSchemaPath(Erc20Token) },
{ $ref: getSchemaPath(Erc721Token) },
],
})
tokenInfo!: NativeToken | Erc20Token | Erc721Token;
}
6 changes: 0 additions & 6 deletions src/routes/balances/entities/token-type.entity.ts

This file was deleted.

Loading
Loading