Skip to content

Commit

Permalink
Merge branch 'evm' of github.com:aura-nw/horoscope-v2 into refactor/d…
Browse files Browse the repository at this point in the history
…etect-proxy-api
  • Loading branch information
phamphong9981 committed Sep 10, 2024
2 parents d98a378 + d5744b0 commit f071678
Show file tree
Hide file tree
Showing 9 changed files with 175 additions and 77 deletions.
5 changes: 4 additions & 1 deletion ci/config.json.ci
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,10 @@
},
"dashboardStatistics": {
"millisecondCrawl": 10000,
"queryPageLimit": 100
"queryPageLimit": 100,
"currentInflation": 0.05,
"currentCommunityTax": 0,
"denomSupply": "stake"
},
"graphiqlApi": {
"hasuraRole": "internal_service",
Expand Down
5 changes: 4 additions & 1 deletion config.json
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,10 @@
},
"dashboardStatistics": {
"millisecondCrawl": 10000,
"queryPageLimit": 100
"queryPageLimit": 100,
"currentInflation": 0.05,
"currentCommunityTax": 0,
"denomSupply": "stake"
},
"feegrant": {
"updateFeegrant": {
Expand Down
13 changes: 9 additions & 4 deletions src/services/evm/erc721.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,15 @@ export default class Erc721Service extends BullableService {
tokenMedia.onchain.token_uri
);
} catch (error) {
this.logger.error(error);
await Erc721Token.query()
.where('id', tokenMedia.erc721_token_id)
.patch({
media_info: {
onchain: {
token_uri: tokenMedia.onchain.token_uri,
},
},
});
throw error;
}
}
Expand Down Expand Up @@ -484,9 +492,6 @@ export default class Erc721Service extends BullableService {
{},
{
removeOnComplete: true,
removeOnFail: {
count: 3,
},
repeat: {
every: config.erc721.millisecondRepeatJob,
},
Expand Down
19 changes: 15 additions & 4 deletions src/services/evm/erc721_media_handler.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
/* eslint-disable no-param-reassign */
import { fromBase64, fromUtf8 } from '@cosmjs/encoding';
import { AWSError } from 'aws-sdk';
import axios, { AxiosError } from 'axios';
import * as FileType from 'file-type';
import * as isIPFS from 'is-ipfs';
import parse from 'parse-uri';
import Moleculer from 'moleculer';
import parse from 'parse-uri';
import { Config } from '../../common';
import { S3Service } from '../../common/utils/s3';

const SUPPORT_DECODED_TOKEN_URI = {
BASE64: 'data:application/json;base64',
};
export interface ITokenMediaInfo {
erc721_token_id: number;
address: string;
Expand Down Expand Up @@ -168,7 +172,10 @@ export async function getMetadata(token_uri: string): Promise<{
image?: string;
animation_url?: string;
}> {
console.log(parseIPFSUri(token_uri));
if (token_uri.split(',')[0] === SUPPORT_DECODED_TOKEN_URI.BASE64) {
const base64Metadata = token_uri.split(',')[1];
return JSON.parse(fromUtf8(fromBase64(base64Metadata)));
}
const metadata = await downloadAttachment(parseIPFSUri(token_uri));
return JSON.parse(metadata.toString());
}
Expand All @@ -181,8 +188,9 @@ export async function downloadAttachment(url: string) {
maxContentLength: parseInt(MAX_CONTENT_LENGTH_BYTE, 10),
maxBodyLength: parseInt(MAX_BODY_LENGTH_BYTE, 10),
});

return axiosClient.get(url).then((response: any) => {
const fromGithub = url.includes('//github.com');
const formatedUrl = fromGithub ? `${url}?raw=true` : url;
return axiosClient.get(formatedUrl).then((response: any) => {
const buffer = Buffer.from(response.data, 'base64');
return buffer;
});
Expand All @@ -206,6 +214,9 @@ export function parseFilename(media_uri: string) {
}
return parsed.path.substring(1); // http://ipfs.io/ipfs/QmWov9DpE1vYZtTH7JLKXb7b8bJycN91rEPJEmXRXdmh2G/nerd_access_pass.gif
}
if (media_uri.includes('//github.com')) {
return parsed.path.substring(1); // https://github.com/storyprotocol/protocol-core/blob/main/assets/license-image.gif
}
}
if (media_uri.startsWith('/ipfs/')) {
return media_uri.substring(1); // /ipfs/QmPAGifcMvxDBgYr1XmEz9gZiC3DEkfYeinFdVSe364uQp/689.png
Expand Down
81 changes: 69 additions & 12 deletions src/services/evm/statistic/dashboard_statistics.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
/* eslint-disable import/no-extraneous-dependencies */
import { Service } from '@ourparentcenter/moleculer-decorators-extended';
import { ServiceBroker } from 'moleculer';
import BigNumber from 'bignumber.js';
import axios from 'axios';
import {
BlockCheckpoint,
DailyStatistics,
Expand All @@ -13,12 +15,19 @@ import {
import { BULL_JOB_NAME, REDIS_KEY, SERVICE } from '../constant';
import config from '../../../../config.json' assert { type: 'json' };
import BullableService, { QueueHandler } from '../../../base/bullable.service';
import networks from '../../../../network.json' assert { type: 'json' };

@Service({
name: SERVICE.V1.DashboardEVMStatisticsService.key,
version: 1,
})
export default class DashboardEVMStatisticsService extends BullableService {
private selectedChain: any = networks.find(
(network) => network.chainId === config.chainId
);

private _lcd = this.selectedChain.LCD[0];

public constructor(public broker: ServiceBroker) {
super(broker);
}
Expand Down Expand Up @@ -109,25 +118,41 @@ export default class DashboardEVMStatisticsService extends BullableService {
public async handleJob(_payload: object): Promise<void> {
this.logger.info('Update EVM dashboard statistics');

const [totalBlocks, totalTxs, avgBlockTime, latestDailyStat] =
await Promise.all([
BlockCheckpoint.query().findOne(
'job_name',
config.evmOnly
? BULL_JOB_NAME.CRAWL_EVM_TRANSACTION
: BULL_JOB_NAME.HANDLE_TRANSACTION_EVM
),
this.statisticTotalTransaction(),
this.avgBlockTime(),
DailyStatistics.query().orderBy('date', 'desc').first(),
]);
const [
totalBlocks,
totalTxs,
avgBlockTime,
latestDailyStat,
totalSupply,
bondedTokens,
] = await Promise.all([
BlockCheckpoint.query().findOne(
'job_name',
config.evmOnly
? BULL_JOB_NAME.CRAWL_EVM_TRANSACTION
: BULL_JOB_NAME.HANDLE_TRANSACTION_EVM
),
this.statisticTotalTransaction(),
this.avgBlockTime(),
DailyStatistics.query().orderBy('date', 'desc').first(),
this.getTotalSupplyByDenom(),
this.getBondedTokenInStakingPool(),
]);

const dashboardStatistics = {
total_blocks: totalBlocks?.height,
total_transactions: Number(totalTxs),
avg_block_time: avgBlockTime,
addresses: latestDailyStat ? latestDailyStat.unique_addresses : 0,
daily_transaction: latestDailyStat ? latestDailyStat.daily_txs : 0,
total_supply: totalSupply,
staking_apr: BigNumber(config.dashboardStatistics.currentInflation)
.multipliedBy(
BigNumber(1 - config.dashboardStatistics.currentCommunityTax)
)
.multipliedBy(BigNumber(totalSupply))
.dividedBy(bondedTokens)
.multipliedBy(100),
};

await this.broker.cacher?.set(
Expand All @@ -136,6 +161,38 @@ export default class DashboardEVMStatisticsService extends BullableService {
);
}

async getBondedTokenInStakingPool() {
if (!this._lcd) {
this.logger.error('Config network not have LCD');
return 0;
}
const resultCallApi = await axios({
baseURL: this._lcd,
url: 'staking/pool',
method: 'GET',
params: {
denom: config.dashboardStatistics.denomSupply,
},
});
return resultCallApi.data.msg.pool.bonded_tokens;
}

async getTotalSupplyByDenom() {
if (!this._lcd) {
this.logger.error('Config network not have LCD');
return 0;
}
const resultCallApi = await axios({
baseURL: this._lcd,
url: '/bank/supply/by_denom',
method: 'GET',
params: {
denom: config.dashboardStatistics.denomSupply,
},
});
return resultCallApi.data.msg.amount.amount;
}

public async _start() {
this.createJob(
BULL_JOB_NAME.HANDLE_DASHBOARD_EVM_STATISTICS,
Expand Down
Loading

0 comments on commit f071678

Please sign in to comment.