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

update applications endpoint #1443

Merged
merged 12 commits into from
Feb 13, 2025
9 changes: 6 additions & 3 deletions src/endpoints/applications/application.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ApiOkResponse, ApiOperation, ApiQuery, ApiTags } from "@nestjs/swagger"
import { ApplicationService } from "./application.service";
import { QueryPagination } from "src/common/entities/query.pagination";
import { ApplicationFilter } from "./entities/application.filter";
import { ParseIntPipe } from "@multiversx/sdk-nestjs-common";
import { ParseIntPipe, ParseBoolPipe } from "@multiversx/sdk-nestjs-common";
import { Application } from "./entities/application";

@Controller()
Expand All @@ -20,15 +20,18 @@ export class ApplicationController {
@ApiQuery({ name: 'size', description: 'Number of items to retrieve', required: false })
@ApiQuery({ name: 'before', description: 'Before timestamp', required: false })
@ApiQuery({ name: 'after', description: 'After timestamp', required: false })
@ApiQuery({ name: 'withTxCount', description: 'Include transaction count', required: false, type: Boolean })
async getApplications(
@Query('from', new DefaultValuePipe(0), ParseIntPipe) from: number,
@Query("size", new DefaultValuePipe(25), ParseIntPipe) size: number,
@Query('before', ParseIntPipe) before?: number,
@Query('after', ParseIntPipe) after?: number,
): Promise<any[]> {
@Query('withTxCount', new ParseBoolPipe()) withTxCount?: boolean,
): Promise<Application[]> {
const applicationFilter = new ApplicationFilter({ before, after, withTxCount });
return await this.applicationService.getApplications(
new QueryPagination({ size, from }),
new ApplicationFilter({ before, after })
applicationFilter
);
}

Expand Down
4 changes: 4 additions & 0 deletions src/endpoints/applications/application.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,18 @@ import { Module } from "@nestjs/common";
import { ElasticIndexerModule } from "src/common/indexer/elastic/elastic.indexer.module";
import { ApplicationService } from "./application.service";
import { AssetsService } from '../../common/assets/assets.service';
import { GatewayService } from "src/common/gateway/gateway.service";
import { TransferModule } from "../transfers/transfer.module";

@Module({
imports: [
ElasticIndexerModule,
TransferModule,
],
providers: [
ApplicationService,
AssetsService,
GatewayService,
],
exports: [
ApplicationService,
Expand Down
58 changes: 57 additions & 1 deletion src/endpoints/applications/application.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,89 @@ import { Application } from './entities/application';
import { QueryPagination } from 'src/common/entities/query.pagination';
import { ApplicationFilter } from './entities/application.filter';
import { AssetsService } from '../../common/assets/assets.service';
import { GatewayService } from 'src/common/gateway/gateway.service';
import { TransferService } from '../transfers/transfer.service';
import { TransactionFilter } from '../transactions/entities/transaction.filter';
import { TransactionType } from '../transactions/entities/transaction.type';
import { Logger } from '@nestjs/common';
import { CacheService } from '@multiversx/sdk-nestjs-cache';
import { CacheInfo } from 'src/utils/cache.info';

@Injectable()
export class ApplicationService {
private readonly logger = new Logger(ApplicationService.name);

constructor(
private readonly elasticIndexerService: ElasticIndexerService,
private readonly assetsService: AssetsService,
private readonly gatewayService: GatewayService,
private readonly transferService: TransferService,
private readonly cacheService: CacheService,
) { }

async getApplications(pagination: QueryPagination, filter: ApplicationFilter): Promise<Application[]> {
filter.validate(pagination.size);

if (!filter.isSet) {
return await this.cacheService.getOrSet(
CacheInfo.Applications(pagination).key,
async () => await this.getApplicationsRaw(pagination, filter),
CacheInfo.Applications(pagination).ttl
);
}

return await this.getApplicationsRaw(pagination, filter);
}

async getApplicationsRaw(pagination: QueryPagination, filter: ApplicationFilter): Promise<Application[]> {
const elasticResults = await this.elasticIndexerService.getApplications(filter, pagination);
const assets = await this.assetsService.getAllAccountAssets();

if (!elasticResults) {
return [];
}

return elasticResults.map(item => ({
const applications = elasticResults.map(item => new Application({
contract: item.address,
deployer: item.deployer,
owner: item.currentOwner,
codeHash: item.initialCodeHash,
timestamp: item.timestamp,
assets: assets[item.address],
balance: '0',
...(filter.withTxCount && { txCount: 0 }),
}));

await Promise.all(applications.map(async (application) => {
const promises: Promise<void>[] = [];

promises.push((async () => {
try {
const { account: { balance } } = await this.gatewayService.getAddressDetails(application.contract);
Copy link
Contributor

Choose a reason for hiding this comment

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

optional: we could have used POST /address/bulk for fetching the state of more addresses

application.balance = balance;
} catch (error) {
this.logger.error(`Error when getting balance for contract ${application.contract}`, error);
application.balance = '0';
}
})());

if (filter.withTxCount) {
promises.push((async () => {
application.txCount = await this.getApplicationTxCount(application.contract);
})());
}

await Promise.all(promises);
}));

return applications;
}

async getApplicationsCount(filter: ApplicationFilter): Promise<number> {
return await this.elasticIndexerService.getApplicationCount(filter);
}

async getApplicationTxCount(address: string): Promise<number> {
return await this.transferService.getTransfersCount(new TransactionFilter({ address, type: TransactionType.Transaction }));
}
}
12 changes: 11 additions & 1 deletion src/endpoints/applications/entities/application.filter.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
import { BadRequestException } from "@nestjs/common";

export class ApplicationFilter {
constructor(init?: Partial<ApplicationFilter>) {
Object.assign(this, init);
}

after?: number;
before?: number;
withTxCount?: boolean;

validate(size: number) {
if (this.withTxCount && size > 25) {
throw new BadRequestException('Size must be less than or equal to 25 when withTxCount is set');
}
}

isSet(): boolean {
return this.after !== undefined ||
this.before !== undefined;
this.before !== undefined ||
this.withTxCount !== undefined;
}
}
6 changes: 6 additions & 0 deletions src/endpoints/applications/entities/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,10 @@ export class Application {

@ApiProperty({ type: AccountAssets, nullable: true, description: 'Contract assets' })
assets: AccountAssets | undefined = undefined;

@ApiProperty({ type: String })
balance: string = '0';

@ApiProperty({ type: Number, required: false })
txCount?: number;
}
110 changes: 107 additions & 3 deletions src/test/unit/services/applications.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@ import { ApplicationFilter } from 'src/endpoints/applications/entities/applicati
import { AssetsService } from '../../../common/assets/assets.service';
import { AccountAssetsSocial } from '../../../common/assets/entities/account.assets.social';
import { AccountAssets } from '../../../common/assets/entities/account.assets';
import { Application } from 'src/endpoints/applications/entities/application';
import { GatewayService } from 'src/common/gateway/gateway.service';
import { TransferService } from 'src/endpoints/transfers/transfer.service';
import { CacheService } from '@multiversx/sdk-nestjs-cache';
import { BadRequestException } from '@nestjs/common';

describe('ApplicationService', () => {
let service: ApplicationService;
let indexerService: ElasticIndexerService;
let assetsService: AssetsService;

let gatewayService: GatewayService;
let transferService: TransferService;
let cacheService: CacheService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
Expand All @@ -29,12 +36,33 @@ describe('ApplicationService', () => {
getAllAccountAssets: jest.fn(),
},
},
{
provide: GatewayService,
useValue: {
getAddressDetails: jest.fn(),
},
},
{
provide: TransferService,
useValue: {
getTransfersCount: jest.fn(),
},
},
{
provide: CacheService,
useValue: {
getOrSet: jest.fn(),
},
},
],
}).compile();

service = module.get<ApplicationService>(ApplicationService);
indexerService = module.get<ElasticIndexerService>(ElasticIndexerService);
assetsService = module.get<AssetsService>(AssetsService);
gatewayService = module.get<GatewayService>(GatewayService);
transferService = module.get<TransferService>(TransferService);
cacheService = module.get<CacheService>(CacheService);
});

it('should be defined', () => {
Expand Down Expand Up @@ -80,22 +108,37 @@ describe('ApplicationService', () => {

jest.spyOn(indexerService, 'getApplications').mockResolvedValue(indexResult);
jest.spyOn(assetsService, 'getAllAccountAssets').mockResolvedValue(assets);
jest.spyOn(gatewayService, 'getAddressDetails').mockResolvedValue({
account: {
address: '',
nonce: 0,
balance: '0',
username: '',
code: '',
codeHash: '',
rootHash: '',
codeMetadata: '',
developerReward: '',
ownerAddress: '',
},
});

const queryPagination = new QueryPagination();
const filter = new ApplicationFilter();
const result = await service.getApplications(queryPagination, filter);
const result = await service.getApplicationsRaw(queryPagination, filter);

expect(indexerService.getApplications).toHaveBeenCalledWith(filter, queryPagination);
expect(indexerService.getApplications).toHaveBeenCalledTimes(1);
expect(assetsService.getAllAccountAssets).toHaveBeenCalled();

const expectedApplications = indexResult.map(item => ({
const expectedApplications = indexResult.map(item => new Application({
contract: item.address,
deployer: item.deployer,
owner: item.currentOwner,
codeHash: item.initialCodeHash,
timestamp: item.timestamp,
assets: assets[item.address],
balance: '0',
}));

expect(result).toEqual(expectedApplications);
Expand All @@ -115,6 +158,67 @@ describe('ApplicationService', () => {

expect(result).toEqual([]);
});

it('should return an array of applications with tx count', async () => {
const indexResult = [
{
address: 'erd1qqqqqqqqqqqqqpgq8372f63glekg7zl22tmx7wzp4drql25r6avs70dmp0',
deployer: 'erd1j770k2n46wzfn5g63gjthhqemu9r23n9tp7seu95vpz5gk5s6avsk5aams',
currentOwner: 'erd1j770k2n46wzfn5g63gjthhqemu9r23n9tp7seu95vpz5gk5s6avsk5aams',
initialCodeHash: 'kDh8hR9vyceELMUuy6JdAg0X90+ZaLeyVQS6tPbY82s=',
timestamp: 1724955216,
},
];

jest.spyOn(indexerService, 'getApplications').mockResolvedValue(indexResult);
jest.spyOn(assetsService, 'getAllAccountAssets').mockResolvedValue({});
jest.spyOn(gatewayService, 'getAddressDetails').mockResolvedValue({
account: {
address: '',
nonce: 0,
balance: '0',
username: '',
code: '',
codeHash: '',
rootHash: '',
codeMetadata: '',
developerReward: '',
ownerAddress: '',
},
});
jest.spyOn(transferService, 'getTransfersCount').mockResolvedValue(42);

const queryPagination = new QueryPagination();
const filter = new ApplicationFilter({ withTxCount: true });
const result = await service.getApplicationsRaw(queryPagination, filter);

const expectedApplications = indexResult.map(item => new Application({
contract: item.address,
deployer: item.deployer,
owner: item.currentOwner,
codeHash: item.initialCodeHash,
timestamp: item.timestamp,
balance: '0',
txCount: 42,
}));

expect(result).toEqual(expectedApplications);
expect(transferService.getTransfersCount).toHaveBeenCalled();
});

it('should return an empty array of applications from cache', async () => {
const queryPagination = new QueryPagination();
const filter = new ApplicationFilter();
jest.spyOn(cacheService, 'getOrSet').mockResolvedValue([]);
const result = await service.getApplications(queryPagination, filter);
expect(result).toEqual([]);
});

it('should throw an error when size is greater than 25 and withTxCount is set', async () => {
const queryPagination = new QueryPagination({ size: 50 });
const filter = new ApplicationFilter({ withTxCount: true });
await expect(service.getApplications(queryPagination, filter)).rejects.toThrow(BadRequestException);
});
});

describe('getApplicationsCount', () => {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/cache.info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,7 @@ export class CacheInfo {
static Applications(queryPagination: QueryPagination): CacheInfo {
return {
key: `applications:${queryPagination.from}:${queryPagination.size}`,
ttl: Constants.oneHour(),
ttl: Constants.oneMinute(),
};
}

Expand Down