repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
srdejo/-adn-ceiba-front-comercio
src/app/core/components/navbar/navbar.component.ts
import { Component, OnInit, Input } from '@angular/core'; import { MenuItem } from '@core/modelo/menu-item'; import { Comercio } from '@shared/modelo/comercio'; import { ComercioService } from '@shared/service/comercio.service'; import { Observable } from 'rxjs'; @Component({ selector: 'app-navbar', templateUrl: 'navbar.component.html', styles: [], }) export class NavbarComponent implements OnInit { public listaComercios: Observable<Comercio[]>; public comercioSeleccionado: string; @Input() items: MenuItem[]; constructor(protected comercioService: ComercioService) { } ngOnInit() { this.comercioSeleccionado = 'Seleccione un comercio'; this.listaComercios = this.comercioService.consultar(); } seleccionarComercio(comercio: Comercio): void { this.comercioService.seleccionar(comercio); this.comercioSeleccionado = comercio.nombre; } }
srdejo/-adn-ceiba-front-comercio
src/app/feature/comercio/components/comercio/comercio.component.spec.ts
<filename>src/app/feature/comercio/components/comercio/comercio.component.spec.ts<gh_stars>1-10 import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComercioComponent } from './comercio.component'; describe('ComercioComponent', () => { let component: ComercioComponent; let fixture: ComponentFixture<ComercioComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ ComercioComponent ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(ComercioComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
srdejo/-adn-ceiba-front-comercio
src/app/shared/modelo/comercio.ts
<reponame>srdejo/-adn-ceiba-front-comercio export class Comercio { id: number; nombre: string; constructor(id: number, nombre: string) { this.id = id; this.nombre = nombre; } }
khassanboi/match-game
src/ts/UsersStore.ts
<reponame>khassanboi/match-game export interface User { id: string; firstName: string; lastName: string; email: string; score: number; avatar: string | null; } export default class UsersStore { // methods getAllUsers(): User[] { const users: User[] = []; this.operationWithDB("getUsers", undefined, (user) => { users.push(user); }); return users; } addUser(newUser: User): void { this.operationWithDB("addUser", newUser); } updateScore(currentUser: User): void { this.operationWithDB("updateScore", currentUser); } private operationWithDB = ( method: "getUsers" | "addUser" | "updateScore", user?: User, success?: (User) => void ): void => { let db = null; const req = indexedDB.open("khassanboi", 1); req.onupgradeneeded = async () => { db = await req.result; db.createObjectStore("usersData", { keyPath: "id" }); }; req.onsuccess = async () => { db = await req.result; const tx = method === "getUsers" ? db.transaction("usersData", "readonly") : db.transaction("usersData", "readwrite"); tx.onerror = (e) => alert(`There was an error: ${e.target.errorCode}`); const usersData = tx.objectStore("usersData"); if (method === "getUsers") { const creq = usersData.openCursor(); creq.onsuccess = (event) => { const cursor = creq.result || event.target.result; if (cursor) { const userCursor: User = cursor.value; success(userCursor); cursor.continue(); } }; } else if (method === "addUser") { usersData.add(user); } else if (method === "updateScore") { usersData.put(user); } }; req.onerror = () => { alert("ERROR"); }; }; }
khassanboi/match-game
src/ts/utils.ts
export function generateUserID(): string { return `user${Math.random().toString(36).substr(2, 9)}`; } export function imgToBlobConverter(img): { size: number; type: string } { const binaryData = []; binaryData.push(img); return new Blob(binaryData, { type: "image" }); } export function imgToBase64Converter(img, success): void { const reader = new FileReader(); reader.readAsDataURL(img); reader.onload = (): void => { success(reader.result); }; reader.onerror = (error) => { alert(`Error: ${error}`); }; } export function formValidator(input): void { const chars = "~!@#$%^&*()[]{}_-+=|:;\"'<>,.?/1234567890"; const emailChars = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i; if ( (input.getAttribute("type") === "text" && input.value.trim() && !chars.split("").some((ch) => input.value.includes(ch)) && input.value.length <= 30) || (input.getAttribute("type") === "email" && emailChars.test(input.value)) ) { // input is valid input.closest("label").classList.remove("invalid"); input.closest("label").classList.add("valid"); } else { // input is not valid input.closest("label").classList.remove("valid"); input.closest("label").classList.add("invalid"); } } export function initUI() { const currentUser = localStorage.getItem("currentUser"); if (currentUser == null) { document.querySelectorAll(".signed-in").forEach((item) => { (item as HTMLElement).style.display = "none"; }); (document.querySelector(".not-signed-in") as HTMLElement).style.display = "inline-block"; } else { document.querySelectorAll(".signed-in").forEach((item) => { (item as HTMLElement).style.display = "inline-block"; }); (document.querySelector(".not-signed-in") as HTMLElement).style.display = "none"; if (JSON.parse(currentUser).avatar) { document.getElementById("nav-avatar").style["background-image"] = `url(${ JSON.parse(currentUser).avatar })`; } } }
khassanboi/match-game
src/app.ts
<filename>src/app.ts<gh_stars>0 // importing import { generateUserID, imgToBase64Converter, imgToBlobConverter, formValidator, initUI, } from "./ts/utils"; import { setTemplate, renderPage } from "./ts/pages"; import UsersStore, { User } from "./ts/UsersStore"; import "./scss/style.scss"; // interfacess declare global { interface Window { timer: number; } } interface Turns { correct: number; incorrect: number; score: () => number; } interface Cards { turnedNumber: number; turnedList: NodeListOf<Element> | []; pairsNumber: number; } // when application has started it renders about page setTemplate(); renderPage("about"); let gridSize: number; // game operation and logic function startGame() { const userStore = new UsersStore(); const currentUser: User = JSON.parse(localStorage.getItem("currentUser")); let secondsSpent: number = 0; const cards: Cards = { turnedNumber: 0, turnedList: [], pairsNumber: (gridSize * gridSize) / 2, }; const turns: Turns = { correct: 0, incorrect: 0, score() { return (this.correct + this.incorrect - this.incorrect) * 100 - secondsSpent * 10 > 0 ? (this.correct + this.incorrect - this.incorrect) * 100 - secondsSpent * 10 : 0; }, }; function checkIfComplete() { if (cards.pairsNumber === turns.correct) { clearInterval(window.timer); currentUser.score += turns.score(); userStore.updateScore(currentUser); localStorage.setItem("currentUser", JSON.stringify(currentUser)); alert( `You have completed the game. Your score is: ${turns.score()} Would you like to go to ranking page?` ); document.getElementById("page-rank").click(); } } document.querySelectorAll(".game__card").forEach((card) => { card.addEventListener("click", () => { if (cards.turnedNumber < 2) { (cards.turnedList as Array<Node>).push(card); card.classList.add("turned"); cards.turnedNumber += 1; if ( cards.turnedNumber === 2 && (cards.turnedList[0] as HTMLElement).dataset.id !== (cards.turnedList[1] as HTMLElement).dataset.id ) { cards.turnedList.forEach((turnedCard) => { turnedCard.classList.add("incorrect"); }); setTimeout(() => { document .querySelectorAll(".game__card:not(.correct)") .forEach((incorrectCard) => { incorrectCard.classList.remove("turned"); }); cards.turnedList.forEach((everyCard) => { everyCard.classList.remove("incorrect"); }); cards.turnedNumber = 0; cards.turnedList = []; }, 1000); turns.incorrect += 1; } else if ( cards.turnedNumber === 2 && (cards.turnedList[0] as HTMLElement).dataset.id === (cards.turnedList[1] as HTMLElement).dataset.id ) { cards.turnedList.forEach((correctCard) => { correctCard.classList.add("correct"); }); cards.turnedNumber = 0; cards.turnedList = []; turns.correct += 1; setTimeout(() => { checkIfComplete(); }, 100); } } }); }); const startTime = Date.now(); window.timer = window.setInterval(() => { const delta = Date.now() - startTime; // milliseconds elapsed since start secondsSpent = Math.floor(delta / 1000); // alternatively just show wall clock time: (document.querySelector(".game__timer") as HTMLElement).innerText = `${ new Date(delta).getMinutes() < 10 ? "0" : "" }${new Date(delta).getMinutes()}:${ new Date(delta).getSeconds() < 10 ? "0" : "" }${new Date(delta).getSeconds()}`; }, 100); } // other page navigations document.querySelectorAll(".page-render").forEach((btn) => { initUI(); btn.addEventListener("click", (e) => { e.preventDefault(); const page = (btn as HTMLElement).dataset.value; if ( page === "about" || page === "ranking" || page === "settings" || page === "reg" ) { renderPage(page); if (window.timer) clearInterval(window.timer); } else if (page === "game") { gridSize = document.getElementById("difficulty") && (<HTMLInputElement>document.getElementById("difficulty")).value ? parseInt( (<HTMLInputElement>document.getElementById("difficulty")).value, 10 ) : 4; renderPage("game", { gridSize, cardType: document.getElementById("card-type") && (<HTMLInputElement>document.getElementById("card-type")).value ? (<HTMLInputElement>document.getElementById("card-type")).value : "animal", }); startGame(); } document.querySelectorAll(".navbar__item").forEach((nav) => { nav.classList.remove("active"); }); btn.closest("div").classList.add("active"); // window.clearInterval(window.timer); }); }); // registration document.getElementById("register").addEventListener("click", () => { renderPage("reg"); document.querySelectorAll(".reg__input").forEach((input) => { if (input.getAttribute("type") === "file") { input.addEventListener("change", () => { imgToBase64Converter(imgToBlobConverter((document.getElementById("avatar") as HTMLInputElement) .files[0]), (img) => { document.getElementById("avatar-image").style[ "background-image" ] = `url(${img})`; }); }); } else { ["change", "keydown"].forEach((evt) => { input.addEventListener(evt, () => { formValidator(input); let formIsValid = true; document .querySelectorAll(".reg__input:not(#avatar)") .forEach((inp) => { formIsValid = inp.parentElement.classList.contains("valid"); }); if (formIsValid) { document.getElementById("add-user").classList.remove("disabled"); } else { document.getElementById("add-user").classList.add("disabled"); } }); }); } }); document.getElementById("cancel-reg").addEventListener("click", () => { document .getElementById("app") .removeChild(document.getElementById("reg-window")); }); document.getElementById("add-user").addEventListener("click", () => { const usersStore = new UsersStore(); const users: User[] = usersStore.getAllUsers(); let avatar: string | null; if ( (document.getElementById("avatar") as HTMLInputElement).files.length !== 0 ) { imgToBase64Converter( imgToBlobConverter( (document.getElementById("avatar") as HTMLInputElement).files[0] ), (base64) => { avatar = base64.toString(); } ); } else { avatar = null; } setTimeout(() => { let newUser: User = { id: generateUserID(), firstName: (document.getElementById("first-name") as HTMLInputElement) .value, lastName: (document.getElementById("last-name") as HTMLInputElement) .value, email: (document.getElementById("email") as HTMLInputElement).value, score: 0, avatar, }; let emailExists: boolean = false; // Adding to IndexedDb if email doesn't exist if (users) { // looping through the data to check if there's any user with the same email users.forEach((user) => { if (user.email === newUser.email) { newUser = user; emailExists = true; } }); } if (!emailExists) { usersStore.addUser(newUser); } // Setting the current user localStorage.setItem("currentUser", JSON.stringify(newUser)); document .getElementById("app") .removeChild(document.getElementById("reg-window")); initUI(); }, 1000); }); }); document.getElementById("quit").addEventListener("click", () => { localStorage.removeItem("currentUser"); document.getElementById("page-about").click(); initUI(); });
khassanboi/match-game
src/ts/pages.ts
<filename>src/ts/pages.ts import UsersStore from "./UsersStore"; export function setTemplate() { document.getElementById("app").innerHTML = ` <header class="header"> <div class="header__item"> <div class="header__item--logo"> <span class="logo-top">Match</span> <span class="logo-bottom">Match</span> </div> </div> <nav class="navbar"> <div class="navbar__item active"> <a href="#" class="page-render" id="page-about" data-value="about"> <svg> <use xlink:href="${require("../fonts/symbol-defs.svg")}#i-about"></use> </svg> <h4>About Game</h4> </a> </div> <div class="navbar__item"> <a href="#" class="page-render" id="page-rank" data-value="ranking"> <svg> <use xlink:href="${require("../fonts/symbol-defs.svg")}#i-star"></use> </svg> <h4>Best Score</h4> </a> </div> <div class="navbar__item"> <a href="#" class="page-render" data-value="settings"> <svg> <use xlink:href="${require("../fonts/symbol-defs.svg")}#i-settings"></use> </svg> <h4>Game Settings</h4> </a> </div> </nav> <div class="header__item"> <a href="#" class="btn btn--ghost page-render not-signed-in" data-value="registration" id="register">Register New Player</a> <a href="#" class="btn btn--ghost page-render signed-in" data-value="game" id="start">Start Game</a> <a href="#" class="btn btn--ghost signed-in" id="quit">Quit</a> <div class="profile-avatar signed-in"> <div id="nav-avatar"></div> </div> </div> </header> <main id="main"></main> `; } export async function renderPage( page: "about" | "ranking" | "settings" | "game" | "reg", gameSettings?: { gridSize: number; cardType: string } ): Promise<void> { if (page === "about") { document.getElementById("main").innerHTML = ` <main class="instr"> <h1 class="h1">How to play?</h1> <section class="instr__item"> <div class="instr__content"> <span class="instr__number">1</span> <p class="instr__text">Register new player in game</p> </div> <img src=${require("../img/instr-1.png")} class="instr__img"></img> </section> <section class="instr__item"> <div class="instr__content"> <span class="instr__number">2</span> <p class="instr__text">Configure your game settings</p> </div> <img src=${require("../img/instr-2.png")} class="instr__img"></img> </section> <section class="instr__item"> <div class="instr__content"> <span class="instr__number">3</span> <p class="instr__text">Start your new game!</p> </div> <img src=${require("../img/instr-3.png")} class="instr__img"></img> </section> </main> `; } else if (page === "ranking") { const users = await new UsersStore().getAllUsers(); document.getElementById("main").innerHTML = ` <main class="rank"> <div class="rank__container"> <h1 class="h1">Best Players</h1> <ul class="rank__list" id="rank-list"></ul> </div> </main> `; setTimeout(() => { users .sort((x, y) => y.score - x.score) .forEach((user) => { document.getElementById("rank-list").innerHTML += ` <li class="rank__item"> <div class="rank__item-container"> <div id="rank-avatar" style="background-image: url(${ user.avatar ? user.avatar : require("../img/profile.png") })" alt="User 1"></div> <div class="rank__item-details"> <h3>${user.firstName} ${user.lastName}</h3> <p>${user.email}</p> </div> </div> <h3 class="rank__item-score">Score: <span>${user.score}</span></h3> </li>`; }); }, 100); } else if (page === "settings") { document.getElementById("main").innerHTML = ` <main class="settings"> <div class="settings__container"> <label class="h1" for="card-type">Game Cards</label> <select name="card-type" id="card-type" class="settings__input"> <option value="" selected>select game cards type</option> <option value="animal">Animals</option> <option value="flag">Flags</option> </select> <label class="h1" for="difficulty">Difficulty</label> <select name="difficulty" id="difficulty" class="settings__input"> <option value="" selected>select game type</option> <option value="4">4x4</option> <option value="6">6x6</option> <option value="8">8x8</option> </select> </div> </main> `; } else if (page === "game") { const gameModeSetup = () => { const cardIndexes: number[] = []; if (gameSettings.gridSize === 4) { for (let i = 1; i <= 8; i += 1) { cardIndexes.push(i, i); } } else if (gameSettings.gridSize === 6) { for (let i = 1; i <= 9; i += 1) { cardIndexes.push(i, i, i, i); } } else if (gameSettings.gridSize === 8) { for (let i = 1; i <= 8; i += 1) { cardIndexes.push(i, i, i, i, i, i, i, i); } } return cardIndexes.sort(() => 0.5 - Math.random()); }; document.getElementById("main").innerHTML = ` <main class="game"> <div class="game__container"> <div class="game__timer">00:00</div> <div class="game__cards" id="game-cards"></div> </div> </main> `; document.getElementById("game-cards").setAttribute( "style", ` grid-template-columns: repeat(${gameSettings.gridSize}, 15%); grid-template-rows: repeat(${gameSettings.gridSize}, 15%); ` ); gameModeSetup().forEach((i) => { document.getElementById("game-cards").innerHTML += ` <div class="game__card" data-id="photo${i}"> <div class="game__card--front"> <img src=${require("../img/mask.png")} alt="Mask"> </div> <div class="game__card--back"> <img src=${require(`../img/card-images/${gameSettings.cardType}-${i}.jpg`)} alt="Mask"> </div> </div> `; }); } else if (page === "reg") { document.getElementById("app").insertAdjacentHTML( "beforeend", ` <section class="reg" id="reg-window"> <!-- add "active" class-name to make it visible --> <div class="reg__window"> <h1 class="h1">Register new Player</h1> <div class="reg__form"> <div class="reg__form--main" action="#"> <label for="first-name" class="reg__label"> First Name <input type="text" id="first-name" name="first-name" class="reg__input"> <svg class="visible"> <use xlink:href="${require("../fonts/symbol-defs.svg")}#i-tick"></use> </svg> </label> <label for="last-name" class="reg__label"> Last Name <input type="text" id="last-name" name="last-name" class="reg__input"> <svg class="visible"> <use xlink:href="${require("../fonts/symbol-defs.svg")}#i-tick"></use> </svg> </label> <label for="email" class="reg__label"> E-mail <input type="email" id="email" name="email" class="reg__input"> <svg class="visible"> <use xlink:href="${require("../fonts/symbol-defs.svg")}#i-tick"></use> </svg> </label> </div> <div class="reg__form--avatar"> <label for="avatar"> <input type="file" id="avatar" class="reg__input" accept="image/png, image/jpg, image/jpeg"> <div id="avatar-image"></div> </label> </div> <div class="reg__buttons"> <a href="#" class="btn btn--dark disabled" id="add-user">Add User</a> <a href="#" class="btn btn--light" id="cancel-reg">Cancel</a> </div> </div> </div> </section> ` ); } }
bianjieai/iobscan-ibc-explorer-backend
src/service/task.dispatch.service.ts
import { Injectable } from '@nestjs/common'; import { Model } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { ITaskDispatch, ITaskDispatchStruct } from '../types/schemaTypes/task.dispatch.interface'; import { getIpAddress, getTimestamp } from '../util/util'; import { TaskEnum } from '../constant'; import { cfg } from '../config/config'; import { Logger } from '../logger'; import { IRandomKey } from '../types'; import { DispatchFaultTolerance } from '../types/task.interface'; @Injectable() export class TaskDispatchService { constructor(@InjectModel('TaskDispatch') private taskDispatchModel: Model<ITaskDispatch>) { this.updateHeartbeatUpdateTime = this.updateHeartbeatUpdateTime.bind(this); } async needDoTask(name: TaskEnum): Promise<boolean> { const task: ITaskDispatchStruct | null = await (this.taskDispatchModel as any).findOneByName(name); if (task) { if (task.is_locked) { Logger.log(`${name}: previous task is executing, the next should not be executed!`); return false; } else { const updated: boolean = await this.lock(name); if (updated) { return true; } else { return false; } } } else { //it should be register if there is no this type of task; const registered = await this.registerTask(name); Logger.log(`${name}: register successfully? ${registered}`); if (registered) { const updated: boolean = await this.lock(name); if (updated) { return true; } else { return false; } } else { Logger.warn(`${name}: task has not been registered, but it couldn't register successfully!`); return false; } } } async registerTask(name: TaskEnum): Promise<ITaskDispatchStruct | null> { const task: ITaskDispatchStruct = { name, is_locked: false, device_ip: getIpAddress(), create_time: getTimestamp(), task_begin_time: 0, task_end_time: 0, heartbeat_update_time: getTimestamp(), }; return await (this.taskDispatchModel as any).createOne(task); } private async lock(name: TaskEnum): Promise<boolean> { return await (this.taskDispatchModel as any).lock(name); } async unlock(name: TaskEnum, randomKey?: IRandomKey): Promise<boolean> { return await (this.taskDispatchModel as any).unlock(name, randomKey); } async taskDispatchFaultTolerance(cb: DispatchFaultTolerance): Promise<void> { const taskList: ITaskDispatchStruct[] = await (this.taskDispatchModel as any).findAllLocked(); if (taskList && taskList.length > 0) { for(let task of taskList){ //对比当前时间跟上次心跳更新时间的差值与 心率, 当大于两个心率周期的时候, 认为上一个执行task的实例发生故障 if ((getTimestamp() - task.heartbeat_update_time) >= (cfg.taskCfg.interval.heartbeatRate * 2)/1000) { Logger.error(`${(task as any).name}: task executed breakdown, and reed to be released the lock`); await this.releaseLockByName((task as any).name); //出故障后, 释放锁, 也需要将出故障的timer清除; cb((task as any).name); } } } } private async releaseLockByName(name: TaskEnum): Promise<ITaskDispatchStruct | null> { return await (this.taskDispatchModel as any).releaseLockByName(name); } public async updateHeartbeatUpdateTime(name: TaskEnum, randomKey?: IRandomKey): Promise<void> { await (this.taskDispatchModel as any).updateHeartbeatUpdateTime(name, randomKey); } public async deleteOneByName(name: TaskEnum): Promise<void> { await (this.taskDispatchModel as any).deleteOneByName(name); } }
bianjieai/iobscan-ibc-explorer-backend
src/module/ibc_statistics.task.module.ts
import { Module } from '@nestjs/common'; import { IbcStatisticsTaskService } from '../task/ibc_statistics.task.service'; @Module({ providers: [IbcStatisticsTaskService], exports: [IbcStatisticsTaskService], }) export class IbcStatisticsTaskModule {}
bianjieai/iobscan-ibc-explorer-backend
src/task/ibc_sync_transfer_tx_task.service.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend<filename>src/task/ibc_sync_transfer_tx_task.service.ts<gh_stars>1-10 import {Injectable} from '@nestjs/common'; import {TaskEnum} from "../constant"; import {IbcTxHandler} from "../util/IbcTxHandler"; import {dateNow} from "../helper/date.helper"; import {TransferTaskStatusMetric} from "../monitor/metrics/ibc_transfer_task_status.metric"; @Injectable() export class IbcSyncTransferTxTaskService { constructor(private readonly taskCommonService: IbcTxHandler,private readonly transferTaskStatusMetric: TransferTaskStatusMetric) { this.doTask = this.doTask.bind(this); } async doTask(taskName?: TaskEnum): Promise<void> { this.transferTaskStatusMetric.collect(1) const ibcTxLatestModel = this.taskCommonService.getIbcTxLatestModel() await this.taskCommonService.parseIbcTx(ibcTxLatestModel,dateNow) } }
bianjieai/iobscan-ibc-explorer-backend
src/types/schemaTypes/ibc_base_denom.interface.ts
export interface IbcBaseDenomType { chain_id: string; denom: string; symbol: string; scale: number; icon: string; is_main_token: boolean; ibc_info_hash_caculate?: string; create_at: string; update_at: string; } export class IbcBaseDenomDto { readonly chain_id: string; readonly denom: string; readonly symbol: string; readonly scale: number; readonly icon: string; readonly is_main_token: boolean; readonly create_at: string; readonly update_at: string; }
bianjieai/iobscan-ibc-explorer-backend
src/monitor/metrics/ibc_chain_lcd_connection.metric.ts
<gh_stars>1-10 import {InjectMetric, makeGaugeProvider} from "@willsoto/nestjs-prometheus"; import {Gauge} from "prom-client"; import {Injectable} from "@nestjs/common"; @Injectable() export class LcdConnectionMetric { constructor(@InjectMetric("ibc_explorer_backend_lcd_connection_status") public gauge: Gauge<string>) {} async collect(chainId,value) { this.gauge.set({ "chain_id":chainId, },value) } } export function LcdConnectionProvider() { return makeGaugeProvider({ name: "ibc_explorer_backend_lcd_connection_status", help: "ibc explorer backend lcd connection status (1:Reachable 0:NotReachable)", labelNames: ['chain_id'], }) }
bianjieai/iobscan-ibc-explorer-backend
src/schema/sync.task.schema.ts
import * as mongoose from 'mongoose'; export const SyncTaskSchema = new mongoose.Schema({ start_height: Number, end_height: Number, current_height: Number, status: String, worker_id: String, worker_logs: Object, last_update_time: Number, }); SyncTaskSchema.statics = { async queryTaskCount(end_height: number = 0, status: string = 'underway') { return this.find({ end_height: end_height, status: status, }).countDocuments(); }, };
bianjieai/iobscan-ibc-explorer-backend
src/helper/denom.helper.ts
<gh_stars>1-10 import sha256 from 'sha256'; export function getDcDenom(msg) { let result = ''; let dc_denom_path = ''; const { source_port, source_channel, destination_port, destination_channel, data, } = msg.msg.packet; const dc_denom = data.denom; const prefix_sc = `${source_port}/${source_channel}/`; const prefix_dc = `${destination_port}/${destination_channel}/`; if (dc_denom.startsWith(prefix_sc)) { let dc_denom_clear_prefix = dc_denom.replace(prefix_sc, ''); if (dc_denom_clear_prefix.indexOf('/') === -1) { result = dc_denom_clear_prefix; dc_denom_path = dc_denom_clear_prefix; } else { result = `ibc/${sha256(dc_denom_clear_prefix).toUpperCase()}`; dc_denom_path = dc_denom_clear_prefix; } } else { result = `ibc/${sha256(`${prefix_dc}${dc_denom}`).toUpperCase()}`; dc_denom_path = `${prefix_dc}${dc_denom}`; } return { dc_denom: result, dc_denom_path: dc_denom_path }; } export function IbcDenom(denomPath :string, baseDenom :string) { if (!denomPath) { return baseDenom } return `ibc/${sha256(denomPath+'/'+baseDenom).toUpperCase()}` }
bianjieai/iobscan-ibc-explorer-backend
src/task/ibc_update_processing_tx_task.service.ts
import {Injectable} from '@nestjs/common'; import {TaskEnum} from "../constant"; import {IbcTxHandler} from "../util/IbcTxHandler"; import {dateNow} from "../helper/date.helper"; @Injectable() export class IbcUpdateProcessingTxTaskService { constructor(private readonly taskCommonService: IbcTxHandler) { this.doTask = this.doTask.bind(this); } async doTask(taskName?: TaskEnum): Promise<void> { const defaultSubstate = 0 const ibcTxLatestModel = this.taskCommonService.getIbcTxLatestModel() await this.taskCommonService.changeIbcTxState(ibcTxLatestModel, dateNow,[defaultSubstate],false,[]) } }
bianjieai/iobscan-ibc-explorer-backend
src/task/ibc_tx_data_update_task.service.test.ts
<gh_stars>1-10 import {IbcTxDataUpdateTaskService} from "./ibc_tx_data_update_task.service"; import {Test} from "@nestjs/testing"; import {AppModule} from "../app.module"; describe('IbcTxLatestMigrateTaskService', () => { let ibcTxDataUpdateTaskService: IbcTxDataUpdateTaskService; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [ AppModule ] }).compile(); ibcTxDataUpdateTaskService = module.get<IbcTxDataUpdateTaskService>(IbcTxDataUpdateTaskService); }) describe('handleUpdateIbcTx', () => { it('handleUpdateIbcTx', async () => { jest.setTimeout(100000000) await ibcTxDataUpdateTaskService.handleUpdateIbcTx() // console.log(ibcTxTaskService,'----') }); }); })
bianjieai/iobscan-ibc-explorer-backend
src/main.ts
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; import * as express from 'express'; import mongoose from 'mongoose'; import { LoggerMiddleware } from './middleware/logger.middleware'; import { LoggerInterceptor } from './interceptor/logger.interceptor'; mongoose.set('useFindAndModify', false) async function bootstrap() { const app = await NestFactory.create(AppModule); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.enableCors(); app.use(LoggerMiddleware); app.useGlobalInterceptors(new LoggerInterceptor()); setUpSwagger(app); await app.listen(3000); } function setUpSwagger(app: any){ const options = new DocumentBuilder() .setTitle('ibc-explorer') .setDescription('跨链浏览器接口列表') .setVersion('0.0.1') .build(); const document = SwaggerModule.createDocument(app, options); SwaggerModule.setup('api', app, document); } bootstrap();
bianjieai/iobscan-ibc-explorer-backend
src/dto/ibc_statistics.dto.ts
import { BaseResDto } from './base.dto' export class IbcStatisticsResDto extends BaseResDto { statistics_name: string; count: string; constructor(value) { super() const { statistics_name, count } = value; this.statistics_name = statistics_name; this.count = count; } static bundleData(value: any): IbcStatisticsResDto[] { const datas: IbcStatisticsResDto[] = value.map((item: any) => { return new IbcStatisticsResDto(item); }); return datas; } }
bianjieai/iobscan-ibc-explorer-backend
src/controller/ibc_tx.controller.ts
import { Controller, Get, Query,Param } from '@nestjs/common'; import { ApiTags } from '@nestjs/swagger'; import { IbcTxService } from '../service/ibc_tx.service'; import {IbcTxDetailsResDto, IbcTxListReqDto, IbcTxResDto, TxWithHashReqDto} from '../dto/ibc_tx.dto'; import { ListStruct, Result } from '../api/ApiResult'; @ApiTags('IbcTxs') @Controller('ibc') export class IbcTxController { constructor(private readonly ibcTxService: IbcTxService) {} @Get('txs') async getRecordList( @Query() query: IbcTxListReqDto, ): Promise<Result<ListStruct<IbcTxResDto[]> | number>> { const result: ListStruct<IbcTxResDto[]> | number = await this.ibcTxService.queryIbcTxList(query); return new Result<ListStruct<IbcTxResDto[]> | number>(result); } @Get("txs/:hash") async getTxDetailsByHash(@Param() query: TxWithHashReqDto):Promise<Result<IbcTxDetailsResDto[]>>{ const data:IbcTxDetailsResDto[] = await this.ibcTxService.queryIbcTxDetailsByHash(query) return new Result(data) } }
bianjieai/iobscan-ibc-explorer-backend
src/types/schemaTypes/config.interface.ts
export interface ConfigType { iobscan: string; }
bianjieai/iobscan-ibc-explorer-backend
src/types/schemaTypes/ibc_chain_config.interface.ts
export interface IbcChainConfigType { chain_id: string; icon: string; chain_name: string; lcd: string; lcd_api_path: { channels_path: string;client_state_path: string;}; ibc_info?: any; ibc_info_hash_lcd?: string; // ibc_info_hash_caculate?: string; is_manual?: boolean }
bianjieai/iobscan-ibc-explorer-backend
src/monitor/ibc_monitor.service.test.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend<filename>src/monitor/ibc_monitor.service.test.ts<gh_stars>1-10 import {IbcMonitorService} from "../monitor/ibc_monitor.service"; import {Test} from "@nestjs/testing"; import {AppModule} from "../app.module"; describe('IbcMonitorService', () => { let ibcMonitorService: IbcMonitorService; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [ AppModule ] }).compile(); ibcMonitorService = module.get<IbcMonitorService>(IbcMonitorService); }) describe('getProcessingCnt', () => { it('getProcessingCnt Test', async () => { const result = await ibcMonitorService.getProcessingCnt() console.log(result, '----') }); }); describe('getNodeInfo', () => { it('getNodeInfo Test', async () => { const result = await ibcMonitorService.getNodeInfo("https://cosmoshub.stakesystems.io/","cosmoshub_4") console.log(result, '----') }); }); })
bianjieai/iobscan-ibc-explorer-backend
src/controller/ibc_denom.controller.ts
import {Body, Controller, Headers, Get, Post, Put} from '@nestjs/common'; import { ApiTags } from '@nestjs/swagger'; import { Result } from '../api/ApiResult'; import { IbcDenomService } from '../service/ibc_denom.service'; import { IbcDenomResDto } from '../dto/ibc_denom.dto'; import { IbcDenomDto } from '../types/schemaTypes/ibc_denom.interface'; import {cfg} from '../config/config'; @ApiTags('IbcDenoms') @Controller('ibc') export class IbcDenomController { constructor(private readonly ibcDenomService: IbcDenomService) {} @Get('denoms') async getAllRecord(): Promise<Result<IbcDenomResDto[]>> { const result: IbcDenomResDto[] = await this.ibcDenomService.findAllRecord(); return new Result<IbcDenomResDto[]>(result); } @Put("denoms") async updateIbcDenom(@Body() dto:IbcDenomDto, @Headers() Headers):Promise<any> { const {executekey} = Headers if (executekey !== cfg.serverCfg.executeKey || !executekey) { return {"message":"deny this operation for executekey is not right."} } return await this.ibcDenomService.updateIbcDenom(dto) } }
bianjieai/iobscan-ibc-explorer-backend
src/service/ibc_denom.service.test.ts
import {IbcDenomService} from "./ibc_denom.service"; import {Test} from "@nestjs/testing"; import {AppModule} from "../app.module"; describe('IbcDenomService', () => { let ibcDenomService: IbcDenomService; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [ AppModule ] }).compile(); ibcDenomService = module.get<IbcDenomService>(IbcDenomService); }) describe('findAllRecord', () => { it('findAllRecord Test', async () => { const result = await ibcDenomService.findAllRecord() console.log(result, '----') }); }); describe('updateIbcDenom', () => { it('updateIbcDenom Test', async () => { const result = await ibcDenomService.updateIbcDenom({ chain_id:"microtick_1", denom:"ibc/5F78C42BCC76287AE6B3185C6C1455DFFF8D805B1847F94B9B625384B93885C7", symbol:"ATOM" }) console.log(result, '----') }); }); })
bianjieai/iobscan-ibc-explorer-backend
src/service/ibc_tx.service.test.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend import {IbcTxService} from "./ibc_tx.service"; import {Test} from "@nestjs/testing"; import {AppModule} from "../app.module"; import {IbcTxListReqDto} from "../dto/ibc_tx.dto"; import {IbcTxQueryType} from "../types/schemaTypes/ibc_tx.interface"; describe('IbcTxService', () => { let ibcTxService: IbcTxService; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [ AppModule ] }).compile(); ibcTxService = module.get<IbcTxService>(IbcTxService); }) describe('queryIbcTxList', () => { it('queryIbcTxList Test', async () => { jest.setTimeout(100000000) const query: IbcTxListReqDto = { page_num: 1, page_size: 10,use_count:false, status:"1,2,3,4", date_range:"0,1642495903", symbol:'Others', // chain_id:'cosmoshub_4', }; const time1 = Math.floor(new Date().getTime()/1000) const result = await ibcTxService.queryIbcTxList(query) console.log("time cost====>:",Math.floor(new Date().getTime()/1000) - time1) console.log('====count==>>:',result) }); }); describe('getTokenBySymbol', () => { it('getTokenBySymbol Test', async () => { const symbol = "osmo" // const symbol = unAuth const result = await ibcTxService.getTokenBySymbol(symbol) console.log(result, '----') }); }); describe('getBaseDenomMap', () => { it('getBaseDenomMap Test', async () => { const result = await ibcTxService.getBaseDenomMap() console.log(result, '----') }); }); describe('getStartTxTime', () => { it('getStartTxTime Test', async () => { const result = await ibcTxService.getStartTxTime() console.log(result, '----') }); }); describe('getTxCount', () => { it('getTxCount Test', async () => { const query: IbcTxListReqDto = {status: "1", chain_id: "osmosis_1"}; const token = await ibcTxService.getTokenBySymbol("osmo") const date_range = query.date_range?.split(","),status = query.status?.split(",") let queryData :IbcTxQueryType = { useCount: query.use_count, // date_range?: number[]; chain_id: query.chain_id, // status?: number[]; // token?: { denom: string; chain_id: string }[]; page_num:1, page_size: 10, } for (const one of date_range) { queryData?.date_range.push(Number(one)) } for (const one of status) { queryData?.status.push(Number(one)) } const result = await ibcTxService.getTxCount(queryData, token) console.log(result, '----') }); }); describe('getIbcTxs', () => { it('getIbcTxs Test', async () => { const query: IbcTxListReqDto = {status: "1", page_num: 1, page_size: 10, chain_id: "osmosis_1"}; const token = await ibcTxService.getTokenBySymbol("osmo") const date_range = query.date_range?.split(","),status = query.status?.split(",") let queryData :IbcTxQueryType = { useCount: query.use_count, // date_range?: number[]; chain_id: query.chain_id, // status?: number[]; // token?: { denom: string; chain_id: string }[]; page_num:1, page_size: 10, } for (const one of date_range) { queryData?.date_range.push(Number(one)) } for (const one of status) { queryData?.status.push(Number(one)) } const result = await ibcTxService.getIbcTxs(queryData, token) console.log(result, '----') }); }); describe('findStatisticTxsCount', () => { it('findStatisticTxsCount Test', async () => { const result = await ibcTxService.findStatisticTxsCount() console.log(result, '----') }); }); describe('getConnectByTransferEventNews', () => { it('getConnectByTransferEventNews Test', async () => { const eventNews = { events_new: [ { "msg_index":0, "events":[ { "type":"coin_received", "attributes":[ { "key":"receiver", "value":"<KEY>" }, { "key":"amount", "value":"965326boot" } ] }, { "type":"coin_spent", "attributes":[ { "key":"spender", "value":"<KEY>" }, { "key":"amount", "value":"965326boot" } ] }, { "type":"ibc_transfer", "attributes":[ { "key":"sender", "value":"<KEY>" }, { "key":"receiver", "value":"osmo1et80vz76fn5w946z864cg9j8yuwp298gnz5yz0" } ] }, { "type":"message", "attributes":[ { "key":"action", "value":"/ibc.applications.transfer.v1.MsgTransfer" }, { "key":"sender", "value":"bostrom1et80vz76fn5w946z864cg9j8yuwp298gc2n826" }, { "key":"module", "value":"ibc_channel" }, { "key":"module", "value":"transfer" } ] }, { "type":"send_packet", "attributes":[ { "key":"packet_data", "value":"{\"amount\":\"965326\",\"denom\":\"boot\",\"receiver\":\"osmo1et80vz76fn5w946z864cg9j8yuwp298gnz5yz0\",\"sender\":\"bostrom1et80vz76fn5w946z864cg9j8yuwp298gc2n826\"}" }, { "key":"packet_data_hex", "value":"7b22616d6f756e74223a22393635333236222c2264656e6f6d223a22626f6f74222c227265636569766572223a226f736d6f3165743830767a3736666e35773934367a3836346367396a3879757770323938676e7a35797a30222c2273656e646572223a22626f7374726f6d3165743830767a3736666e35773934367a3836346367396a38797577703239386763326e383236227d" }, { "key":"packet_timeout_height", "value":"1-2608471" }, { "key":"packet_timeout_timestamp", "value":"0" }, { "key":"packet_sequence", "value":"2114" }, { "key":"packet_src_port", "value":"transfer" }, { "key":"packet_src_channel", "value":"channel-2" }, { "key":"packet_dst_port", "value":"transfer" }, { "key":"packet_dst_channel", "value":"channel-95" }, { "key":"packet_channel_ordering", "value":"ORDER_UNORDERED" }, { "key":"packet_connection", "value":"connection-2" } ] }, { "type":"transfer", "attributes":[ { "key":"recipient", "value":"<KEY>" }, { "key":"sender", "value":"<KEY>" }, { "key":"amount", "value":"965326boot" } ] } ] } ] }; const result = await ibcTxService.getConnectByTransferEventNews(eventNews,1) console.log(result, '----') }); }); describe('queryIbcTxDetailsByHash', () => { it('queryIbcTxDetailsByHash Test', async () => { const result = await ibcTxService.queryIbcTxDetailsByHash({hash:'A7B69456C9C34B477FA021D6781F8F95A704BEC001532AF5D833354961573C98'}) console.log(result, '----') }); it('getIbcTxDetail Test', async () => { const result = await ibcTxService.getIbcTxDetail({hash:'A7B69456C9C34B477FA021D6781F8F95A704BEC001532AF5D833354961573C98'}) // console.log(result, '----') console.log(result.length, '----') }); it('getScTxInfo Test', async () => { const result = await ibcTxService.getScTxInfo("qa_iris_snapshot","A7B69456C9C34B477FA021D6781F8F95A704BEC001532AF5D833354961573C98","transferchannel-1transferchannel-541") console.log(result, '----') }); it('getDcTxInfo Test', async () => { const result = await ibcTxService.getDcTxInfo("cosmoshub_4","E3DFBCF3A15BF971C9C97CBCEBBD81C610B028CE18F285FDC3175A2968CFA2AB","transferchannel-12transferchannel-1823433") console.log(result, '----') }); }); })
bianjieai/iobscan-ibc-explorer-backend
src/schema/ibc_denom.schema.ts
<gh_stars>1-10 /* eslint-disable @typescript-eslint/camelcase */ import * as mongoose from 'mongoose'; import { IbcDenomType } from '../types/schemaTypes/ibc_denom.interface'; import {Logger} from "../logger"; import {AggregateBaseDenomCnt} from "../types/schemaTypes/ibc_denom.interface"; export const IbcDenomSchema = new mongoose.Schema( { chain_id: String, denom: String, base_denom: String, denom_path: String, is_source_chain: Boolean, is_base_denom: Boolean, symbol: { type: String, default: '', }, create_at: { type: Number, default: Math.floor(new Date().getTime() / 1000), }, update_at: { type: Number, default: Math.floor(new Date().getTime() / 1000), }, }, {versionKey: false}, ); IbcDenomSchema.index({chain_id: 1, denom: 1}, {unique: true}); IbcDenomSchema.index({symbol: -1}, {background: true}); IbcDenomSchema.statics = { async findAllRecord(): Promise<IbcDenomType[]> { return this.find({}); }, async findRecordBySymbol(symbol: string): Promise<IbcDenomType[]> { //todo this should limit for large data return this.find({symbol}); }, async findUnAuthDenom(page_num,page_size) : Promise<IbcDenomType[]> { return this.find({ // chain_id:chain_id, symbol:'', }, {_id: 0}).skip((Number(page_num) - 1) * Number(page_size)) .limit(Number(page_size)); }, async findCount(): Promise<number> { return this.count({}); }, async findBaseDenomCount(): Promise<Array<AggregateBaseDenomCnt>> { // return this.count({ // is_base_denom: true, // }); return this.aggregate([ { $match: { is_base_denom: true, } }, { $group: { _id: {base_denom: "$base_denom", chain_id: "$chain_id"} } }]); }, async findDenomRecord(chain_id, denom): Promise<IbcDenomType> { return this.findOne({chain_id, denom}, {_id: 0}); }, async findAllDenomRecord(chain_id): Promise<IbcDenomType> { return this.find({chain_id}, {_id: 0}); }, // async findAllDenomRecord(): Promise<IbcDenomType> { // return this.findOne({}); // }, async updateDenomRecord(denomRecord): Promise<void> { const {chain_id, denom} = denomRecord; const options = {upsert: true, new: false, setDefaultsOnInsert: true}; return this.findOneAndUpdate({ chain_id, denom }, denomRecord, options); }, async insertManyDenom(ibcDenom): Promise<void> { return this.insertMany(ibcDenom, { ordered: false },(error) => { if(JSON.stringify(error).includes('E11000 duplicate key error collection')){ }else { Logger.error(error) } }); }, };
bianjieai/iobscan-ibc-explorer-backend
src/module/ibc_base_denom.module.ts
import { Module } from '@nestjs/common'; import { IbcBaseDenomController } from '../controller/ibc_base_denom.controller'; import { IbcBaseDenomService } from '../service/ibc_base_denom.service'; @Module({ providers: [IbcBaseDenomService], controllers: [IbcBaseDenomController], }) export class IbcBaseDenomModule {}
bianjieai/iobscan-ibc-explorer-backend
src/service/task.dispatch.service.test.ts
<gh_stars>1-10 import {TaskDispatchService} from "../service/task.dispatch.service"; import {Test} from "@nestjs/testing"; import {AppModule} from "../app.module"; import {TaskEnum} from '../constant'; describe('TaskDispatchService', () => { let taskService: TaskDispatchService; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [ AppModule ] }).compile(); taskService = module.get<TaskDispatchService>(TaskDispatchService); }) describe('needDoTask', () => { it('needDoTask Test', async () => { const taskName = TaskEnum.tx const isNeed = await taskService.needDoTask(taskName) console.log(isNeed, '----') }); }); })
bianjieai/iobscan-ibc-explorer-backend
src/schema/ibc_denom_caculate.schema.ts
<gh_stars>1-10 import * as mongoose from 'mongoose'; import {IbcDenomCaculateType} from "../types/schemaTypes/ibc_denom_hash.interface"; export const IbcDenomCaculateSchema = new mongoose.Schema( { chain_id: String, sc_chain_id: String, denom: String, base_denom: String, denom_path: String, symbol: { type: String, default: '', }, create_at: { type: Number, default: Math.floor(new Date().getTime() / 1000), }, update_at: { type: Number, default: Math.floor(new Date().getTime() / 1000), }, }, {versionKey: false}, ); IbcDenomCaculateSchema.index({chain_id: 1, denom: 1}, {unique: true}); IbcDenomCaculateSchema.index({sc_chain_id: 1}); IbcDenomCaculateSchema.statics = { async findCount(): Promise<number> { return this.count(); }, async findCaculateDenom(sc_chain_id): Promise<IbcDenomCaculateType[]> { return this.find({sc_chain_id:sc_chain_id}); }, async findIbcDenoms(chain_id,denoms): Promise<IbcDenomCaculateType[]> { return this.find({ chain_id:chain_id, denom: { $in: denoms, }}, {_id: 0}); }, async insertDenomCaculate(ibcDenom, session): Promise<void>{ return this.insertMany(ibcDenom,{ ordered: false }, (error) => { if(JSON.stringify(error).includes('E11000')){ // Primary key conflict handling }else { if (error) { console.log(error,'insertMany IbcTx error') } } },session); }, };
bianjieai/iobscan-ibc-explorer-backend
src/module/ibc_denom_update.task.module.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend import { Module } from '@nestjs/common'; import { IbcDenomUpdateTaskService } from '../task/ibc_denom_update.task.service'; @Module({ providers: [IbcDenomUpdateTaskService], exports: [IbcDenomUpdateTaskService], }) export class IbcDenomUpdateTaskModule {}
bianjieai/iobscan-ibc-explorer-backend
src/task/ibc_update_substate_tx_task.service.ts
import {Injectable} from '@nestjs/common'; import {SubState, TaskEnum} from "../constant"; import {IbcTxHandler} from "../util/IbcTxHandler"; import {dateNow} from "../helper/date.helper"; @Injectable() export class IbcUpdateSubStateTxTaskService { constructor(private readonly taskCommonService: IbcTxHandler) { this.doTask = this.doTask.bind(this); } async doTask(taskName?: TaskEnum): Promise<void> { const substate = [SubState.SuccessRecvPacketNotFound,SubState.RecvPacketAckFailed,SubState.SuccessTimeoutPacketNotFound] const ibcTxLatestModel = this.taskCommonService.getIbcTxLatestModel() await this.taskCommonService.changeIbcTxState(ibcTxLatestModel,dateNow,substate,false,[]) } }
bianjieai/iobscan-ibc-explorer-backend
src/service/ibc_denom.service.ts
import { Injectable } from '@nestjs/common'; import { Connection } from 'mongoose'; import { InjectConnection } from '@nestjs/mongoose'; import { IbcDenomSchema } from '../schema/ibc_denom.schema'; import { IbcDenomResDto } from '../dto/ibc_denom.dto'; @Injectable() export class IbcDenomService { private ibcDenomModel; constructor(@InjectConnection() private connection: Connection) { this.getModels(); } async getModels(): Promise<void> { this.ibcDenomModel = await this.connection.model( 'ibcDenomModel', IbcDenomSchema, 'ibc_denom', ); } // findAllRecord async findAllRecord(): Promise<IbcDenomResDto[]> { const result: IbcDenomResDto[] = IbcDenomResDto.bundleData(await this.ibcDenomModel.findAllRecord()) return result; } async updateIbcDenom(ibcDenom) :Promise<void>{ return await this.ibcDenomModel.updateDenomRecord(ibcDenom) } }
bianjieai/iobscan-ibc-explorer-backend
src/controller/monitor.controller.ts
import { PrometheusController } from "@willsoto/nestjs-prometheus"; import { Controller, Get, Res } from "@nestjs/common"; import { Response } from "express"; @Controller() export class MonitorController extends PrometheusController { @Get() async index(@Res() response: Response) { await super.index(response); } }
bianjieai/iobscan-ibc-explorer-backend
src/module/ibc_sync_transfer_tx_task.module.ts
<filename>src/module/ibc_sync_transfer_tx_task.module.ts import { Module } from '@nestjs/common'; import {IbcSyncTransferTxTaskService} from "../task/ibc_sync_transfer_tx_task.service"; import {IbcTxHandler} from "../util/IbcTxHandler"; import {TransferTaskStatusMetric, TransferTaskStatusProvider} from "../monitor/metrics/ibc_transfer_task_status.metric"; @Module({ providers: [IbcSyncTransferTxTaskService,IbcTxHandler,TransferTaskStatusMetric, TransferTaskStatusProvider(),], exports: [IbcSyncTransferTxTaskService], }) export class IbcSyncTransferTxTaskModule {}
bianjieai/iobscan-ibc-explorer-backend
src/task/ibc_statistics.task.service.test.ts
import {Test} from '@nestjs/testing' import {IbcStatisticsTaskService} from "./ibc_statistics.task.service"; import {AppModule} from "../app.module"; describe('IbcStatisticsTaskService', () => { let ibcStatisticsTaskService: IbcStatisticsTaskService; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [ AppModule ] }).compile(); ibcStatisticsTaskService = module.get<IbcStatisticsTaskService>(IbcStatisticsTaskService); }) describe('parseIbcStatistics', () => { it('parseIbcStatistics', async () => { const dateNow = Math.floor(1637737022); await ibcStatisticsTaskService.parseIbcStatistics(dateNow) // console.log(ibcTxTaskService,'----') }); }); describe("AggregateFindSrcChannels", () => { it('AggregateFindSrcChannels ', async () => { const dateNow = Math.floor(1623955689); const chains = ["osmosis_1", "cosmoshub_4"] const data = await ibcStatisticsTaskService.aggregateFindSrcChannels(dateNow, chains) console.log(data) }); }); describe("AggregateFindDesChannels", () => { it('AggregateFindDesChannels Test ', async () => { const dateNow = Math.floor(1623955689); const chains = ["osmosis_1", "cosmoshub_4", "regen_1"] const data = await ibcStatisticsTaskService.aggregateFindDesChannels(dateNow, chains) console.log(data) }); }); describe("updateStaticsData", () => { it('updateDb Test', async () => { const record = await ibcStatisticsTaskService.findStatisticsRecord("chains_24hr") record.count = 10 console.log(record) await ibcStatisticsTaskService.updateStatisticsRecord(record) }); }); describe("aggregateBaseDenomCnt", () => { it('aggregateBaseDenomCnt Test', async () => { const record = await ibcStatisticsTaskService.aggregateBaseDenomCnt() console.log(record) }); it('getCountinfo Test', async () => { const record = await ibcStatisticsTaskService.getCountinfo() console.log(record) }); }); })
bianjieai/iobscan-ibc-explorer-backend
src/service/ibc_chain.service.ts
<gh_stars>1-10 import {Injectable} from '@nestjs/common'; import {Connection} from 'mongoose'; import {InjectConnection} from '@nestjs/mongoose'; import {IbcChainConfigSchema} from '../schema/ibc_chain_config.schema'; import {IbcChainConfigType} from '../types/schemaTypes/ibc_chain_config.interface'; import {IbcChainResDto, IbcChainResultResDto} from '../dto/ibc_chain.dto'; import {IbcTxSchema} from "../schema/ibc_tx.schema"; // import {AggregateResult24hr} from "../types/schemaTypes/ibc_tx.interface"; import {IbcStatisticsSchema} from "../schema/ibc_statistics.schema"; import {IbcStatisticsType} from "../types/schemaTypes/ibc_statistics.interface"; @Injectable() export class IbcChainService { private ibcChainConfigModel; private ibcStatisticsModel; constructor(@InjectConnection() private connection: Connection) { this.getModels(); } async getModels(): Promise<void> { this.ibcChainConfigModel = await this.connection.model( 'ibcChainConfigModel', IbcChainConfigSchema, 'chain_config', ); // ibcStatisticsModel this.ibcStatisticsModel = await this.connection.model( 'ibcStatisticsModel', IbcStatisticsSchema, 'ibc_statistics', ); } async findActiveChains24hr():Promise<IbcStatisticsType> { // return await this.ibcTxModel.findActiveChains24hr(dateNow); return await this.ibcStatisticsModel.findStatisticsRecord( 'chains_24hr', ); } async handleActiveChains(allIbcChainInfos: IbcChainConfigType[]): Promise<IbcChainConfigType[]> { const result24hrs = await this.findActiveChains24hr(); const chainMap = new Map(); const chains = result24hrs.statistics_info.split(",") for ( const one of chains) { chainMap.set(one,'') } return allIbcChainInfos.filter( (item: IbcChainConfigType) => { return chainMap.has(item.chain_id) }, ); } async getAllChainConfigs() :Promise<IbcChainConfigType[]>{ return await this.ibcChainConfigModel.findList(); } async queryChainsByDatetime(): Promise<IbcChainResultResDto> { const ibcChainAllDatas: IbcChainConfigType[] = await this.getAllChainConfigs() const ibcChainActiveDatas: IbcChainConfigType[] = await this.handleActiveChains(ibcChainAllDatas) const ibcChainInActiveDatas: IbcChainConfigType[] = ibcChainAllDatas.filter( (item: IbcChainConfigType) => { return !ibcChainActiveDatas.some((subItem: IbcChainConfigType) => { return subItem.chain_id === item.chain_id; }); }, ); return new IbcChainResultResDto({ all: IbcChainResDto.bundleData(ibcChainAllDatas), active: IbcChainResDto.bundleData(ibcChainActiveDatas), inactive: IbcChainResDto.bundleData(ibcChainInActiveDatas), }); } }
bianjieai/iobscan-ibc-explorer-backend
src/dto/ibc_base_denom.dto.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend<gh_stars>1-10 import { IbcBaseDenomType } from '../types/schemaTypes/ibc_base_denom.interface'; import { BaseResDto } from './base.dto' export class IbcBaseDenomResDto extends BaseResDto { chain_id: string; denom: string; symbol: string; scale: number; icon: string; is_main_token: boolean; create_at: string; update_at: string; constructor(value) { super() const { chain_id, denom, symbol, scale, icon, is_main_token, create_at, update_at, } = value; this.chain_id = chain_id; this.denom = denom; this.symbol = symbol; this.scale = scale; this.icon = icon; this.is_main_token = is_main_token; this.create_at = create_at; this.update_at = update_at; } static bundleData(value: IbcBaseDenomType[] = []) { const datas: IbcBaseDenomResDto[] = value.map((item: any) => { return { chain_id: item.chain_id, denom: item.denom, symbol: item.symbol, scale: item.scale, icon: item.icon, is_main_token: item.is_main_token, create_at: item.create_at, update_at: item.update_at, } }) return datas } }
bianjieai/iobscan-ibc-explorer-backend
src/app.module.ts
<filename>src/app.module.ts /* eslint-disable @typescript-eslint/consistent-type-assertions */ import {Module} from '@nestjs/common'; import {MongooseModule} from '@nestjs/mongoose'; import {APP_FILTER, APP_PIPE} from '@nestjs/core'; import {HttpExceptionFilter} from './exception/HttpExceptionFilter'; import ValidationPipe from './pipe/validation.pipe'; import {ScheduleModule} from '@nestjs/schedule'; import {TasksService} from './task/task.service'; import {cfg} from './config/config'; import {TaskDispatchModule} from './module/task.dispatch.module'; import {IbcTxModule} from './module/ibc_tx.module'; import {IbcChainConfigTaskModule} from './module/ibc_chain_config.task.module'; import {IbcChainModule} from './module/ibc_chain.module'; import {IbcStatisticsTaskModule} from './module/ibc_statistics.task.module'; import {IbcStatisticsModule} from './module/ibc_statistics.module'; import {IbcBaseDenomModule} from './module/ibc_base_denom.module'; import {IbcDenomModule} from './module/ibc_denom.module'; import {ConfigModule} from './module/config.module'; import {MonitorModule} from './module/monitor.task.module'; import {IbcSyncTransferTxTaskModule} from "./module/ibc_sync_transfer_tx_task.module"; import {IbcUpdateProcessingTxModule} from "./module/ibc_update_processing_tx_task.module"; import {IbcUpdateSubstateTxTaskModule} from "./module/ibc_update_substate_tx_task.module"; import {IbcTxDataUpdateModule} from "./module/ibc_tx_data_update_task.module"; import {IbcTxLatestMigrateTaskModule} from "./module/ibc_tx_latest_migrate_task.module"; import {IbcDenomCaculateTaskModule} from "./module/ibc_denom_caculate.task.module"; import {IbcDenomUpdateTaskModule} from "./module/ibc_denom_update.task.module"; const url = `mongodb://${cfg.dbCfg.user}:${cfg.dbCfg.psd}@${cfg.dbCfg.dbAddr}/${cfg.dbCfg.dbName}`; // const url: string = `mongodb://localhost:27017/ibc-db`; export const params = { imports: [ MongooseModule.forRoot(url), ScheduleModule.forRoot(), TaskDispatchModule, IbcTxModule, IbcChainConfigTaskModule, IbcChainModule, IbcStatisticsTaskModule, IbcStatisticsModule, IbcBaseDenomModule, IbcDenomModule, IbcDenomCaculateTaskModule, IbcDenomUpdateTaskModule, IbcSyncTransferTxTaskModule, IbcUpdateProcessingTxModule, IbcUpdateSubstateTxTaskModule, IbcTxDataUpdateModule, IbcTxLatestMigrateTaskModule, ConfigModule, MonitorModule, ], providers: <any>[ { provide: APP_FILTER, useClass: HttpExceptionFilter, }, { provide: APP_PIPE, useClass: ValidationPipe, }, ], }; params.providers.push(TasksService); // if (cfg.env !== 'development') { // params.providers.push(TasksService); // } @Module(params) export class AppModule { }
bianjieai/iobscan-ibc-explorer-backend
src/schema/ibc_task_record.schema.ts
import * as mongoose from 'mongoose'; import { IbcTaskRecordType } from '../types/schemaTypes/ibc_task_record.interface'; import { IbcTaskRecordStatus } from '../constant'; export const IbcTaskRecordSchema = new mongoose.Schema({ _id: String, task_name: String, status: { type: String, default: IbcTaskRecordStatus.OPEN, }, height: Number, create_at: { type: Number, default: Math.floor(new Date().getTime() / 1000), }, update_at: { type: Number, default: Math.floor(new Date().getTime() / 1000), }, }); IbcTaskRecordSchema.index({ task_name: 1 }, { unique: true }); IbcTaskRecordSchema.statics = { // async findAllChainConfig(): Promise<IbcTaskRecordType[]> { // return this.find(); // }, async findTaskRecord(task_id): Promise<IbcTaskRecordType> { return await this.findOne( { task_name: `sync_${task_id}_transfer` }, { _id: 0 }, ); }, async updateTaskRecord(taskRecord: IbcTaskRecordType): Promise<void> { const { task_name } = taskRecord; const options = { upsert: true, new: false, setDefaultsOnInsert: true }; return this.findOneAndUpdate({ task_name }, taskRecord, options); }, async insertManyTaskRecord(taskRecords: IbcTaskRecordType[]): Promise<void> { return this.insertMany(taskRecords, { ordered: false }); }, };
bianjieai/iobscan-ibc-explorer-backend
src/types/task.interface.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend<filename>src/types/task.interface.ts import { IRandomKey } from './index'; import { TaskEnum } from '../constant'; export interface TaskCallback { (taskName?: TaskEnum, randomKey?: IRandomKey): Promise<void>; } export interface DispatchFaultTolerance { (taskName: TaskEnum): void; }
bianjieai/iobscan-ibc-explorer-backend
src/dto/config.dto.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend<gh_stars>1-10 export class ConfigResDto { iobscan: string constructor(value) { const { iobscan } = value; this.iobscan = iobscan } }
bianjieai/iobscan-ibc-explorer-backend
src/schema/ibc_base_denom.schema.ts
<filename>src/schema/ibc_base_denom.schema.ts import * as mongoose from 'mongoose'; import { IbcBaseDenomType } from '../types/schemaTypes/ibc_base_denom.interface'; export const IbcBaseDenomSchema = new mongoose.Schema( { chain_id: String, denom: String, symbol: String, scale: Number, icon: String, is_main_token: Boolean, ibc_info_hash_caculate: String, create_at: { type: Number, default: Math.floor(new Date().getTime() / 1000), }, update_at: { type: Number, default: Math.floor(new Date().getTime() / 1000), }, }, { versionKey: false }, ); IbcBaseDenomSchema.index({ chain_id: 1, denom: 1 }, { unique: true }); IbcBaseDenomSchema.statics = { async findCount(): Promise<number> { return this.count(); }, async findAllRecord(): Promise<IbcBaseDenomType[]> { return this.find(); }, async findByDenoms(denoms): Promise<IbcBaseDenomType[]> { return this.find({ denom:{ $in:denoms, } }); }, async updateBaseDenomWithSession(baseDenom: IbcBaseDenomType,session) { const {chain_id,denom} = baseDenom; const options = {session,upsert: true, new: false, setDefaultsOnInsert: true}; return this.findOneAndUpdate({chain_id,denom}, baseDenom, options); }, async insertBaseDenom(ibcBaseDenom): Promise<void>{ return this.create(ibcBaseDenom); }, };
bianjieai/iobscan-ibc-explorer-backend
src/service/ibc_statistics.service.ts
import { Injectable } from '@nestjs/common'; import { Connection } from 'mongoose'; import { InjectConnection } from '@nestjs/mongoose'; import { IbcStatisticsSchema } from '../schema/ibc_statistics.schema'; import { IbcStatisticsResDto } from '../dto/ibc_statistics.dto'; @Injectable() export class IbcStatisticsService { private ibcStatisticsModel; constructor(@InjectConnection() private connection: Connection) { this.getModels(); } async getModels(): Promise<void> { // ibcStatisticsModel this.ibcStatisticsModel = await this.connection.model( 'ibcStatisticsModel', IbcStatisticsSchema, 'ibc_statistics', ); } // getAllRecord async findAllRecord(): Promise<IbcStatisticsResDto[]> { const result: IbcStatisticsResDto[] = IbcStatisticsResDto.bundleData( await this.ibcStatisticsModel.findAllRecord(), ); return result; } }
bianjieai/iobscan-ibc-explorer-backend
src/task/ibc_chain_config.task.service.test.ts
import {IbcChainConfigTaskService} from "./ibc_chain_config.task.service"; import {Test} from "@nestjs/testing"; import {AppModule} from "../app.module"; describe('IbcChainConfigTaskService', () => { let ibcChainConfigTaskService: IbcChainConfigTaskService; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [ AppModule ] }).compile(); ibcChainConfigTaskService = module.get<IbcChainConfigTaskService>(IbcChainConfigTaskService); }) describe('parseChainConfig', () => { it('parseChainConfig Test', async () => { const result = await ibcChainConfigTaskService.parseChainConfig() console.log(result,'----') }); }); describe('findAllConfig', () => { it('findAllConfig Test', async () => { const allChains = await ibcChainConfigTaskService.findAllConfig() console.log(allChains,'--allChains--') }); }); describe('handleChain', () => { it('handleChain Test', async () => { const allChains = await ibcChainConfigTaskService.handleChain() console.log(allChains,'--allChains--') }); }); })
bianjieai/iobscan-ibc-explorer-backend
src/helper/date.helper.ts
export const dateNow = Math.floor(new Date().getTime() / 1000);
bianjieai/iobscan-ibc-explorer-backend
src/module/ibc_chain_config.task.module.ts
import { Module } from '@nestjs/common'; import { ChainHttp } from '../http/lcd/chain.http'; import { IbcChainConfigTaskService } from '../task/ibc_chain_config.task.service'; @Module({ imports: [ChainHttp], providers: [IbcChainConfigTaskService], exports: [IbcChainConfigTaskService], }) export class IbcChainConfigTaskModule {}
bianjieai/iobscan-ibc-explorer-backend
src/types/schemaTypes/ibc_statistics.interface.ts
export interface IbcStatisticsType { statistics_name: string; count: number; count_latest:number; statistics_info: string; create_at: string; update_at: string; }
bianjieai/iobscan-ibc-explorer-backend
src/task/ibc_chain_config.task.service.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend import { Injectable, Logger } from '@nestjs/common'; import { Connection } from 'mongoose'; import { InjectConnection } from '@nestjs/mongoose'; import { IbcChainConfigSchema } from '../schema/ibc_chain_config.schema'; import { TaskEnum, Delimiter } from '../constant'; import { ChainHttp } from '../http/lcd/chain.http'; import { groupBy } from 'lodash'; import {IbcChainConfigType} from "../types/schemaTypes/ibc_chain_config.interface"; import {Md5} from 'ts-md5/dist/md5' @Injectable() export class IbcChainConfigTaskService { private chainConfigModel; constructor(@InjectConnection() private connection: Connection) { this.getModels(); this.doTask = this.doTask.bind(this); } async doTask(taskName?: TaskEnum): Promise<void> { // this.parseChainConfig(); this.handleChain(); } async getModels(): Promise<void> { this.chainConfigModel = await this.connection.model( 'chainConfigModel', IbcChainConfigSchema, 'chain_config', ); } async findAllConfig():Promise<IbcChainConfigType[]> { return await this.chainConfigModel.findAll(); } dcChainKey(chain,channel) :string{ return `${chain.chain_id}${Delimiter}${channel.channel_id}/${channel.port_id}` } async getDcChainMap(chain){ let scChainDcChainMap = new Map; for (const channel of chain['ibc_info']) { if (!chain.lcd_api_path.client_state_path) { Logger.error("get dc_chain_id fail from lcd for lcd_api_path.client_state_path is empty") continue } let dc_chain_id = await ChainHttp.getDcChainIdByScChannel(chain.lcd, chain.lcd_api_path.client_state_path, channel.port_id, channel.channel_id); if (dc_chain_id) { dc_chain_id = dc_chain_id.replace(new RegExp("\-", "g"),"_") scChainDcChainMap.set(this.dcChainKey(chain,channel),dc_chain_id) } } return scChainDcChainMap } async handleChain() { Logger.debug("Start to handle Chain Channels info") const allChains = await this.findAllConfig(); // request configed allchannels Promise.all( allChains.map(async chain => { let channels = await ChainHttp.getIbcChannels(chain.lcd,chain.lcd_api_path.channels_path); channels && channels.map(channel => { channel.sc_chain_id = chain.chain_id; }); return Promise.resolve({ chain_id: chain.chain_id, chain_name: chain.chain_name, lcd: chain.lcd, lcd_api_path: chain.lcd_api_path, icon: chain.icon, ibc_info: channels ? channels : [], ibc_info_hash_lcd:"", ibc_info_hash_caculate:"", isManual: chain?.is_manual }); }), ).then(allChains => { const channelsObj = {}; let supportChainsIdMap = new Map; for(const chain of allChains) { supportChainsIdMap.set(chain.chain_id,chain.chain_id) } // set channelsObj datas allChains && allChains.forEach(chain => { channelsObj[chain['chain_id']] = {}; chain['ibc_info'] && chain['ibc_info'].forEach(channel => { channelsObj[chain['chain_id']][ `${channel.channel_id}/${channel.port_id}/${channel.counterparty.channel_id}/${channel.counterparty.port_id}` ] = `${channel.sc_chain_id}${Delimiter}${channel.state}`; }); }); // get datas from channelsObj allChains && allChains.forEach(async chain => { //获取最新的ibc_info的hashCode const hashCode = Md5.hashStr(JSON.stringify(chain.ibc_info)) //判断是否需要更新ibc_info信息 if (hashCode !== chain.ibc_info_hash_lcd && chain.ibc_info.length > 0) { chain.ibc_info_hash_lcd = Md5.hashStr(JSON.stringify(chain.ibc_info)) }else{ Logger.log("this chain ibc_info no need update for ibc_info hashcode is not change") return } const dcChainIdMap = await this.getDcChainMap(chain) chain['ibc_info'] && chain['ibc_info'].forEach(channel => { const key = this.dcChainKey(chain,channel) // get dc_Chainid by key const dc_Chainid = dcChainIdMap.get(key) if (dcChainIdMap.size > 0 && dc_Chainid) { if (supportChainsIdMap.has(dc_Chainid)){ // dcChainId find and only include config chain channel['chain_id'] = dc_Chainid const result = channelsObj[dc_Chainid][ `${channel.counterparty.channel_id}/${channel.counterparty.port_id}/${channel.channel_id}/${channel.port_id}` ]; if (result) { channel['counterparty']['state'] = result.split(Delimiter)[1]; } } } }); // filter unconfig channels chain['ibc_info'] = chain['ibc_info'] && chain['ibc_info'].filter(channel => { return channel.hasOwnProperty('chain_id'); }); const ibcInfoGroupBy = groupBy(chain['ibc_info'], 'chain_id'); const ibcInfo = []; Object.keys(ibcInfoGroupBy) && Object.keys(ibcInfoGroupBy).forEach(chain_id => { ibcInfo.push({ chain_id, paths: ibcInfoGroupBy[`${chain_id}`] }); }); chain['ibc_info'] = ibcInfo; // update if(!chain.isManual){ this.chainConfigModel.updateChain(chain); } }); }); Logger.debug("Quit to handle Chain Channels info") } // get and sync chainConfig datas async parseChainConfig() { const allChains = await this.findAllConfig(); // request configed allchannels Promise.all( allChains.map(async chain => { let channels = await ChainHttp.getIbcChannels(chain.lcd,chain.lcd_api_path.channels_path); channels && channels.map(channel => { channel.sc_chain_id = chain.chain_id; }); return Promise.resolve({ chain_id: chain.chain_id, chain_name: chain.chain_name, lcd: chain.lcd, lcd_api_path: chain.lcd_api_path, icon: chain.icon, ibc_info: channels ? channels : [], isManual: chain?.is_manual }); }), ).then(allChains => { const channelsObj = {}; const allChainsId = allChains && allChains.map(chain => { return chain['chain_id']; }); // set channelsObj datas allChains && allChains.forEach(chain => { channelsObj[chain['chain_id']] = {}; chain['ibc_info'] && chain['ibc_info'].forEach(channel => { channelsObj[chain['chain_id']][ `${channel.channel_id}/${channel.port_id}/${channel.counterparty.channel_id}/${channel.counterparty.port_id}` ] = `${channel.sc_chain_id}${Delimiter}${channel.state}`; }); }); // get datas from channelsObj allChains && allChains.forEach(async chain => { chain['ibc_info'] && chain['ibc_info'].forEach(channel => { allChainsId && allChainsId.forEach(chainId => { if (chainId !== chain['chain_id']) { const result = channelsObj[chainId][ `${channel.counterparty.channel_id}/${channel.counterparty.port_id}/${channel.channel_id}/${channel.port_id}` ]; if (result) { channel['chain_id'] = result.split(Delimiter)[0]; channel['counterparty']['state'] = result.split(Delimiter)[1]; } } }); }); // filter unconfig channels chain['ibc_info'] = chain['ibc_info'] && chain['ibc_info'].filter(channel => { return channel.hasOwnProperty('chain_id'); }); // groupby datas const ibcInfoGroupBy = groupBy(chain['ibc_info'], 'chain_id'); const ibcInfo = []; Object.keys(ibcInfoGroupBy) && Object.keys(ibcInfoGroupBy).forEach(chain_id => { ibcInfo.push({ chain_id, paths: ibcInfoGroupBy[`${chain_id}`] }); }); chain['ibc_info'] = ibcInfo; // update if(!chain.isManual){ this.chainConfigModel.updateChain(chain); } }); }); } }
bianjieai/iobscan-ibc-explorer-backend
src/helper/denom.helper.test.ts
<gh_stars>1-10 import {getDcDenom, IbcDenom} from "./denom.helper"; describe('getDcDenom', () => { describe('getDcDenom', () => { it('getDcDenom Test', async () => { const msg = { msg:{ 'packet':{ "source_port" : "transfer", "source_channel" : "channel-10", "destination_port" : "transfer", "destination_channel" : "channel-36", "data" : { "denom" : "transfer/channel-9/transfer/channel-54/uiris", "amount" : 2, "sender" : "<KEY>", "receiver" : "<KEY>" } }} } const data = await getDcDenom(msg) console.log(data, '--result--') }); it('IbcDenom Test', async () => { const data = await IbcDenom("transfer/channel-54","uiris") console.log(data, '--result--') const data1 = await IbcDenom("","uiris") console.log(data1, '--result--') }); }); })
bianjieai/iobscan-ibc-explorer-backend
src/types/schemaTypes/ibc_task_record.interface.ts
export interface IbcTaskRecordType { task_name: String; status: String; height: Number; create_at: Number; update_at: Number; }
bianjieai/iobscan-ibc-explorer-backend
src/dto/http.dto.ts
import { LcdChannelType } from '../types/lcd.interface'; import { BaseResDto } from './base.dto' export class LcdChannelDto extends BaseResDto { state: string; counterparty: { port_id: string; channel_id: string; }; port_id: string; channel_id: string; sc_chain_id: string; constructor(value: any) { super() const { state, counterparty, port_id, channel_id } = value; this.state = state || ''; this.counterparty = counterparty || { port_id: '', channel_id: '', }; this.port_id = port_id || ''; this.channel_id = channel_id || ''; } static bundleData(value: LcdChannelType[]): LcdChannelDto[] { const datas: LcdChannelDto[] = value.map(item => { return new LcdChannelDto(item); }); return datas; } } export class LcdDenomDto extends BaseResDto { denom_path: string; base_denom: string; constructor(value) { super() const { path, base_denom } = value this.denom_path = path this.base_denom = base_denom } }
bianjieai/iobscan-ibc-explorer-backend
src/helper/task.helper.ts
import {Logger} from '../logger'; export async function getTaskStatus(chainId:any,taskModel: any,taskName): Promise<boolean>{ let count: number = await taskModel.queryTaskCount() console.log(chainId,count,`${chainId} task count is ${count}`) if (count <= 0) { Logger.log(`${taskName}: Catch-up status task suspended`) } return count == 1 }
bianjieai/iobscan-ibc-explorer-backend
src/util/IbcTxHandler.ts
<filename>src/util/IbcTxHandler.ts /* eslint-disable @typescript-eslint/camelcase */ import {Injectable} from '@nestjs/common'; import {Connection, StartSession} from 'mongoose'; import {InjectConnection} from '@nestjs/mongoose'; import {IbcChainConfigSchema} from '../schema/ibc_chain_config.schema'; import {IbcDenomSchema} from '../schema/ibc_denom.schema'; import {IbcTxSchema} from '../schema/ibc_tx.schema'; import {TxSchema} from '../schema/tx.schema'; import {IbcBlockSchema} from '../schema/ibc_block.schema'; import {IbcTaskRecordSchema} from '../schema/ibc_task_record.schema'; import {IbcTxType} from '../types/schemaTypes/ibc_tx.interface'; import {JSONparse} from '../util/util'; import {getDcDenom} from '../helper/denom.helper'; import {SubState, TaskTime, IbcTxTable} from '../constant'; import { TaskEnum, TxType, TxStatus, IbcTxStatus, RecordLimit, IbcTaskRecordStatus, } from '../constant'; import {dateNow} from "../helper/date.helper"; import {getTaskStatus} from "../helper/task.helper"; import {SyncTaskSchema} from "../schema/sync.task.schema"; import {Logger} from "../logger"; import {IbcChainConfigType} from "../types/schemaTypes/ibc_chain_config.interface"; @Injectable() export class IbcTxHandler { private ibcTaskRecordModel; private chainConfigModel; private ibcTxLatestModel; private ibcTxModel; private ibcDenomModel; constructor(@InjectConnection() private readonly connection: Connection) { this.getModels(); } // getModels async getModels(): Promise<void> { // ibcTaskRecordModel this.ibcTaskRecordModel = await this.connection.model( 'ibcTaskRecordModel', IbcTaskRecordSchema, 'ibc_task_record', ); // chainConfigModel this.chainConfigModel = await this.connection.model( 'chainConfigModel', IbcChainConfigSchema, 'chain_config', ); // ibcTxModel this.ibcTxModel = await this.connection.model( 'ibcTxModel', IbcTxSchema, IbcTxTable.IbcTxTableName, ); this.ibcTxLatestModel = await this.connection.model( 'ibcTxLatestModel', IbcTxSchema, IbcTxTable.IbcTxLatestTableName, ); // ibcDenomModel this.ibcDenomModel = await this.connection.model( 'ibcDenomModel', IbcDenomSchema, 'ibc_denom', ); } getIbcTxModel() { return this.ibcTxModel } getIbcTxLatestModel() { return this.ibcTxLatestModel } // ibcTx first(transfer) async getAllChainsMap() { const allChains = await this.chainConfigModel.findAll(); const allChainsMap = new Map, allChainsDenomPathsMap = new Map if (allChains?.length) { allChains.forEach(item => { if (item?.chain_id) { allChainsMap.set(item.chain_id, item) if (item?.ibc_info?.length) { item.ibc_info.forEach(info => { if (info?.paths?.length) { info.paths.forEach(path => { if (path?.channel_id && path?.port_id) allChainsDenomPathsMap.set(`${info.chain_id}${path.counterparty.channel_id}${path.counterparty.port_id}`, `${path.counterparty.channel_id}${path.counterparty.port_id}`) }) } }) } } }) } return { allChainsMap, allChainsDenomPathsMap } } async getDenomRecordByChainId(chainId) { const ibcDenomRecordMap = new Map const ibcDenomRecord = await this.ibcDenomModel.findAllDenomRecord(chainId); if (ibcDenomRecord?.length) { ibcDenomRecord.forEach(ibcDenomRecordItem => { if (ibcDenomRecordItem?.denom) { ibcDenomRecordMap.set(ibcDenomRecordItem?.denom, ibcDenomRecordItem) } }) } return ibcDenomRecordMap } async getRecordLimitTx(chainId, height, limit): Promise<Array<any>> { const txModel = await this.connection.model( 'txModel', TxSchema, `sync_${chainId}_tx`, ); let txs = []; //根据块高排序 查询最后限制条数的交易 const txsByLimit = await txModel.queryTxListSortHeight({ type: TxType.transfer, height: height, limit: limit, }); // 根据块高查询限制条数的最后一条交易 const txsByHeight = txsByLimit.length ? await txModel.queryTxListByHeight( TxType.transfer, txsByLimit[txsByLimit.length - 1].height, ) : []; //去重 const hash = {}; txs = [...txsByLimit, ...txsByHeight].reduce((txsResult, next) => { hash[next.tx_hash] ? '' : (hash[next.tx_hash] = true) && txsResult.push(next); return txsResult; }, []); return txs } async checkTaskFollowingStatus(chainId): Promise<boolean> { const taskModel = await this.connection.model( 'txModel', SyncTaskSchema, `sync_${chainId}_task`, ); return await getTaskStatus(chainId, taskModel, TaskEnum.tx) } async parseIbcTx(ibcTxModel,dateNow): Promise<void> { const allChains = await this.chainConfigModel.findAll(); const {allChainsMap, allChainsDenomPathsMap} = await this.getAllChainsMap() let ibcDenoms = [] for (const {chain_id} of allChains) { // get taskRecord by chain_id let taskRecord = await this.ibcTaskRecordModel.findTaskRecord(chain_id); if (!taskRecord) { await this.ibcTaskRecordModel.insertManyTaskRecord({ task_name: `sync_${chain_id}_transfer`, status: IbcTaskRecordStatus.OPEN, height: 0, create_at: dateNow, update_at: dateNow, }); taskRecord = await this.ibcTaskRecordModel.findTaskRecord(chain_id); } else { if (taskRecord.status === IbcTaskRecordStatus.CLOSE) continue; } const taskCount = await this.checkTaskFollowingStatus(chain_id) if (!taskCount) continue const denomMap = await this.getDenomRecordByChainId(chain_id) const txs = await this.getRecordLimitTx(chain_id, taskRecord.height, RecordLimit) let { handledTx, denoms } = await this.handlerSourcesTx(txs, chain_id, dateNow, allChainsMap, allChainsDenomPathsMap,denomMap) ibcDenoms = [...denoms] if (ibcDenoms?.length) { await this.ibcDenomModel.insertManyDenom(ibcDenoms); } if (handledTx?.length) { const session = await this.connection.startSession() session.startTransaction() try { await ibcTxModel.insertManyIbcTx(handledTx) taskRecord.height = handledTx[handledTx.length - 1]?.sc_tx_info?.height; taskRecord.update_at = dateNow await this.ibcTaskRecordModel.updateTaskRecord(taskRecord); await session.commitTransaction(); session.endSession(); } catch (e) { Logger.log(e, 'transaction is error') await session.abortTransaction() session.endSession(); } } } Logger.debug(`end parseIbcTx time ${dateNow}`) } async getProcessingTxs(ibcTxModel,substate) { if (substate?.length == 1 && substate[0] === 0) { const ibcTxs = await ibcTxModel.queryTxList({ status: IbcTxStatus.PROCESSING, substate: substate, limit: RecordLimit, }); return ibcTxs } else { const substateTxs = await ibcTxModel.queryTxListBySubstate({ status: IbcTxStatus.PROCESSING, substate: substate, limit: RecordLimit, }); return substateTxs } } async getChainsCfg() :Promise<IbcChainConfigType[]>{ return await this.chainConfigModel.findAll(); } // get processing ibc tx by page for update batch limit async getProcessingTxsByPage(sc_chain_id,substate,page) { const stateTxs = await this.ibcTxModel.queryTxListByPage({ sc_chain_id:sc_chain_id, status: IbcTxStatus.PROCESSING, substate: substate, page: page, limit: RecordLimit, }); return stateTxs } async getPacketIds(txs) { const packetIds = [] if (txs?.length) { for (const tx of txs) { if (tx?.sc_tx_info?.msg?.msg?.packet_id) { // ibcTx.sc_tx_info.msg.msg.timeout_height.revision_height; if (tx?.dc_chain_id && tx?.sc_tx_info?.msg?.msg?.packet_id && tx?.sc_tx_info?.msg?.msg?.timeout_height?.revision_height >= 0 // && tx?.sc_tx_info?.msg?.msg?.timeout_timestamp >= 0 ) { packetIds.push( { chainId: tx.dc_chain_id, height: tx.sc_tx_info.msg.msg.timeout_height.revision_height, packetId: tx.sc_tx_info.msg.msg.packet_id, timeOutTime: tx.sc_tx_info.msg.msg.timeout_timestamp } ) } } } } return packetIds } // if handlIbcTxCron is true,don't need call insertManyDenom save ibc_denom async changeIbcTxState(ibcTxModel,dateNow, substate: number[],handlIbcTxCron:boolean,txs :IbcTxType[]): Promise<void> { const ibcTxs = await this.getProcessingTxs(ibcTxModel,substate) if (handlIbcTxCron && txs?.length) { ibcTxs.push(txs) } // const ibcTxs = await ibcTxModel.queryTxByRecordId("transferchannel-28transferchannel-12163541irishub_qaF29DEFE6DE7C6355489F5D2CCC96EF2D630E351F843852050D1A29317C21FBDB0") let packetIdArr = ibcTxs?.length ? await this.getPacketIds(ibcTxs) : []; let recvPacketTxMap = new Map, chainHeightMap = new Map, refundedTxTxMap = new Map, acknowledgeTxsMap = new Map, needUpdateTxs = [], denoms = [] let dcChains = [],scChains = []; ibcTxs.forEach(item => { if (item?.dc_chain_id ) { dcChains.push(item.dc_chain_id) } if(item?.sc_chain_id){ scChains.push(item.sc_chain_id) } }) const allChains = [...dcChains,...scChains] const currentDcChains = Array.from(new Set(allChains)) // 根据链的配置信息,查询出每条链的 recv_packet 成功的交易的那条记录 if (currentDcChains?.length) { for (const chain of currentDcChains) { if (chain) { const blockModel = await this.connection.model( 'blockModel', IbcBlockSchema, `sync_${chain}_block`, ); const chainHeightObj = await blockModel.findLatestBlock(); if (chainHeightObj && JSON.stringify(chainHeightObj) !== '{}') { let {height, time} = await blockModel.findLatestBlock(); chainHeightMap.set(chain, {height, time}) } } } for (const chain of currentDcChains) { if (chain) { const txModel = await this.connection.model( 'txModel', TxSchema, `sync_${chain}_tx`, ); const taskCount = await this.checkTaskFollowingStatus(chain) if (!taskCount) continue //每条链最新的高度 let refundedTxPacketIdsMap = new Map const refundedTxPacketIds = [],acknowledgeTxPacketIds = []; packetIdArr.forEach(item => { if (item?.chainId && item?.height || item?.timeOutTime) { const currentChainLatestObj = chainHeightMap.get(item.chainId) const dateLen = String(item?.timeOutTime).length if (dateLen > 10) { refundedTxPacketIdsMap.set(item.packetId,'') refundedTxPacketIds.push(item.packetId) }else if (item.height < currentChainLatestObj?.height || item.timeOutTime < currentChainLatestObj?.time) { if (item?.packetId) { refundedTxPacketIdsMap.set(item.packetId, '') refundedTxPacketIds.push(item.packetId) } } } }) const recvPacketIds = packetIdArr.map(item => { if (item?.packetId) { return item.packetId } }) // txs 数组 if (recvPacketIds?.length) { const txs = await txModel.queryTxsByPacketId({ type: TxType.recv_packet, limit: packetIdArr.length, // status: TxStatus.SUCCESS, packet_id: recvPacketIds, }); if (txs?.length) { for (let tx of txs) { if (tx?.msgs?.length) { for (let msg of tx.msgs) { if (msg?.type === TxType.recv_packet && msg.msg.packet_id) { if (tx?.status) { // recv_packet tx is success recvPacketTxMap.set(`${chain}${msg.msg.packet_id}`, tx) }else{ // recv_packet tx is fail acknowledgeTxPacketIds.push(msg.msg.packet_id) } } } } } } } if (refundedTxPacketIds?.length) { // const notIncludeNullPacketIds = refundedTxPacketIds.filter( item => item) const refundedTxs = await txModel.queryTxListByPacketId({ type: TxType.timeout_packet, limit: refundedTxPacketIds.length, status: TxStatus.SUCCESS, packet_id: refundedTxPacketIds, }); if (refundedTxs?.length) { for (let refundedTx of refundedTxs) { if (refundedTx?.msgs?.length) { for (let msg of refundedTx.msgs) { if (msg?.type === TxType.timeout_packet && msg.msg.packet_id) { refundedTxTxMap.set(`${chain}${msg.msg.packet_id}`, refundedTx) } } } } } } if (acknowledgeTxPacketIds?.length) { const acknowledgeTxs = await txModel.queryTxListByPacketId({ type: TxType.acknowledge_packet, limit: acknowledgeTxPacketIds.length, status: TxStatus.SUCCESS, packet_id: acknowledgeTxPacketIds, }); if (acknowledgeTxs?.length) { for (let acknowledgeTx of acknowledgeTxs) { if (acknowledgeTx?.msgs?.length) { for (let msg of acknowledgeTx.msgs) { if (msg?.type === TxType.acknowledge_packet && msg.msg.packet_id) { acknowledgeTxsMap.set(`${chain}${msg.msg.packet_id}`,acknowledgeTx) } } } } } } } } } for (let [index, ibcTx] of ibcTxs.entries()) { if (!ibcTx.dc_chain_id) continue if (!recvPacketTxMap.size && !refundedTxTxMap.size && !acknowledgeTxsMap.size) { ibcTx.substate = SubState.SuccessRecvPacketNotFound; ibcTx = this.setNextTryTime(ibcTx, index) needUpdateTxs.push(ibcTx) } else if (recvPacketTxMap?.has(`${ibcTx.dc_chain_id}${ibcTx.sc_tx_info.msg.msg.packet_id}`)) { const recvPacketTx = recvPacketTxMap?.get(`${ibcTx.dc_chain_id}${ibcTx.sc_tx_info.msg.msg.packet_id}`) // let counter_party_tx = null recvPacketTx && recvPacketTx.msgs.length && recvPacketTx.msgs.forEach(async (msg, msgIndex) => { if (msg.type === TxType.recv_packet && ibcTx.sc_tx_info.msg.msg.packet_id === msg.msg.packet_id) { const {dc_denom, dc_denom_path} = getDcDenom(msg); // add write_acknowledgement solution, value type is string; let result = ''; const tx_events = recvPacketTx.events_new.find( event_new => { return event_new.msg_index === msgIndex; }, ); tx_events && tx_events.events.forEach(event => { if (event.type === 'write_acknowledgement') { event.attributes.forEach(attribute => { if (attribute.key === 'packet_ack') { result = attribute.value === '' ? 'false' : attribute.value && attribute.value.includes('error') ? 'false' : 'true'; } }); } }); switch (result) { case "true": ibcTx.status = IbcTxStatus.SUCCESS ibcTx.substate = 0 ibcTx.retry_times = 0 ibcTx.next_try_time = 0 break; case "false": ibcTx.substate = SubState.RecvPacketAckFailed; ibcTx = this.setNextTryTime(ibcTx, index) break; } ibcTx.status = result === 'false' ? IbcTxStatus.FAILED : IbcTxStatus.SUCCESS; ibcTx.dc_tx_info = { hash: recvPacketTx.tx_hash, status: recvPacketTx.status, time: recvPacketTx.time, height: recvPacketTx.height, fee: recvPacketTx.fee, msg_amount: msg.msg.token, msg, }; ibcTx.update_at = dateNow; // ibcTx.tx_time = counter_party_tx.time; ibcTx.denoms['dc_denom'] = dc_denom; const denom_path = dc_denom_path === ibcTx.base_denom ? '' : dc_denom_path.replace(`/${ibcTx.base_denom}`, ''); needUpdateTxs.push(ibcTx) if (ibcTx.status === IbcTxStatus.SUCCESS) { const denomObj = { chain_id: ibcTx.dc_chain_id, denom: dc_denom, base_denom: ibcTx.base_denom, denom_path: denom_path, is_source_chain: !Boolean(denom_path), is_base_denom: Boolean(dc_denom === ibcTx.base_denom), create_at: dateNow, update_at: '' } denoms.push(denomObj) } } }) } else if (acknowledgeTxsMap?.has(`${ibcTx.sc_chain_id}${ibcTx.sc_tx_info.msg.msg.packet_id}`)){ const acknowledgeTx = acknowledgeTxsMap?.get(`${ibcTx.sc_chain_id}${ibcTx.sc_tx_info.msg.msg.packet_id}`); acknowledgeTx && acknowledgeTx.msgs.forEach(msg => { if ( msg.type === TxType.acknowledge_packet && ibcTx.sc_tx_info.msg.msg.packet_id === msg.msg.packet_id ){ ibcTx.status = IbcTxStatus.REFUNDED; ibcTx.retry_times = 0; ibcTx.next_try_time = 0 ibcTx.refunded_tx_info = { hash: acknowledgeTx.tx_hash, status: acknowledgeTx.status, time: acknowledgeTx.time, height: acknowledgeTx.height, fee: acknowledgeTx.fee, msg_amount: msg.msg.token, msg, }; ibcTx.update_at = dateNow; ibcTx.substate = 0 needUpdateTxs.push(ibcTx) } }) }else { /* * 没有找到的结果 * */ if (refundedTxTxMap.has(`${ibcTx.sc_chain_id}${ibcTx.sc_tx_info.msg.msg.packet_id}`)) { const refunded_tx = refundedTxTxMap?.get(`${ibcTx.sc_chain_id}${ibcTx.sc_tx_info.msg.msg.packet_id}`); refunded_tx && refunded_tx.msgs.forEach(msg => { if ( msg.type === TxType.timeout_packet && ibcTx.sc_tx_info.msg.msg.packet_id === msg.msg.packet_id ) { ibcTx.status = IbcTxStatus.REFUNDED; ibcTx.retry_times = 0; ibcTx.next_try_time = 0 ibcTx.refunded_tx_info = { hash: refunded_tx.tx_hash, status: refunded_tx.status, time: refunded_tx.time, height: refunded_tx.height, fee: refunded_tx.fee, msg_amount: msg.msg.token, msg, }; ibcTx.update_at = dateNow; // ibcTx.tx_time = refunded_tx.time; ibcTx.substate = 0 needUpdateTxs.push(ibcTx) } }); } else { ibcTx.substate = SubState.SuccessTimeoutPacketNotFound; ibcTx = this.setNextTryTime(ibcTx, index) needUpdateTxs.push(ibcTx) } } } if (needUpdateTxs?.length) { for (let needUpdateTx of needUpdateTxs) { await ibcTxModel.updateIbcTx(needUpdateTx); } } if (denoms?.length && !handlIbcTxCron) { await this.ibcDenomModel.insertManyDenom(denoms); } } setNextTryTime(ibcTx, index) { ibcTx.retry_times = ibcTx.retry_times ? Number(ibcTx.retry_times) + 1 : 1 const taskDiffTime = Math.floor(Number(ibcTx.retry_times) * TaskTime) ibcTx.next_try_time = Math.floor(Number(taskDiffTime) + Number(dateNow) + index) return ibcTx } // get dc_port、dc_channel、sequence getIbcInfoFromEventsMsg( tx, msgIndex, ): { dc_port: string; dc_channel: string; sequence: string; base_denom: string; denom_path: string; } { const msg = { dc_port: '', dc_channel: '', sequence: '', base_denom: '', denom_path: '', }; tx.events_new[msgIndex] && tx.events_new[msgIndex].events.forEach(evt => { if (evt.type === 'send_packet') { evt.attributes.forEach(attr => { switch (attr.key) { case 'packet_dst_port': msg.dc_port = attr.value; break; case 'packet_dst_channel': msg.dc_channel = attr.value; break; case 'packet_sequence': msg.sequence = attr.value; break; case 'packet_data': const packet_data = JSONparse(attr.value); const denomOrigin = packet_data.denom; const denomOriginSplit = denomOrigin.split('/'); msg.base_denom = denomOriginSplit[denomOriginSplit.length - 1]; msg.denom_path = denomOriginSplit .slice(0, denomOriginSplit.length - 1) .join('/'); break; default: break; } }); } }); return msg; } async handlerSourcesTx(sourcesTx, chain_id, currentTime, allChainsMap, allChainsDenomPathsMap,denomMap) { let handledTx = [], denoms = [] if (sourcesTx && chain_id) { sourcesTx.forEach((tx, txIndex) => { const height = tx.height; const log = tx.log; const time = tx.time; const hash = tx.tx_hash; const status = tx.status; const fee = tx.fee; tx.msgs.forEach(async (msg, msgIndex) => { if (msg.type === TxType.transfer) { const ibcTx: IbcTxType = { record_id: '', sc_addr: '', dc_addr: '', sc_port: '', sc_channel: '', sc_chain_id: '', dc_port: '', dc_channel: '', dc_chain_id: '', sequence: '', status: 0, sc_tx_info: {}, dc_tx_info: {}, refunded_tx_info: {}, log: {}, substate: 0, denoms: { sc_denom: '', dc_denom: '', }, base_denom: '', create_at: '', update_at: '', tx_time: '', }; switch (tx.status) { case TxStatus.SUCCESS: ibcTx.status = IbcTxStatus.PROCESSING; break; case TxStatus.FAILED: ibcTx.status = IbcTxStatus.FAILED; break; default: break; } const sc_chain_id = chain_id; const sc_port = msg.msg.source_port; const sc_channel = msg.msg.source_channel; let dc_chain_id = ''; let dc_channel = ''; let dc_port = ''; const sc_addr = msg.msg.sender; const dc_addr = msg.msg.receiver; const sc_denom = msg.msg.token.denom; const msg_amount = msg.msg.token; let base_denom = ''; let denom_path = ''; let sequence = ''; //根据 sc_chain_id sc_port sc_channel 查询目标链的信息 let dcChainConfig: any = {} if (sc_chain_id && allChainsMap) { if (allChainsMap.has(sc_chain_id)) { const currentChainInfo = allChainsMap.get(sc_chain_id) if (currentChainInfo?.ibc_info?.length) { currentChainInfo?.ibc_info.forEach(item => { if (item.paths?.length) { item.paths.forEach(pathItem => { if (pathItem?.channel_id === sc_channel && pathItem?.port_id === sc_port) { dcChainConfig = currentChainInfo dc_chain_id = item.chain_id; dc_channel = pathItem.counterparty.channel_id; dc_port = pathItem.counterparty.port_id; } }) } }) } } } if (ibcTx.status === IbcTxStatus.FAILED) { // get base_denom、denom_path from ibc_denom collection if (sc_denom.indexOf('ibc') !== -1) { if (denomMap?.has(sc_denom)) { const ibcDenom = denomMap.get(sc_denom) if (ibcDenom?.base_denom) { base_denom = ibcDenom.base_denom denom_path = ibcDenom?.denom_path } } } else { base_denom = sc_denom; } } else { // get base_denom、denom_path、sequence from events const event_msg = this.getIbcInfoFromEventsMsg(tx, msgIndex); dc_port = event_msg.dc_port; dc_channel = event_msg.dc_channel; base_denom = event_msg.base_denom; denom_path = event_msg.denom_path; sequence = event_msg.sequence; } if (!dc_chain_id && ibcTx.status !== IbcTxStatus.FAILED) { ibcTx.status = IbcTxStatus.SETTING; } ibcTx.record_id = `${sc_port}${sc_channel}${dc_port}${dc_channel}${sequence}${sc_chain_id}${hash}${msgIndex}`; ibcTx.sc_addr = sc_addr; ibcTx.dc_addr = dc_addr; ibcTx.sc_port = sc_port; ibcTx.sc_channel = sc_channel; ibcTx.sc_chain_id = sc_chain_id; ibcTx.dc_port = dc_port; ibcTx.dc_channel = dc_channel; ibcTx.dc_chain_id = dc_chain_id; ibcTx.sequence = sequence; ibcTx.denoms['sc_denom'] = sc_denom; ibcTx.base_denom = base_denom; ibcTx.create_at = currentTime; ibcTx.update_at = currentTime; ibcTx.tx_time = tx.time; ibcTx.sc_tx_info = { hash, status, time, height, fee, msg_amount, msg, }; ibcTx.log['sc_log'] = log; let isBaseDenom = null if (sc_denom === base_denom) { isBaseDenom = true } else { if (denom_path && denom_path.split('/').length > 1) { const dc_port = denom_path.split('/')[0]; const dc_channel = denom_path.split('/')[1]; if (allChainsDenomPathsMap.has(`${dc_chain_id}${dc_channel}${dc_port}`)) { isBaseDenom = false } else { isBaseDenom = true } } } if (ibcTx.status === IbcTxStatus.PROCESSING) { denoms.push({ chain_id: sc_chain_id, denom: sc_denom, base_denom: base_denom, denom_path: denom_path, is_source_chain: !Boolean(denom_path), is_base_denom: isBaseDenom, create_at: dateNow, update_at: '' }) } handledTx.push(ibcTx) } }); }); return { handledTx, denoms } } } }
bianjieai/iobscan-ibc-explorer-backend
src/module/monitor.task.module.ts
import { Module } from '@nestjs/common'; import { PrometheusModule} from "@willsoto/nestjs-prometheus"; import { IbcMonitorService } from "../monitor/ibc_monitor.service"; import { MonitorController } from "../controller/monitor.controller"; import {LcdConnectionMetric,LcdConnectionProvider} from "../monitor/metrics/ibc_chain_lcd_connection.metric"; import {IbcTxProcessingMetric,IbcTxProcessingProvider} from "../monitor/metrics/ibc_tx_processing_cnt.metric"; @Module({ imports: [PrometheusModule.register({ controller: MonitorController, })], providers: [ IbcMonitorService, LcdConnectionMetric, LcdConnectionProvider(), IbcTxProcessingMetric, IbcTxProcessingProvider(), ], exports: [ IbcMonitorService, ] }) export class MonitorModule {}
bianjieai/iobscan-ibc-explorer-backend
src/service/ibc_chain.service.test.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend import {IbcChainService} from "./ibc_chain.service"; import {Test} from "@nestjs/testing"; import {AppModule} from "../app.module"; describe('IbcChainService', () => { let ibcChainService: IbcChainService; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [ AppModule ] }).compile(); ibcChainService = module.get<IbcChainService>(IbcChainService); }) describe('getAllChainConfigs', () => { it('getAllChainConfigs Test', async () => { const result = await ibcChainService.getAllChainConfigs() console.log(result, '----') }); }); describe('findActiveChains24hr', () => { it('findActiveChains24hr Test', async () => { const result = await ibcChainService.findActiveChains24hr() console.log(result, '----') }); }); describe('queryChains', () => { it('queryChains Test', async () => { const result = await ibcChainService.queryChainsByDatetime() console.log(result, '----') }); }); describe('handleActiveChains', () => { it('handleActiveChains Test', async () => { const allChainConfigs = await ibcChainService.getAllChainConfigs() const result = await ibcChainService.handleActiveChains(allChainConfigs) console.log(result, '----') }); }); })
bianjieai/iobscan-ibc-explorer-backend
src/service/ibc_base_denom.service.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend import { Injectable } from '@nestjs/common'; import { Connection } from 'mongoose'; import { InjectConnection } from '@nestjs/mongoose'; import { IbcBaseDenomSchema } from '../schema/ibc_base_denom.schema'; import { IbcBaseDenomResDto } from '../dto/ibc_base_denom.dto'; @Injectable() export class IbcBaseDenomService { private ibcBaseDenomModel; constructor(@InjectConnection() private connection: Connection) { this.getModels(); } async getModels(): Promise<void> { this.ibcBaseDenomModel = await this.connection.model( 'ibcBaseDenomModel', IbcBaseDenomSchema, 'ibc_base_denom', ); } // findAllRecord async findAllRecord(): Promise<IbcBaseDenomResDto[]> { const result: IbcBaseDenomResDto[] = IbcBaseDenomResDto.bundleData(await this.ibcBaseDenomModel.findAllRecord()) return result; } async insertBaseDenom(dto):Promise<void>{ return await this.ibcBaseDenomModel.insertBaseDenom(dto) } }
bianjieai/iobscan-ibc-explorer-backend
src/constant/index.ts
<gh_stars>1-10 export const RecordLimit = 100; export const MaxMigrateBatchLimit = 1000; export const Delimiter = '|'; export const unAuth = 'Others'; export enum SubState { // recv_packet success tx not found SuccessRecvPacketNotFound = 1, // recv_packet ack failed RecvPacketAckFailed = 2, // timeout_packet success tx not found SuccessTimeoutPacketNotFound = 3, } export const TaskTime:number = 15 export const StatisticsNames = [ 'tx_24hr_all', 'chains_24hr', 'channels_24hr', 'chain_all', 'channel_all', 'channel_opened', 'channel_closed', 'tx_all', 'tx_success', 'tx_failed', 'base_denom_all', 'denom_all', ]; export enum TaskEnum { tx = 'ex_sync_tx', transferTx ='ex_sync_transfer_tx', updateProcessingTx = 'update_processing_tx', updateSubStateTx = 'update_substate_tx', ibcTxUpdateCronJob = 'ibc_tx_update_cronjob', ibcTxMigrateCronJob = 'ibc_tx_migrate_cronjob', ibcDenomCaculateCronJob = 'ibc_denom_caculate_cronjob', ibcDenomUpdateCronjob = 'ibc_denom_update_cronjob', chain = 'ex_sync_chain', monitor = "promethous_monitor", statistics = 'ex_sync_statistics', denom = 'ex_sync_denom', nft = 'ex_sync_nft', staticsTxAll = 'tx_all', txServiceName = 'sync_tx_service_name', validators = 'sync_validators', identity = 'sync_identity', stakingSyncValidatorsInfo = 'staking_sync_validators_info', stakingSyncValidatorsMoreInfo = 'staking_sync_validators_more_info', stakingSyncParameters = 'staking_sync_parameters', tokens = 'tokens', proposal = 'ex_sync_proposal', account = 'ex_sync_account', accountInfo = 'ex_sync_account_info', } export const DefaultPaging = { pageNum: 1, pageSize: 10, }; export enum ENV { development = 'development', production = 'production', } export enum TxType { // service define_service = 'define_service', bind_service = 'bind_service', call_service = 'call_service', respond_service = 'respond_service', update_service_binding = 'update_service_binding', disable_service_binding = 'disable_service_binding', enable_service_binding = 'enable_service_binding', refund_service_deposit = 'refund_service_deposit', pause_request_context = 'pause_request_context', start_request_context = 'start_request_context', kill_request_context = 'kill_request_context', update_request_context = 'update_request_context', service_set_withdraw_address = 'service/set_withdraw_address', withdraw_earned_fees = 'withdraw_earned_fees', // nft burn_nft = 'burn_nft', transfer_nft = 'transfer_nft', edit_nft = 'edit_nft', issue_denom = 'issue_denom', mint_nft = 'mint_nft', // Asset issue_token = 'issue_token', edit_token = 'edit_token', mint_token = 'mint_token', transfer_token_owner = 'transfer_token_owner', burn_token = 'burn_token', //Transfer send = 'send', multisend = 'multisend', //Crisis verify_invariant = 'verify_invariant', //Evidence submit_evidence = 'submit_evidence', //Staking begin_unbonding = 'begin_unbonding', edit_validator = 'edit_validator', create_validator = 'create_validator', delegate = 'delegate', begin_redelegate = 'begin_redelegate', // Slashing unjail = 'unjail', // Distribution set_withdraw_address = 'set_withdraw_address', withdraw_delegator_reward = 'withdraw_delegator_reward', withdraw_validator_commission = 'withdraw_validator_commission', fund_community_pool = 'fund_community_pool', // Gov deposit = 'deposit', vote = 'vote', submit_proposal = 'submit_proposal', // Coinswap add_liquidity = 'add_liquidity', remove_liquidity = 'remove_liquidity', swap_order = 'swap_order', // Htlc create_htlc = 'create_htlc', claim_htlc = 'claim_htlc', refund_htlc = 'refund_htlc', // Guardian add_profiler = 'add_profiler', delete_profiler = 'delete_profiler', add_trustee = 'add_trustee', delete_trustee = 'delete_trustee', add_super = 'add_super', // Oracle create_feed = 'create_feed', start_feed = 'start_feed', pause_feed = 'pause_feed', edit_feed = 'edit_feed', // IBC transfer = 'transfer', recv_packet = 'recv_packet', create_client = 'create_client', update_client = 'update_client', timeout_packet = 'timeout_packet', acknowledge_packet = 'acknowledge_packet', // Identity create_identity = 'create_identity', update_identity = 'update_identity', // Record create_record = 'create_record', // Random request_rand = 'request_rand', } export enum IbcTxTable { IbcTxTableName = 'ex_ibc_tx', IbcTxLatestTableName = 'ex_ibc_tx_latest' } export enum TxStatus { SUCCESS = 1, FAILED = 0, } export enum IbcTxStatus { SUCCESS = 1, FAILED = 2, PROCESSING = 3, REFUNDED = 4, SETTING = 5, } export enum IbcTaskRecordStatus { OPEN = 'open', CLOSE = 'close' } export enum LoggerLevel { ALL = 'ALL', TRACE = 'TRACE', DEBUG = 'DEBUG', INFO = 'INFO', WARN = 'WARN', ERROR = 'ERROR', FATAL = 'FATAL', MARK = 'MARK', OFF = 'OFF', }
bianjieai/iobscan-ibc-explorer-backend
src/types/schemaTypes/ibc_tx.interface.ts
<gh_stars>1-10 export interface IbcTxType { record_id: string; sc_addr: string; dc_addr: string; sc_port: string; sc_channel: string; sc_chain_id: string; dc_port: string; dc_channel: string; dc_chain_id: string; sequence: string; status: number; sc_tx_info: object; dc_tx_info: object; refunded_tx_info?: object; substate: number; log: object; denoms: object; base_denom: string; create_at: string; update_at: string; tx_time: string; retry_times?: number; next_try_time?: number; } export interface IbcTxQueryType { useCount?: boolean; date_range?: number[]; chain_id?: string; status?: number[]; token?: { denom: string; chain_id: string }[]; page_num?: number; page_size?: number; } export interface AggregateResult24hr { _id:{sc_chain_id?:string,dc_chain_id?:string,sc_channel?:string,dc_channel?:string}; }
bianjieai/iobscan-ibc-explorer-backend
src/module/ibc_tx.module.ts
import { Module } from '@nestjs/common'; import { IbcTxController } from '../controller/ibc_tx.controller'; import { IbcTxService } from '../service/ibc_tx.service'; @Module({ providers: [IbcTxService], controllers: [IbcTxController], exports: [IbcTxService], }) export class IbcTxModule {}
bianjieai/iobscan-ibc-explorer-backend
src/task/ibc_denom_caculate.task.service.test.ts
import {IbcDenomCaculateTaskService} from "./ibc_denom_caculate.task.service"; import {Test} from "@nestjs/testing"; import {AppModule} from "../app.module"; describe('IbcDenomHashTaskService', () => { let ibcDenomHashTaskService: IbcDenomCaculateTaskService; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [ AppModule ] }).compile(); ibcDenomHashTaskService = module.get<IbcDenomCaculateTaskService>(IbcDenomCaculateTaskService); }) describe('findConfig', () => { it('findAllBaseDenom Test', async () => { const AllBaseDenom = await ibcDenomHashTaskService.findAllBaseDenom() console.log(AllBaseDenom,'--findAllBaseDenom--') }); it('findAllChainConfig Test', async () => { const allChains = await ibcDenomHashTaskService.findAllChainConfig() console.log(allChains,'--findAllChainConfig--') }); it('handleChain Test', async () => { await ibcDenomHashTaskService.handleChain() }); it('getCaculateDenomMap Test', async () => { const data = await ibcDenomHashTaskService.getCaculateDenomMap("sifchain_1") console.log('--data-->:',data) }); it('caculateBaseDenom Test', async () => { const chainConfig = await ibcDenomHashTaskService.findAllChainConfig() const AllBaseDenom = await ibcDenomHashTaskService.findAllBaseDenom() let denomMap = new Map, channelMap = new Map for (const one of AllBaseDenom) { denomMap.set(`${one.chain_id}`, one) } for (const one of chainConfig) { channelMap.set(`${one.chain_id}`, one) } await ibcDenomHashTaskService.caculateBaseDenom(denomMap.get("cosmoshub_4"),channelMap) }); it('findCount Test', async () => { const chainConfig = await ibcDenomHashTaskService.findAllChainConfig() let Total = 0 for (const one of chainConfig) { let num = 0 if (one?.ibc_info?.length > 0) { for (const ibcInfo of one?.ibc_info) { if (ibcInfo?.chain_id && ibcInfo?.paths?.length > 0) { ibcInfo.paths.forEach(item => { if (item?.counterparty?.port_id && item?.counterparty?.channel_id) { Total++ num++ } }) } } } console.log("chain:",one.chain_id," total:",num) } console.log('--Total-->:',Total) }); }); })
bianjieai/iobscan-ibc-explorer-backend
src/task/task.service.test.ts
import {TasksService} from "./task.service"; import {Test} from "@nestjs/testing"; import {AppModule} from "../app.module"; import {TaskEnum} from '../constant'; import {IbcMonitorService} from "../monitor/ibc_monitor.service"; describe('TasksService', () => { let taskService: TasksService; let ibcMonitorService: IbcMonitorService; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [ AppModule ] }).compile(); taskService = module.get<TasksService>(TasksService); ibcMonitorService = module.get<IbcMonitorService>(IbcMonitorService); }) describe('ibcMonitorService', () => { it('ibcMonitorService Test', async () => { await taskService.handleDoTask(TaskEnum.monitor,ibcMonitorService.doTask) console.log('----') }); }); })
bianjieai/iobscan-ibc-explorer-backend
src/schema/tx.schema.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend<filename>src/schema/tx.schema.ts import * as mongoose from 'mongoose'; export const TxSchema = new mongoose.Schema( { time: Number, height: Number, tx_hash: String, memo: String, status: Number, log: String, type: String, types: Array, signer: String, events: Array, events_new: Array, msgs: Array, signers: Array, addrs: Array, fee: Object, tx_index: Number, }, {versionKey: false}, ); TxSchema.index({'types': -1, height: -1}, {background: true}); TxSchema.index({'msgs.type': -1, status: -1}, {background: true}); TxSchema.index({'msgs.msg.packet_id': -1}, {background: true}); // txs TxSchema.statics = { async queryTxListSortHeight(query): Promise<any> { const {type, height, limit} = query; return this.find({'types': type, height: {$gte: height}}) .sort({height: 1}) .limit(Number(limit)); }, async queryTxsByPacketId(query): Promise<any> { const {type, limit, packet_id} = query; return this.find({ 'msgs.type': type, 'msgs.msg.packet_id': {$in: packet_id}, }).limit(Number(limit)); }, async queryTxListByPacketId(query): Promise<any> { const {type, limit, status, packet_id} = query; return this.find({ 'msgs.type': type, status, 'msgs.msg.packet_id': {$in: packet_id}, }).limit(Number(limit)); }, async queryTxListByHeight(type, height): Promise<any> { return this.find({'types': type, height}); }, async queryTxByHash(hash): Promise<any> { return this.find({'tx_hash': hash}); }, };
bianjieai/iobscan-ibc-explorer-backend
src/task/ibc_tx_data_update_task.service.ts
<filename>src/task/ibc_tx_data_update_task.service.ts import {Injectable, Logger} from '@nestjs/common'; import {RecordLimit, SubState, TaskEnum} from "../constant"; import {IbcTxHandler} from "../util/IbcTxHandler"; import {dateNow} from "../helper/date.helper"; import {cfg} from "../config/config"; @Injectable() export class IbcTxDataUpdateTaskService { constructor(private readonly taskCommonService: IbcTxHandler) { this.doTask = this.doTask.bind(this); } async doTask(taskName?: TaskEnum): Promise<void> { await this.handleUpdateIbcTx() } async handleUpdateIbcTx() { let pageNum = 1, handIbcTxs = [] const defaultSubstate = 0 const substate = [defaultSubstate, SubState.SuccessRecvPacketNotFound, SubState.RecvPacketAckFailed, SubState.SuccessTimeoutPacketNotFound] const ibcTxModel = this.taskCommonService.getIbcTxModel() const chainsCfg = await this.taskCommonService.getChainsCfg() // 依次遍历每条链去处理ibc_tx表中历史状态的数据 for (const chainCfg of chainsCfg) { //judge handIbcTxs size for handle batch limit while (handIbcTxs?.length < cfg.serverCfg.updateIbcTxBatchLimit) { const ibcTxs = await this.taskCommonService.getProcessingTxsByPage(chainCfg.chain_id, substate, pageNum) if (ibcTxs.length) { handIbcTxs.push(...ibcTxs) } // break when finish collect all the ibc tx. if (ibcTxs?.length < RecordLimit) { break; } pageNum++ } await this.taskCommonService.changeIbcTxState(ibcTxModel, dateNow, substate, true, handIbcTxs) Logger.log("finish update chain "+chainCfg.chain_id+ " ibc_tx processing data") } } }
bianjieai/iobscan-ibc-explorer-backend
src/types/schemaTypes/ibc_denom_hash.interface.ts
export interface IbcDenomCaculateType { chain_id: string; sc_chain_id: string; denom: string; base_denom: string; denom_path: string; create_at: string; update_at: string; }
bianjieai/iobscan-ibc-explorer-backend
src/helper/ibcTx.helper.ts
<gh_stars>1-10 /* eslint-disable @typescript-eslint/camelcase */ import { IbcTxStatus } from '../constant'; import { IbcTxQueryType } from '../types/schemaTypes/ibc_tx.interface'; interface IbcTxQueryParamsType { tx_time?: { $gte?; $lte? }; status?: number | { $in: number[] }; $and?: any[]; } const parseQuery = (query: IbcTxQueryType): IbcTxQueryParamsType => { const { chain_id, status, token, date_range } = query; const queryParams: IbcTxQueryParamsType = {}; if ((date_range && date_range[0] > 0) || (date_range && date_range[1] > 0)) { queryParams.tx_time = {}; } if (date_range && date_range[0] > 0) { queryParams.tx_time.$gte = date_range[0]; } if (date_range && date_range[1] > 0) { queryParams.tx_time.$lte = date_range[1]; } if (chain_id || token) { queryParams.$and = []; } if (chain_id) { const $or = []; $or.push({ sc_chain_id: chain_id }); $or.push({ dc_chain_id: chain_id }); queryParams.$and.push({ $or }); } if (token && token.length) { const $or = []; if (token[0] && typeof token[0] === 'string') { $or.push({ 'denoms.sc_denom': { $in: token } }); $or.push({ 'denoms.dc_denom': { $in: token } }); } else { const sc_or = { $or: token.map(item => { return { 'denoms.sc_denom': item.denom, sc_chain_id: item.chain_id, }; }), }; const dc_or = { $or: token.map(item => { return { 'denoms.dc_denom': item.denom, dc_chain_id: item.chain_id, }; }), }; $or.push(sc_or, dc_or); } queryParams.$and.push({ $or }); } if (status) { queryParams.status = { $in: status, }; } else { queryParams.status = { $in: [ IbcTxStatus.SUCCESS, IbcTxStatus.FAILED, IbcTxStatus.PROCESSING, IbcTxStatus.REFUNDED, ], }; } return queryParams; }; export { parseQuery };
bianjieai/iobscan-ibc-explorer-backend
src/controller/ibc_statistics.controller.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend import { Controller, Get, Query } from '@nestjs/common'; import { ApiTags } from '@nestjs/swagger'; import { Result } from '../api/ApiResult'; import { IbcStatisticsService } from '../service/ibc_statistics.service'; import { IbcStatisticsResDto } from '../dto/ibc_statistics.dto'; @ApiTags('IbcStatistics') @Controller('ibc') export class IbcStatisticsController { constructor(private readonly ibcStatisticsService: IbcStatisticsService) {} @Get('statistics') async getAllRecord(): Promise<Result<IbcStatisticsResDto[]>> { const result: IbcStatisticsResDto[] = await this.ibcStatisticsService.findAllRecord(); return new Result(result); } }
bianjieai/iobscan-ibc-explorer-backend
src/dto/ibc_chain.dto.ts
<filename>src/dto/ibc_chain.dto.ts import {IbcChainConfigType} from '../types/schemaTypes/ibc_chain_config.interface'; import {BaseResDto} from './base.dto'; export class IbcChainResDto extends BaseResDto { chain_id: string; chain_name: string; icon: string; constructor(value) { super(); const {chain_id, chain_name, icon} = value; this.chain_id = chain_id; this.chain_name = chain_name; this.icon = icon; } static bundleData(value: any): IbcChainResDto[] { const datasSortChars = value.filter( (item: IbcChainConfigType) => { const sASC = item.chain_name.charCodeAt(0); return (sASC >= 65 && sASC <= 90) || (sASC >= 97 && sASC <= 122); }, ); const datasSortOthers = value.filter( (item: IbcChainConfigType) => { const sASC = item.chain_name.charCodeAt(0); return sASC < 65 || (90 < sASC && sASC < 97) || sASC > 122; }, ); const datas: IbcChainResDto[] = [...datasSortChars, ...datasSortOthers].map( (item: IbcChainConfigType) => { return new IbcChainResDto(item); }, ); return datas; } } export class IbcChainResultResDto { all: IbcChainResDto[]; active: IbcChainResDto[]; inactive: IbcChainResDto[]; constructor(value) { const {all, active, inactive} = value; this.all = all || []; this.active = active || []; this.inactive = inactive || []; } }
bianjieai/iobscan-ibc-explorer-backend
src/types/schemaTypes/ibc_block.interface.ts
<gh_stars>1-10 export interface IbcBlockType { height: number, hash: string, txn: number, time: number, proposer: string, }
bianjieai/iobscan-ibc-explorer-backend
src/controller/ibc_base_denom.controller.ts
import {Body, Controller,Headers, Get, Post} from '@nestjs/common'; import {ApiTags} from '@nestjs/swagger'; import { Result } from '../api/ApiResult'; import { IbcBaseDenomService } from '../service/ibc_base_denom.service'; import { IbcBaseDenomResDto } from '../dto/ibc_base_denom.dto'; import {IbcBaseDenomDto} from "../types/schemaTypes/ibc_base_denom.interface"; import {cfg} from '../config/config'; @ApiTags('IbcBaseDenoms') @Controller('ibc') export class IbcBaseDenomController { constructor(private readonly ibcBaseDenomService: IbcBaseDenomService) {} @Get('baseDenoms') async getAllRecord(): Promise<Result<IbcBaseDenomResDto[]>> { const result: IbcBaseDenomResDto[] = await this.ibcBaseDenomService.findAllRecord(); return new Result<IbcBaseDenomResDto[]>(result); } @Post("baseDenoms") async insertIbcDenom(@Body() dto:IbcBaseDenomDto, @Headers() Headers):Promise<any> { const {executekey} = Headers if (executekey !== cfg.serverCfg.executeKey || !executekey) { return {"message":"deny this operation for executekey is not right."} } return await this.ibcBaseDenomService.insertBaseDenom(dto) } }
bianjieai/iobscan-ibc-explorer-backend
src/types/lcd.interface.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend export interface LcdChannelType { state: string; counterparty: { port_id: string; channel_id: string; }; ordering: string; connection_hops: string[]; port_id: string; channel_id: string; version: string; } export interface DenomType { path: string; base_denom: string; } export interface LcdChannelClientState{ identified_client_state: { client_id: string; client_state: { chain_id: string; } } } export interface NodeInfoType { node_info: { network:string; version:string; listen_addr: string; } }
bianjieai/iobscan-ibc-explorer-backend
src/service/ibc_tx.service.ts
<filename>src/service/ibc_tx.service.ts /* eslint-disable @typescript-eslint/camelcase */ import {Injectable, Logger} from '@nestjs/common'; import {Connection} from 'mongoose'; import {InjectConnection} from '@nestjs/mongoose'; import {ListStruct, Result} from '../api/ApiResult'; import {IbcTxDetailsResDto, IbcTxListReqDto, IbcTxResDto, TxWithHashReqDto} from '../dto/ibc_tx.dto'; import {IbcDenomSchema} from '../schema/ibc_denom.schema'; import {IbcBaseDenomSchema} from '../schema/ibc_base_denom.schema'; import {IbcTxSchema} from '../schema/ibc_tx.schema'; import {unAuth, TaskEnum, IbcTxTable, TxType,} from '../constant'; import {cfg} from '../config/config'; import {IbcTxQueryType, IbcTxType} from "../types/schemaTypes/ibc_tx.interface"; import {IbcStatisticsSchema} from "../schema/ibc_statistics.schema"; import {TxSchema} from "../schema/tx.schema"; @Injectable() export class IbcTxService { private ibcDenomModel; private ibcBaseDenomModel; private ibcTxLatestModel; private ibcTxModel; private ibcStatisticsModel; constructor(@InjectConnection() private connection: Connection) { this.getModels(); } async getModels(): Promise<void> { this.ibcTxLatestModel = await this.connection.model( 'ibcTxLatestModel', IbcTxSchema, IbcTxTable.IbcTxLatestTableName, ); this.ibcTxModel = await this.connection.model( 'ibcTxModel', IbcTxSchema, IbcTxTable.IbcTxTableName, ); this.ibcDenomModel = await this.connection.model( 'ibcDenomModel', IbcDenomSchema, 'ibc_denom', ); this.ibcBaseDenomModel = await this.connection.model( 'ibcBaseDenomModel', IbcBaseDenomSchema, 'ibc_base_denom', ); // ibcStatisticsModel this.ibcStatisticsModel = await this.connection.model( 'ibcStatisticsModel', IbcStatisticsSchema, 'ibc_statistics', ); } async getStartTxTime(): Promise<number> { const startTx = await this.ibcTxLatestModel.findFirstTx() return startTx?.tx_time; } async getTxCount(query: IbcTxQueryType, token): Promise<number> { const count = await this.ibcTxLatestModel.countTxList({...query, token}); if (count >= cfg.serverCfg.displayIbcRecordMax) { return cfg.serverCfg.displayIbcRecordMax } return count } async getIbcTxs(query: IbcTxQueryType, token): Promise<IbcTxType[]> { return await this.ibcTxLatestModel.findTxList({...query, token}) } async findStatisticTxsCount(): Promise<number> { const statisticData = await this.ibcStatisticsModel.findStatisticsRecord( TaskEnum.staticsTxAll, ); if (statisticData.count_latest >= cfg.serverCfg.displayIbcRecordMax) { return cfg.serverCfg.displayIbcRecordMax } return statisticData.count_latest } async getTokenBySymbol(symbol): Promise<any> { const result = await this.ibcDenomModel.findRecordBySymbol(symbol); return result.map(item => { return { denom: item.denom, base_denom: item.base_denom, chain_id: item.chain_id }; }); } async getBaseDenomMap() : Promise<any>{ let baseDenomMap = new Map const baseDenom = await this.ibcBaseDenomModel.findAllRecord() if (baseDenom?.length) { for (const item of baseDenom) { baseDenomMap.set(`${item?.denom}`,item?.symbol) } } return baseDenomMap } async queryIbcTxList( query: IbcTxListReqDto, ): Promise<ListStruct<IbcTxResDto[]> | number> { const {use_count, page_num, page_size, symbol, denom, start_time} = query; const date_range = query?.date_range?.split(",") || [0, new Date().getTime() / 1000], status = query?.status?.split(",") || [1, 2, 3, 4] let queryData: IbcTxQueryType = { useCount: query.use_count, date_range: [], chain_id: query.chain_id, status: [], // token?: { denom: string; chain_id: string }[]; page_num: page_num, page_size: page_size > cfg.serverCfg.maxPageSize ? cfg.serverCfg.maxPageSize : page_size, } for (const one of date_range) { queryData?.date_range.push(Number(one)) } for (const one of status) { queryData?.status.push(Number(one)) } let token = undefined; if (symbol === unAuth) { token = await this.getTokenBySymbol('') // filter token which base_denom exist in ibc_base_denom if (token.length) { const baseDenomMap = await this.getBaseDenomMap() let tokensFilter = [] for (const one of token) { //only push token which base_denom not in ibc_base_denom if (baseDenomMap && !baseDenomMap?.has(`${one?.base_denom}`)) { tokensFilter.push(one) } } if (tokensFilter?.length) { token = [...tokensFilter] } } } else if (symbol) { token = await this.getTokenBySymbol(symbol) } if (denom) { token = [denom]; } if (start_time) { // const startTx = await this.ibcTxModel.findFirstTx() // return startTx?.tx_time; //todo this value get by setting data return await this.getStartTxTime(); } if (use_count) { if (query.symbol || query.chain_id || query.denom || (!queryData.date_range.includes(0)) || (queryData.status?.length !== 4)) { return await this.getTxCount(queryData, token) } // get statistic data return await this.findStatisticTxsCount() // return await this.ibcTxModel.countTxList({...query, token}); } else { const ibcTxDatas: IbcTxResDto[] = IbcTxResDto.bundleData( // await this.ibcTxModel.findTxList({...query, token}), await this.getIbcTxs(queryData, token), ); return new ListStruct(ibcTxDatas, page_num, page_size); } }; async getConnectByTransferEventNews(eventNews,txMsgIndex) { let connect = '', timeout_timestamp = '' if (eventNews?.events_new?.length) { eventNews.events_new.forEach(item => { if (item?.events?.length && item?.msg_index === txMsgIndex) { item.events.forEach(event => { if (event?.type === 'send_packet') { if (event?.attributes?.length) { event.attributes.forEach(attribute => { switch (attribute.key) { case 'packet_connection': connect = attribute.value break case 'packet_timeout_timestamp': timeout_timestamp = attribute.value break } }) } } }) } }) } return {connect, timeout_timestamp} } async getConnectByRecvPacketEventsNews(eventNews,txMsgIndex) { let connect = '', ackData = '' if (eventNews?.events_new?.length) { eventNews.events_new.forEach(item => { if (item?.events?.length && item?.msg_index === txMsgIndex) { item.events.forEach(event => { if (event?.type === 'write_acknowledgement' || event?.type === 'recv_packet') { if (event?.attributes?.length) { event.attributes.forEach(attribute => { switch (attribute.key) { case 'packet_connection': connect = attribute.value break case 'packet_ack': ackData = attribute.value break } }) } } }) } }) } return {connect, ackData} } async getMsgIndex(tx,txType,packetId) :Promise<number>{ for (const index in tx?.msgs) { if (tx?.msgs[index]?.type === txType && tx?.msgs[index]?.msg?.packet_id === packetId){ return Number(index) } } return -1 } async getScTxInfo(scChainID, scTxHash,packetId) { let scSigners = null, scConnect = null, timeOutTimestamp = null; if (scChainID && scTxHash) { const txModel = await this.connection.model( 'txModel', TxSchema, `sync_${scChainID}_tx`, ); let scTxData = await txModel.queryTxByHash(scTxHash) if (scTxData?.length) { const scTx = scTxData[scTxData?.length - 1] scSigners = scTx?.signers if (scTx?.events_new) { const txMsgIndex = await this.getMsgIndex(scTx,TxType.transfer, packetId) const {connect, timeout_timestamp} = await this.getConnectByTransferEventNews(scTx,txMsgIndex) scConnect = connect timeOutTimestamp = timeout_timestamp } } } return { scSigners, scConnect, timeOutTimestamp, } } async getDcTxInfo(dcChainID, dcTxHash, packetId) { let ack = null, dcConnect = null; if (dcChainID && dcTxHash) { const txModel = await this.connection.model( 'txModel', TxSchema, `sync_${dcChainID}_tx`, ); let dcTxData = await txModel.queryTxByHash(dcTxHash) if (dcTxData?.length) { const dcTx = dcTxData[dcTxData?.length - 1] if (dcTx?.events_new){ const txMsgIndex = await this.getMsgIndex(dcTx,TxType.recv_packet, packetId) const {connect, ackData} = await this.getConnectByRecvPacketEventsNews(dcTx,txMsgIndex); dcConnect = connect ack = ackData } } } return { ack, dcConnect } } async getIbcTxDetail(txHash) { let ibcTx = await this.ibcTxLatestModel.queryTxDetailByHash(txHash) if (ibcTx.length === 0) { ibcTx = await this.ibcTxModel.queryTxDetailByHash(txHash) } let ibcTxDetail = [],setMap = new Map for (const one of ibcTx) { if (setMap.has(one.record_id)) { continue } ibcTxDetail.push(one) setMap.set(one.record_id,'') } return ibcTxDetail } async getTxInfo(tx) { const packetId = `${tx.sc_port}${tx.sc_channel}${tx.dc_port}${tx.dc_channel}${tx.sequence}` if (tx.sc_chain_id && tx?.sc_tx_info?.hash) { const {scSigners, scConnect} = await this.getScTxInfo(tx.sc_chain_id, tx?.sc_tx_info?.hash, packetId) if (scSigners) { tx.sc_signers = scSigners } if (scConnect) { tx.sc_connect = scConnect } } if (tx.dc_chain_id && tx?.dc_tx_info?.hash) { const {ack, dcConnect} = await this.getDcTxInfo(tx.dc_chain_id, tx?.dc_tx_info?.hash, packetId) if (ack) { tx.dc_tx_info.ack = ack } if (dcConnect) { tx.dc_connect = dcConnect } } return tx } async queryIbcTxDetailsByHash(query: TxWithHashReqDto): Promise<IbcTxDetailsResDto[]> { let txDetailsData = await this.getIbcTxDetail(query) //todo not support detail return many data currently if (txDetailsData.length > 1) { return [] } for (let tx of txDetailsData) { tx = await this.getTxInfo(tx) tx.dc_signers = [] if (tx?.dc_tx_info?.msg?.msg?.signer) { tx.dc_signers.push(tx?.dc_tx_info?.msg?.msg?.signer) } } return IbcTxDetailsResDto.bundleData( txDetailsData, ); } }
bianjieai/iobscan-ibc-explorer-backend
src/util/ibcTxHandler.test.ts
// @ts-ignore import {IbcTxHandler} from "../util/IbcTxHandler"; import {Test} from "@nestjs/testing"; import {AppModule} from "../app.module"; describe('IbcTxHandler', () => { let ibcTxHandler: IbcTxHandler; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [ AppModule ] }).compile(); ibcTxHandler = module.get<IbcTxHandler>(IbcTxHandler); }) describe('parseIbcTx', () => { it('parseIbcTxBychain Test', async () => { const dateNow = new Date().getTime() / 1000; const txmodel = await ibcTxHandler.getIbcTxModel() await ibcTxHandler.parseIbcTx(txmodel,dateNow) console.log('----') }); }); describe('getRecordLimitTx', () => { it('getRecordLimitTx Test', async () => { let chain_id = "emoney_3" const result = await ibcTxHandler.getRecordLimitTx(chain_id,13106,10) console.log(result,'----') }); }); describe('checkTaskFollowingStatus', () => { it('checkTaskFollowingStatus Test', async () => { let chain_id = "irishub-test" const result = await ibcTxHandler.checkTaskFollowingStatus(chain_id) console.log(result,'-checkTaskFollowingStatus---') }); }); describe('handlerSourcesTx', () => { it('handlerSourcesTx Test', async () => { let chain_id = "osmosis_1" const txs = await ibcTxHandler.getRecordLimitTx(chain_id,1858626,10) const {allChainsMap,allChainsDenomPathsMap} = await ibcTxHandler.getAllChainsMap() const dateNow = Math.floor(new Date().getTime() / 1000); let denomMap = await ibcTxHandler.getDenomRecordByChainId(chain_id) const {handledTx,denoms} = await ibcTxHandler.handlerSourcesTx(txs,chain_id,dateNow,allChainsMap,allChainsDenomPathsMap,denomMap) console.log(handledTx,'--ibcTxs--') console.log(denoms,'--denoms--') }); }); describe('changeIbcTxState', () => { it('changeIbcTxState Test', async () => { const dateNow = Math.floor(new Date().getTime() / 1000); jest.setTimeout(100000000) const txmodel = await ibcTxHandler.getIbcTxLatestModel() await ibcTxHandler.changeIbcTxState(txmodel,dateNow,[3],false,[]) return null }); }); describe('getDenomRecordByChainId', () => { it('getDenomRecordByChainId Test', async () => { let data = await ibcTxHandler.getDenomRecordByChainId("osmosis_1") console.log(data,":<==============") return null }); }); describe('getProcessingTxs', () => { it('getProcessingTxs Test', async () => { jest.setTimeout(100000000) const txmodel = ibcTxHandler.getIbcTxModel() const ibcTxs = await ibcTxHandler.getProcessingTxs(txmodel,0) console.log(ibcTxs,'--ibcTxs--') let packetIdArr = ibcTxs?.length ? await ibcTxHandler.getPacketIds(ibcTxs) : []; console.log(packetIdArr,'--packetIdArr--') return null }); }); })
bianjieai/iobscan-ibc-explorer-backend
src/module/ibc_tx_latest_migrate_task.module.ts
import { Module } from '@nestjs/common'; import {IbcTxLatestMigrateTaskService} from "../task/ibc_tx_latest_migrate_task.service"; @Module({ providers: [IbcTxLatestMigrateTaskService], exports: [IbcTxLatestMigrateTaskService], }) export class IbcTxLatestMigrateTaskModule {}
bianjieai/iobscan-ibc-explorer-backend
src/schema/ibc_block.schema.ts
import * as mongoose from 'mongoose'; import { IbcBlockType } from '../types/schemaTypes/ibc_block.interface'; export const IbcBlockSchema = new mongoose.Schema( { height: Number, hash: String, txn: Number, time: Number, proposer: String, }, { versionKey: false }, ); IbcBlockSchema.statics = { async findLatestBlock(): Promise<IbcBlockType> { return this.findOne() .sort({ height: -1 }) }, };
bianjieai/iobscan-ibc-explorer-backend
src/dto/ibc_tx.dto.ts
<gh_stars>1-10 /* eslint-disable @typescript-eslint/camelcase */ import {BaseReqDto, PagingReqDto} from './base.dto'; import {ApiPropertyOptional} from '@nestjs/swagger'; import {BaseResDto} from './base.dto'; export class IbcTxListReqDto extends PagingReqDto { @ApiPropertyOptional() date_range?: string; @ApiPropertyOptional() status?: string; @ApiPropertyOptional() chain_id?: string; @ApiPropertyOptional() symbol?: string; @ApiPropertyOptional() denom?: string; @ApiPropertyOptional() page_num?: number; @ApiPropertyOptional() page_size?: number; @ApiPropertyOptional() start_time?: boolean static convert(value: any): any { return super.convert(value); } } export class TxWithHashReqDto extends BaseReqDto { @ApiPropertyOptional() hash: string; } export class IbcTxDetailsResDto extends BaseResDto{ base_denom: string; sc_signers:string[]; dc_signers:string[]; dc_addr: string; dc_chain_id: string; dc_channel: string; dc_port: string; denoms: object; sc_addr: string; sc_chain_id: string; sc_channel: string; sc_port: string; sc_tx_info: object; sequence: string; status: string; tx_time: string; dc_tx_info:object; dc_connect:string; sc_connect:string; constructor(value: any) { super(); const { base_denom, dc_addr, dc_chain_id, dc_channel, dc_port, denoms, sc_addr, sc_chain_id, sc_channel, sc_port, sc_tx_info, sequence, status, tx_time, dc_tx_info, sc_signers, dc_signers, dc_connect, sc_connect, } = value; this.base_denom = base_denom || ''; this.dc_addr = dc_addr || ''; this.dc_chain_id = dc_chain_id || ''; this.dc_channel = dc_channel; this.dc_port = dc_port || ''; this.denoms = denoms || ''; this.sc_addr = sc_addr || ''; this.sc_chain_id = sc_chain_id || ''; this.sc_channel = sc_channel || ''; this.sc_port = sc_port || []; this.sc_tx_info = sc_tx_info || {}; this.sequence = sequence || ''; this.status = status || ''; this.tx_time = tx_time || ''; this.dc_tx_info = dc_tx_info || {}; this.sc_signers = sc_signers || []; this.dc_signers = dc_signers || []; this.dc_connect = dc_connect || ''; this.sc_connect = sc_connect || ''; } static bundleData(value: any): IbcTxDetailsResDto[] { const datas: IbcTxDetailsResDto[] = value.map((item: any) => { return new IbcTxDetailsResDto(item); }); return datas; } } export class IbcTxResDto extends BaseResDto { record_id: string; sc_addr: string; dc_addr: string; status: number; sc_chain_id: string; dc_chain_id: string; dc_channel: string; sc_channel: string; sequence: string; sc_tx_info: object; dc_tx_info?: object; base_denom: string; denoms: string[]; create_at: string; tx_time: string; constructor(value: any) { super(); const { record_id, sc_addr, dc_addr, dc_chain_id, sc_chain_id, status, dc_channel, sc_channel, sequence, sc_tx_info, dc_tx_info, base_denom, denoms, create_at, tx_time, } = value; this.record_id = record_id || ''; this.sc_addr = sc_addr || ''; this.dc_addr = dc_addr || ''; this.status = status; this.sequence = sequence || ''; this.dc_channel = dc_channel || ''; this.sc_channel = sc_channel || ''; this.sc_chain_id = sc_chain_id || ''; this.dc_chain_id = dc_chain_id || ''; this.sc_tx_info = sc_tx_info || {}; this.dc_tx_info = dc_tx_info || {}; this.base_denom = base_denom || ''; this.denoms = denoms || []; this.create_at = create_at || ''; this.tx_time = tx_time || ''; } static bundleData(value: any): IbcTxResDto[] { const datas: IbcTxResDto[] = value.map((item: any) => { return new IbcTxResDto(item); }); return datas; } }
bianjieai/iobscan-ibc-explorer-backend
src/module/ibc_update_substate_tx_task.module.ts
<filename>src/module/ibc_update_substate_tx_task.module.ts<gh_stars>1-10 import { Module } from '@nestjs/common'; import {IbcTxHandler} from "../util/IbcTxHandler"; import {IbcUpdateSubStateTxTaskService} from "../task/ibc_update_substate_tx_task.service"; @Module({ providers: [IbcUpdateSubStateTxTaskService,IbcTxHandler], exports: [IbcUpdateSubStateTxTaskService], }) export class IbcUpdateSubstateTxTaskModule {}
bianjieai/iobscan-ibc-explorer-backend
src/module/ibc_update_processing_tx_task.module.ts
import { Module } from '@nestjs/common'; import {IbcTxHandler} from "../util/IbcTxHandler"; import {IbcUpdateProcessingTxTaskService} from "../task/ibc_update_processing_tx_task.service"; @Module({ providers: [IbcUpdateProcessingTxTaskService,IbcTxHandler], exports: [IbcUpdateProcessingTxTaskService], }) export class IbcUpdateProcessingTxModule {}
bianjieai/iobscan-ibc-explorer-backend
src/http/lcd/chain.http.test.ts
import { ChainHttp } from './chain.http'; describe('ChainHttp', () => { describe('getIbcChannels', () => { it('getIbcChannels Test', async () => { const lcdAddr = "https://cosmoshub.stakesystems.io" const lcdApiPath = {channels_path:"/ibc/core/channel/v1beta1/channels?pagination.offset=OFFSET&pagination.limit=LIMIT&pagination.count_total=true"} const result = await ChainHttp.getIbcChannels(lcdAddr,lcdApiPath.channels_path) console.log(result,'----') }); }); describe('getDenomByLcdAndHash', () => { it('getDenomByLcdAndHash Test', async () => { const lcdAddr = "https://cosmoshub.stakesystems.io",ibcHash = "EC4B5D87917DD5668D9998146F82D70FDF86652DB333D04CE29D1EB18E296AF5" const result = await ChainHttp.getDenomByLcdAndHash(lcdAddr,ibcHash) console.log(result,'----') }); }); describe('getDcChainIdByScChannel', () => { it('getDcChainIdByScChannel Test', async () => { const lcdAddr = "https://osmosis.stakesystems.io", lcdApiPath = {client_state_path:"/ibc/core/channel/v1/channels/CHANNEL/ports/PORT/client_state"} let result = await ChainHttp.getDcChainIdByScChannel(lcdAddr,lcdApiPath.client_state_path,"transfer","channel-6") result = result.replace(new RegExp("\-", "g"),"_") console.log(result,'----') }); }); })
bianjieai/iobscan-ibc-explorer-backend
src/schema/ibc_chain_config.schema.ts
import * as mongoose from 'mongoose'; import {IbcChainConfigType} from '../types/schemaTypes/ibc_chain_config.interface'; export const IbcChainConfigSchema = new mongoose.Schema({ chain_id: String, icon: String, chain_name: String, lcd: String, lcd_api_path: Object, ibc_info: Object, ibc_info_hash_lcd: String, // ibc_info_hash_caculate: String, is_manual: Boolean }); IbcChainConfigSchema.index({chain_id: 1}, {unique: true}); IbcChainConfigSchema.statics = { async findCount(query): Promise<number> { return this.count(query); }, async findAll(): Promise<IbcChainConfigType[]> { return this.find({}).sort({'chain_name': 1}); }, async findList(): Promise<IbcChainConfigType[]> { return this.find().select({ "_id": 0, 'chain_id': 1, 'chain_name': 1, 'icon': 1 }).collation({locale: 'en_US'}).sort({'chain_name': 1}); }, async updateChain(chain: IbcChainConfigType) { const {chain_id} = chain; const options = {upsert: true, new: false, setDefaultsOnInsert: true}; return this.findOneAndUpdate({chain_id}, chain, options); }, // async updateChainCfgWithSession(chain: IbcChainConfigType,session) { // const {chain_id} = chain; // const options = {session,upsert: true, new: false, setDefaultsOnInsert: true}; // return this.findOneAndUpdate({chain_id}, chain, options); // }, };
bianjieai/iobscan-ibc-explorer-backend
src/task/ibc_statistics.task.service.ts
/* eslint-disable @typescript-eslint/camelcase */ import {Injectable} from '@nestjs/common'; import {Connection} from 'mongoose'; import {InjectConnection} from '@nestjs/mongoose'; import {IbcStatisticsSchema} from '../schema/ibc_statistics.schema'; import {IbcChainConfigSchema} from '../schema/ibc_chain_config.schema'; import {IbcTxSchema} from '../schema/ibc_tx.schema'; import {IbcDenomSchema} from '../schema/ibc_denom.schema'; import {TaskEnum, StatisticsNames} from '../constant'; import {AggregateBaseDenomCnt} from "../types/schemaTypes/ibc_denom.interface"; import {AggregateResult24hr} from "../types/schemaTypes/ibc_tx.interface"; import {IbcStatisticsType} from "../types/schemaTypes/ibc_statistics.interface"; import {IbcTxTable} from "../constant/index"; @Injectable() export class IbcStatisticsTaskService { private ibcStatisticsModel; private chainConfigModel; private ibcTxModel; private ibcTxLatestModel; private ibcDenomModel; constructor(@InjectConnection() private connection: Connection) { this.getModels(); this.doTask = this.doTask.bind(this); } async doTask(taskName?: TaskEnum): Promise<void> { const dateNow = Math.floor(new Date().getTime() / 1000); this.parseIbcStatistics(dateNow); } // getModels async getModels(): Promise<void> { // ibcStatisticsModel this.ibcStatisticsModel = await this.connection.model( 'ibcStatisticsModel', IbcStatisticsSchema, 'ibc_statistics', ); // chainConfigModel this.chainConfigModel = await this.connection.model( 'chainConfigModel', IbcChainConfigSchema, 'chain_config', ); // ibcTxModel this.ibcTxModel = await this.connection.model( 'ibcTxModel', IbcTxSchema, IbcTxTable.IbcTxTableName, ); // ibcTxModel this.ibcTxLatestModel = await this.connection.model( 'ibcTxLatestModel', IbcTxSchema, IbcTxTable.IbcTxLatestTableName, ); // ibcDenomModel this.ibcDenomModel = await this.connection.model( 'ibcDenomModel', IbcDenomSchema, 'ibc_denom', ); } async aggregateFindSrcChannels(dateNow, chains: Array<string>): Promise<Array<AggregateResult24hr>> { return await this.ibcTxLatestModel.aggregateFindSrcChannels24hr(dateNow, chains); } async aggregateFindDesChannels(dateNow, chains: Array<string>): Promise<Array<AggregateResult24hr>> { return await this.ibcTxLatestModel.aggregateFindDesChannels24hr(dateNow, chains); } async updateStatisticsRecord(statisticsRecord: IbcStatisticsType) { await this.ibcStatisticsModel.updateStatisticsRecord(statisticsRecord); } async findStatisticsRecord(statistics_name: string): Promise<IbcStatisticsType> { return await this.ibcStatisticsModel.findStatisticsRecord( statistics_name, ); } async aggregateBaseDenomCnt(): Promise<Array<AggregateBaseDenomCnt>> { return await this.ibcDenomModel.findBaseDenomCount() } async getCountinfo() :Promise<any>{ // tx_all const tx_all_new = await this.ibcTxLatestModel.countAll(); let tx_all = await this.ibcTxModel.countAll(); tx_all = tx_all + tx_all_new // tx_success const tx_success_new = await this.ibcTxLatestModel.countSuccess(); let tx_success = await this.ibcTxModel.countSuccess(); tx_success = tx_success_new + tx_success // tx_failed const tx_failed_new = await this.ibcTxLatestModel.countFaild(); let tx_failed = await this.ibcTxModel.countFaild(); tx_failed = tx_failed_new + tx_failed return {tx_all_new,tx_all,tx_success,tx_failed} } // sync count async parseIbcStatistics(dateNow): Promise<void> { // chain_all const chain_all = await this.chainConfigModel.findCount(); const chain_all_record = await this.chainConfigModel.findAll(); const channels_all_record = [], chains = []; chain_all_record.forEach(chain => { chains.push(chain.chain_id) chain.ibc_info && chain.ibc_info.forEach(ibc_info_item => { ibc_info_item.paths.forEach(channel => { channels_all_record.push({ channel_id: channel.channel_id, state: channel.state, }); }); }); }); // tx_24hr_all const tx_24hr_all = await this.ibcTxLatestModel.countActive(); //sc_chain_id,sc_channel const srcinfo_24hr = await this.aggregateFindSrcChannels(dateNow, chains); //dc_chain_id,dc_channel const desinfo_24hr = await this.aggregateFindDesChannels(dateNow, chains); const chainMap = new Map(); for (const element of srcinfo_24hr) { if (chainMap.has(element._id.sc_chain_id) === false) { chainMap.set(element._id.sc_chain_id, '') } } for (const element of desinfo_24hr) { if (chainMap.has(element._id.dc_chain_id) === false) { chainMap.set(element._id.dc_chain_id, '') } } // chains_24hr_all const chains_24hr = chainMap.size; // channels_24hr const channels_24hr = srcinfo_24hr.length + desinfo_24hr.length; // channel_all const channel_all = channels_all_record.length; // channel_opened const channel_opened = channels_all_record.filter(channel => { return channel.state === 'STATE_OPEN'; }).length; // channel_closed const channel_closed = channels_all_record.filter(channel => { return channel.state === 'STATE_CLOSED'; }).length; const {tx_all_new,tx_all,tx_success,tx_failed} = await this.getCountinfo() // // tx_all // const tx_all = await ibcTxModel.countAll(); // // // tx_success // const tx_success = await ibcTxModel.countSuccess(); // // // tx_failed // const tx_failed = await ibcTxModel.countFaild(); // denom_all const denom_all = await this.ibcDenomModel.findCount(); // base_denom_all // const base_denom_all = await this.ibcBaseDenomModel.findCount(); const base_denoms = await this.aggregateBaseDenomCnt(); const base_denom_all = base_denoms.length; const parseCount = { tx_24hr_all, chains_24hr, channels_24hr, chain_all, channel_all, channel_opened, channel_closed, tx_all, tx_success, tx_failed, base_denom_all, denom_all, }; for (const statistics_name of StatisticsNames) { let statistics_info = '',count_latest=0; if ((statistics_name === 'chains_24hr') && (chainMap.size > 0)){ const chains24hr = [...chainMap.keys()] statistics_info = chains24hr.join(",") } if (statistics_name === 'tx_all'){ count_latest = Number(tx_all_new) } const statisticsRecord = await this.findStatisticsRecord( statistics_name, ); if (!statisticsRecord) { await this.ibcStatisticsModel.insertManyStatisticsRecord({ statistics_name, count: parseCount[statistics_name], count_latest, statistics_info, create_at: dateNow, update_at: dateNow, }); } else { statisticsRecord.count = parseCount[statistics_name]; statisticsRecord.update_at = dateNow; statisticsRecord.statistics_info = statistics_info statisticsRecord.count_latest = count_latest await this.updateStatisticsRecord(statisticsRecord); } } } }
bianjieai/iobscan-ibc-explorer-backend
src/task/ibc_tx_latest_migrate_task.service.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend import {Injectable} from '@nestjs/common'; import {TaskEnum, IbcTxTable, MaxMigrateBatchLimit, IbcTxStatus} from "../constant"; import {cfg} from "../config/config"; import {Connection} from 'mongoose'; import {InjectConnection} from "@nestjs/mongoose"; import {IbcTxSchema} from "../schema/ibc_tx.schema"; import {Logger} from "../logger"; @Injectable() export class IbcTxLatestMigrateTaskService { private ibcTxModel; private ibcTxLatestModel; constructor(@InjectConnection() private readonly connection: Connection) { this.getModels(); this.doTask = this.doTask.bind(this); } // getModels async getModels(): Promise<void> { // ibcTxModel this.ibcTxModel = await this.connection.model( 'ibcTxModel', IbcTxSchema, IbcTxTable.IbcTxTableName, ); // ibcTxLatestModel this.ibcTxLatestModel = await this.connection.model( 'ibcTxLatestModel', IbcTxSchema, IbcTxTable.IbcTxLatestTableName, ); } async doTask(taskName?: TaskEnum): Promise<void> { const txCount = await this.ibcTxLatestModel.countAll(); if (txCount <= cfg.serverCfg.displayIbcRecordMax) { return } const migrateCnt = txCount - cfg.serverCfg.displayIbcRecordMax await this.startMigrate(migrateCnt) Logger.log("ibc migrate have finished,migrate count:", migrateCnt) } async startMigrate(migrateCount): Promise<void> { // migrate start condition value with timestamp random const value = (Math.floor(new Date().getTime() / 1000) % 10) * 10000 if (migrateCount > value) { // migrate max bitch count limit if (migrateCount > MaxMigrateBatchLimit) { let batchNum = Math.floor(migrateCount / MaxMigrateBatchLimit) const batchSize = batchNum * MaxMigrateBatchLimit for (; batchNum > 0; batchNum--) { await this.migrateData(MaxMigrateBatchLimit) } return await this.migrateData(migrateCount - batchSize) } return await this.migrateData(migrateCount) } } // limit max value is MaxMigrateBatchLimit async migrateData(limit): Promise<void> { if (limit <= 0) { return } const settingTxs = await this.ibcTxLatestModel.queryTxsByStatusLimit({ status: IbcTxStatus.SETTING, limit: limit }) // this migrate status[1,2,3,4] txs data is (limit - settingTxs.length) let limitNormalData = 0 if (limit > settingTxs.length) { limitNormalData = limit - settingTxs.length } let batchTxs = [ ...settingTxs] if (limitNormalData > 0 ) { const Txs = await this.ibcTxLatestModel.queryTxsLimit(limitNormalData, 1) batchTxs = [...Txs] } const session = await this.connection.startSession() session.startTransaction() try { let recordIds = [] for (const one of batchTxs) { recordIds.push(one.record_id) } await this.ibcTxModel.insertManyIbcTx(batchTxs, session) await this.ibcTxLatestModel.deleteManyIbcTx(recordIds, session) await session.commitTransaction(); session.endSession(); } catch (e) { Logger.log(e, 'transaction is error') await session.abortTransaction() session.endSession(); } } }
bianjieai/iobscan-ibc-explorer-backend
src/schema/task.dispatch.schema.ts
<filename>src/schema/task.dispatch.schema.ts import * as mongoose from 'mongoose'; import { getIpAddress, getTimestamp } from '../util/util'; import { ITaskDispatchStruct } from '../types/schemaTypes/task.dispatch.interface'; import { TaskEnum } from '../constant'; import { Logger } from '../logger'; import { IRandomKey } from '../types'; import { taskLoggerHelper } from '../helper/task.log.helper'; import moment from 'moment'; export const TaskDispatchSchema = new mongoose.Schema( { name: { type: String, unique: true }, is_locked: Boolean, device_ip: String, create_time: Number, task_begin_time: Number, task_end_time: Number, heartbeat_update_time: Number, }, { versionKey: false }, ); TaskDispatchSchema.statics = { async findOneByName(name: TaskEnum): Promise<ITaskDispatchStruct | null> { return await this.findOne({ name }).exec(); }, async createOne(t: ITaskDispatchStruct): Promise<ITaskDispatchStruct | null> { return new this(t).save(); }, async lock(name: TaskEnum): Promise<boolean> { return new Promise(async res => { return await this.update( { name, is_locked: false }, { // condition: is_locked: false, those server whose query's is_locked is true should not to be updated; is_locked: true, task_begin_time: getTimestamp(), device_ip: getIpAddress(), }, null, (error, effect) => { if (error) { Logger.log(`update lock error ${error}`) res(false); return; } if (effect && effect.nModified === 1) { res(true); Logger.log( `From task.dispatch.schema ${name} task begin time: ${new Date().getTime()}`, ); } else { Logger.log(`update lock number ${effect.nModified}`) res(true); } }, ).exec(); }); }, async unlock(name: TaskEnum, randomKey?: IRandomKey): Promise<boolean> { return new Promise(async res => { //console.log('before updated unlock:',await this.find({ name})) return await this.update( { name, is_locked: true }, { is_locked: false, task_end_time: getTimestamp(), }, null, (error, effect) => { if (error) { taskLoggerHelper(`${name}: unlock error`, randomKey); res(false); return; } //TODO(lvshenchao) it seems like that there is a bug in mongoose, the params of nModified returned 0 while record was be updated // console.log('updated unlock:',effect); //console.log('updated unlock:',await this.find({ name})) if (effect && effect.nModified === 1) { taskLoggerHelper( `${name}: unlock successful, From task.dispatch.schema ${name} task end time: ${new Date().getTime()}`, randomKey, ); res(true); } else { taskLoggerHelper(`${name}: unlock failed`, randomKey); res(false); } }, ).exec(); }); }, async releaseLockByName(name: TaskEnum): Promise<ITaskDispatchStruct | null> { return await this.updateOne( { name, is_locked: true, }, { is_locked: false, }, ).exec(); }, async findAllLocked(): Promise<ITaskDispatchStruct[]> { return await this.find({ is_locked: true }).exec(); }, async updateHeartbeatUpdateTime( name: TaskEnum, randomKey?: IRandomKey, ): Promise<ITaskDispatchStruct | null> { if (randomKey) { taskLoggerHelper(`${name}: update hearbeat time`, randomKey); } else { //定时任务打印的日志, 不需要对step递增 Logger.log( `${name}: update hearbeat time: ${moment(new Date().getTime()).format( 'YYYY-MM-DD HH:mm:ss', )}`, ); } return await this.updateOne( { name, is_locked: true }, { heartbeat_update_time: getTimestamp(), }, ).exec(); }, async deleteOneByName(name: TaskEnum) { await this.deleteOne({ name: name }); }, };
bianjieai/iobscan-ibc-explorer-backend
src/module/ibc_chain.module.ts
<filename>src/module/ibc_chain.module.ts<gh_stars>1-10 import {Module} from '@nestjs/common'; import {IbcChainController} from '../controller/ibc_chain.controller'; import {IbcChainService} from '../service/ibc_chain.service'; @Module({ providers: [IbcChainService], controllers: [IbcChainController], }) export class IbcChainModule { }
bianjieai/iobscan-ibc-explorer-backend
src/dto/base.dto.ts
/* eslint-disable @typescript-eslint/no-empty-function */ /* eslint-disable @typescript-eslint/camelcase */ import { IsOptional } from 'class-validator'; import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { ApiError } from '../api/ApiResult'; import { ErrorCodes } from '../api/ResultCodes'; import { DefaultPaging } from '../constant'; //base request dto export class BaseReqDto { static validate(value: any): void {} static convert(value: any): any { return value; } } // base response dto export class BaseResDto { static bundleData(value: any): any { return value; } } //base Paging request Dto export class PagingReqDto extends BaseReqDto { @ApiPropertyOptional() @IsOptional() page_num?: number; @ApiPropertyOptional() @IsOptional() page_size?: number; @ApiPropertyOptional({ description: 'true/false' }) @IsOptional() use_count?: boolean; static validate(value: any): void { const patt = /^[1-9]\d*$/; if (value.pageNum && (!patt.test(value.pageNum) || value.pageNum < 1)) { throw new ApiError( ErrorCodes.InvalidParameter, 'The pageNum must be a positive integer greater than 0', ); } if (value.pageSize && (!patt.test(value.pageSize) || value.pageNum < 1)) { throw new ApiError( ErrorCodes.InvalidParameter, 'The pageSize must be a positive integer greater than 0', ); } } static convert(value: any): any { if (!value.pageNum) { value.pageNum = DefaultPaging.pageNum; } if (!value.pageSize) { value.pageSize = DefaultPaging.pageSize; } if (!value.use_count) { value.use_count = false; } else { if (value.use_count === 'true') { value.use_count = true; } else { value.use_count = false; } } value.pageNum = Number(value.pageNum); value.pageSize = Number(value.pageSize); return value; } }
bianjieai/iobscan-ibc-explorer-backend
src/module/ibc_denom.module.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend import { Module } from '@nestjs/common'; import { IbcDenomController } from '../controller/ibc_denom.controller'; import { IbcDenomService } from '../service/ibc_denom.service'; @Module({ providers: [IbcDenomService], controllers: [IbcDenomController], }) export class IbcDenomModule {}
bianjieai/iobscan-ibc-explorer-backend
src/task/ibc_denom_update.task.service.test.ts
<gh_stars>1-10 import {Test} from "@nestjs/testing"; import {AppModule} from "../app.module"; import {IbcDenomUpdateTaskService} from "./ibc_denom_update.task.service"; describe('IbcDenomUpdateTaskService', () => { let ibcDenomUpdateTaskService: IbcDenomUpdateTaskService; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [ AppModule ] }).compile(); ibcDenomUpdateTaskService = module.get<IbcDenomUpdateTaskService>(IbcDenomUpdateTaskService); }) describe('Uint Test', () => { it('getEmptySymbolDenom Test', async () => { jest.setTimeout(100000000) const AllDenom = await ibcDenomUpdateTaskService.getNeedhandleIbcDenoms(1,100) const ret = await ibcDenomUpdateTaskService.collectChainDenomsMap(AllDenom) console.log(ret,'--ret--') }); it('getNeedhandleIbcDenoms Test', async () => { jest.setTimeout(100000000) const AllDenom = await ibcDenomUpdateTaskService.getNeedhandleIbcDenoms(1,100) console.log(AllDenom,'--AllDenom--') }); it('handleChainDenoms Test', async () => { jest.setTimeout(100000000) await ibcDenomUpdateTaskService.handleChainDenoms() }); it('handleChain Test', async () => { const ret = await ibcDenomUpdateTaskService.getIbcDenoms("bigbang",["ibc/FD01DE9421BAC4DA062DF60B0750248026D1EA64C7990A4BB58D91EC2BBEAB56","ibc/4BAD958A5FF565DEADCF82F5B5D95B823EE9A7796683D3CCFE31A761BF931513"]) console.log(ret,"====ret===") }); }); })
bianjieai/iobscan-ibc-explorer-backend
src/constant/dbRes.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend export const dbRes = { txList:{ record_id:1, base_denom:1, dc_addr:1, 'dc_tx_info.hash':1, dc_chain_id:1, sc_chain_id:1, sc_channel:1, dc_channel:1, sequence:1, denoms:1, sc_addr:1, 'sc_tx_info.hash':1, tx_time:1, status:1, 'sc_tx_info.msg_amount':1, } }
bianjieai/iobscan-ibc-explorer-backend
src/schema/ibc_tx.schema.ts
/* eslint-disable @typescript-eslint/camelcase */ import * as mongoose from 'mongoose'; import {AggregateResult24hr, IbcTxQueryType, IbcTxType,} from '../types/schemaTypes/ibc_tx.interface'; import {parseQuery} from '../helper/ibcTx.helper'; import {IbcTxStatus, SubState, TxStatus} from '../constant'; import {dbRes} from "../constant/dbRes"; export const IbcTxSchema = new mongoose.Schema({ record_id: String, sc_addr: String, dc_addr: String, sc_port: String, sc_channel: String, sc_chain_id: String, dc_port: String, dc_channel: String, dc_chain_id: String, sequence: String, status: Number, sc_tx_info: Object, dc_tx_info: Object, refunded_tx_info: Object, log: { sc_log: String, dc_log: String, }, substate: Number, denoms: { sc_denom: String, dc_denom: String, }, base_denom: String, create_at: { type: Number, default: Math.floor(new Date().getTime() / 1000), }, update_at: { type: Number, default: Math.floor(new Date().getTime() / 1000), }, tx_time: { type: Number, default: Math.floor(new Date().getTime() / 1000), }, retry_times:{ type: Number, default: 0, }, next_try_time:{ type:Number, default:0 } }); IbcTxSchema.index({record_id: -1}, {unique: true}); IbcTxSchema.index({substate:-1, status: -1, next_retry_time:-1}, {background: true}); IbcTxSchema.index({status: -1, tx_time: -1}, {background: true}); IbcTxSchema.index({sc_chain_id: -1}, {background: true}); IbcTxSchema.index({dc_chain_id: -1}, {background: true}); IbcTxSchema.index({'denoms.sc_denom': -1, sc_chain_id: -1}, {background: true}); IbcTxSchema.index({'denoms.dc_denom': -1, dc_chain_id: -1}, {background: true}); IbcTxSchema.index({'sc_tx_info.hash': -1}, {background: true}); IbcTxSchema.index({'dc_tx_info.hash': -1}, {background: true}); IbcTxSchema.statics = { async countActive(): Promise<number> { return this.count({ tx_time: {$gte: Math.floor(new Date().getTime() / 1000) - 24 * 60 * 60}, status: { $in: [ IbcTxStatus.SUCCESS, IbcTxStatus.FAILED, IbcTxStatus.PROCESSING, IbcTxStatus.REFUNDED, ], }, }); }, async countAll(): Promise<number> { return this.count({ status: { $in: [ IbcTxStatus.SUCCESS, IbcTxStatus.FAILED, IbcTxStatus.PROCESSING, IbcTxStatus.REFUNDED, ], }, }); }, async findActiveChains24hr(dateNow: any): Promise<Array<AggregateResult24hr>> { return this.aggregate([ { $match: { tx_time: {$gte: dateNow - 24 * 60 * 60}, status: { $in: [ IbcTxStatus.SUCCESS, IbcTxStatus.FAILED, IbcTxStatus.PROCESSING, IbcTxStatus.REFUNDED, ], } } }, { $group: { _id: {sc_chain_id: "$sc_chain_id", dc_chain_id: "$dc_chain_id"} } }]); }, async aggregateFindSrcChannels24hr(dateNow: any, chains: Array<string>): Promise<Array<AggregateResult24hr>> { return this.aggregate([ { $match: { sc_chain_id: {$in: chains}, tx_time: {$gte: dateNow - 24 * 60 * 60}, status: { $in: [ IbcTxStatus.SUCCESS, IbcTxStatus.FAILED, IbcTxStatus.PROCESSING, IbcTxStatus.REFUNDED, ], }, "sc_tx_info.status": 1 } }, { $group: { _id: {sc_channel: "$sc_channel", sc_chain_id: "$sc_chain_id"} } }]); }, async aggregateFindDesChannels24hr(dateNow: any, chains: Array<string>): Promise<Array<AggregateResult24hr>> { return this.aggregate([ { $match: { dc_chain_id: {$in: chains}, tx_time: {$gte: dateNow - 24 * 60 * 60}, $or: [ {status: IbcTxStatus.SUCCESS}, {status: IbcTxStatus.PROCESSING, substate: SubState.RecvPacketAckFailed}, {status: IbcTxStatus.FAILED, "dc_tx_info.status":TxStatus.SUCCESS}, ], } }, { $group: { _id: {dc_channel: "$dc_channel", dc_chain_id: "$dc_chain_id"}, } }]); }, async countSuccess(): Promise<number> { return this.count({ status: IbcTxStatus.SUCCESS, }); }, async countProcessing(): Promise<number> { return this.count({ status: IbcTxStatus.PROCESSING, }); }, async countFaild(): Promise<number> { return this.count({ status: {$in: [IbcTxStatus.FAILED, IbcTxStatus.REFUNDED]}, }); }, async countTxList(query: IbcTxQueryType): Promise<number> { const queryParams = parseQuery(query); return this.count(queryParams); }, async findTxList(query: IbcTxQueryType): Promise<IbcTxType[]> { const queryParams = parseQuery(query); const {page_num, page_size} = query; return this.find(queryParams, dbRes.txList) .skip((Number(page_num) - 1) * Number(page_size)) .limit(Number(page_size)) .sort({tx_time: -1}); }, async findFirstTx(): Promise<IbcTxType> { return this.findOne().sort({tx_time: 1}) }, async queryTxByRecordId(record_id): Promise<IbcTxType[]> { return this.find({record_id}, {_id: 0}) .sort({tx_time: 1}) .limit(Number(1)); }, async queryTxsByStatusLimit(query): Promise<IbcTxType[]> { const {status,limit} = query; return this.find({status: status}, {_id: 0}) .sort({tx_time: 1}) .limit(Number(limit)); }, async queryTxsLimit(limit:number,sort:number): Promise<IbcTxType[]> { return this.find({ status: { $in: [ IbcTxStatus.SUCCESS, IbcTxStatus.FAILED, IbcTxStatus.PROCESSING, IbcTxStatus.REFUNDED, ], }}, {_id: 0}) .sort({tx_time: sort}) .limit(Number(limit)); }, async queryTxList(query): Promise<IbcTxType[]> { const {status,substate,limit} = query; return this.find({status,substate:{$in:substate}}, {_id: 0}) .sort({tx_time: 1}) .limit(Number(limit)); }, async queryTxListBySubstate(query):Promise<IbcTxType[]> { const {status,substate,limit} = query; return this.find({status,substate:{$in:substate}}, {_id: 0}) .sort({next_retry_time: 1}) .limit(Number(limit)); }, async queryTxListByPage(query):Promise<IbcTxType[]> { const {sc_chain_id,status,substate,page,limit} = query; return this.find({sc_chain_id,status,substate:{$in:substate}}, {_id: 0}) .skip((Number(page) - 1) * Number(limit)) .limit(Number(limit)) .sort({tx_time: -1}); }, // async distinctChainList(query): Promise<any> { // const { type, dateNow, status } = query; // return this.distinct(type, { // update_at: { $gte: dateNow - 24 * 60 * 60 }, // status: { $in: status }, // }); // }, async updateIbcTx(ibcTx): Promise<void> { const {record_id} = ibcTx; const options = {upsert: true, new: false, setDefaultsOnInsert: true}; return this.findOneAndUpdate({record_id}, ibcTx, options); }, async insertManyIbcTx(ibcTx, session): Promise<void> { return this.insertMany(ibcTx,{ ordered: false }, (error) => { if(JSON.stringify(error).includes('E11000')){ // Primary key conflict handling }else { if (error) { console.log(error,'insertMany IbcTx error') } } },session); }, async deleteManyIbcTx(recordIds, session): Promise<void> { const options = {session, isDeleted: true }; const filter = { record_id:{ $in:recordIds }, } return this.deleteMany(filter, options); }, async queryTxDetailByHash(query) : Promise<IbcTxType[]>{ const {hash} = query return this.find({ status: { $in: [ IbcTxStatus.SUCCESS, IbcTxStatus.FAILED, IbcTxStatus.PROCESSING, IbcTxStatus.REFUNDED, ], }, $or: [ {"sc_tx_info.hash": hash}, {"dc_tx_info.hash": hash} ] }, {__v: 0,_id: 0}); } };
bianjieai/iobscan-ibc-explorer-backend
src/config/config.ts
<gh_stars>1-10 import dotenv from 'dotenv'; dotenv.config(); const { LCD_ADDR, RPC_ADDR, DB_USER, DB_PASSWD, DB_ADDR, ICONURI, DB_DATABASE, NODE_ENV, EXECUTE_KEY, MAX_PAGE_SIZE, DISPLAY_IBC_RECORD_MAX, FAULT_TOLERANCE_EXECUTE_TIME, HEARTBEAT_RATE, DisableLog, CRON_JOBS, UPDATE_DENOM_BATCH_LIMIT, UPDATE_IBC_TX_BATCH_LIMIT, IBCCHAIN_EXECUTE_TIME, IBCSTATISTICS_EXECUTE_TIME, CHANNELS_LIMITS, CHANNELS_OFFSET, SYNC_TRANSFER_TX_TIME, UPDATE_PROCESSING_TX_TIME, UPDATE_SUB_STATE_TX_TIME, IBC_TX_LATEST_MIGRATE, IBC_TX_UPDATE_CRONJOB, IBC_DENOM_CACULATE_CRONJOB, IBC_MONITOR_CRONJOB, IBC_DENOM_UPDATE_CRONJOB } = process.env; export const cfg = { channels:{ limit: CHANNELS_LIMITS || 1000, offset: CHANNELS_OFFSET || 0, }, env: NODE_ENV, disableLog:Boolean(DisableLog=='true'), dbCfg: { user: DB_USER, psd: DB_PASSWD, dbAddr: DB_ADDR, dbName: DB_DATABASE, }, serverCfg:{ lcdAddr:LCD_ADDR, rpcAddr:RPC_ADDR, iconUri: ICONURI || 'https://keybase.io/_/api/1.0/user/lookup.json', executeKey: EXECUTE_KEY, displayIbcRecordMax:Number(DISPLAY_IBC_RECORD_MAX || 500000), updateDenomBatchLimit: Number(UPDATE_DENOM_BATCH_LIMIT || 100), updateIbcTxBatchLimit: Number(UPDATE_IBC_TX_BATCH_LIMIT || 100), maxPageSize: Number(MAX_PAGE_SIZE || 100), }, taskCfg:{ interval:{ heartbeatRate:Number(HEARTBEAT_RATE || 10000), }, executeTime:{ // tx: '*/10 * * * * *', // chain: '*/10 * * * * *', // statistics: '*/10 * * * * *', // tx: IBCTX_EXECUTE_TIME || '15 * * * * *', chain: IBCCHAIN_EXECUTE_TIME || '0 0 */1 * * *', statistics: IBCSTATISTICS_EXECUTE_TIME || '0 */10 * * * *', faultTolerance:FAULT_TOLERANCE_EXECUTE_TIME || '41 * * * * *', transferTx: SYNC_TRANSFER_TX_TIME || '*/15 * * * * *', updateProcessingTx: UPDATE_PROCESSING_TX_TIME || '*/15 * * * * *', updateSubStateTx: UPDATE_SUB_STATE_TX_TIME || '*/15 * * * * *', ibcTxLatestMigrate: IBC_TX_LATEST_MIGRATE || '0 */30 * * * *', ibcTxUpdateCronjob: IBC_TX_UPDATE_CRONJOB || '0 0 */2 * * *', ibcDenomCaculateCronjob: IBC_DENOM_CACULATE_CRONJOB || '0 0 */1 * * *', ibcDenomUpdateCronjob: IBC_DENOM_UPDATE_CRONJOB || '*/30 * * * * *', ibcMonitorCronjob: IBC_MONITOR_CRONJOB || '0 */1 * * * *', }, CRON_JOBS: CRON_JOBS ? JSON.parse(CRON_JOBS) : [], }, };
bianjieai/iobscan-ibc-explorer-backend
src/monitor/metrics/ibc_transfer_task_status.metric.ts
import {InjectMetric, makeGaugeProvider} from "@willsoto/nestjs-prometheus"; import {Gauge} from "prom-client"; import {Injectable} from "@nestjs/common"; @Injectable() export class TransferTaskStatusMetric { constructor(@InjectMetric("ibc_explorer_backend_transfer_task_status") public gauge: Gauge<string>) {} async collect(value) { this.gauge.set(value) } } export function TransferTaskStatusProvider() { return makeGaugeProvider({ name: "ibc_explorer_backend_transfer_task_status", help: "ibc explorer backend transfer task status (1:Working 0:Notwork)", }) }
bianjieai/iobscan-ibc-explorer-backend
src/task/task.service.ts
import { Injectable } from '@nestjs/common'; import { Cron, SchedulerRegistry } from '@nestjs/schedule'; import { TaskDispatchService } from '../service/task.dispatch.service'; import { TaskEnum } from '../constant'; import { getIpAddress } from '../util/util'; import { cfg } from '../config/config'; import { TaskCallback } from '../types/task.interface'; import { Logger } from '../logger'; import { IRandomKey } from '../types'; import { taskLoggerHelper } from '../helper/task.log.helper'; import { IbcChainConfigTaskService } from './ibc_chain_config.task.service'; import { IbcStatisticsTaskService } from './ibc_statistics.task.service'; import {IbcSyncTransferTxTaskService} from "./ibc_sync_transfer_tx_task.service"; import {IbcUpdateProcessingTxTaskService} from "./ibc_update_processing_tx_task.service"; import {IbcUpdateSubStateTxTaskService} from "./ibc_update_substate_tx_task.service"; import {IbcTxDataUpdateTaskService} from "./ibc_tx_data_update_task.service"; import {IbcTxLatestMigrateTaskService} from "./ibc_tx_latest_migrate_task.service"; import {IbcDenomCaculateTaskService} from "./ibc_denom_caculate.task.service"; import {IbcDenomUpdateTaskService} from "./ibc_denom_update.task.service"; import {IbcMonitorService} from "../monitor/ibc_monitor.service"; @Injectable() export class TasksService { constructor( private readonly taskDispatchService: TaskDispatchService, private readonly ibcChainConfigTaskService: IbcChainConfigTaskService, private readonly ibcStatisticsTaskService: IbcStatisticsTaskService, private readonly ibcSyncTransferTxTaskService : IbcSyncTransferTxTaskService, private readonly ibcUpdateProcessingTxService : IbcUpdateProcessingTxTaskService, private readonly ibcUpdateSubstateTxService: IbcUpdateSubStateTxTaskService, private readonly ibcTxDataUpdateTaskService: IbcTxDataUpdateTaskService, private readonly ibcTxLatestMigrateTaskService: IbcTxLatestMigrateTaskService, private readonly ibcDenomCaculateTaskService: IbcDenomCaculateTaskService, private readonly ibcDenomUpdateTaskService: IbcDenomUpdateTaskService, private readonly ibMonitorService: IbcMonitorService ) { // this[`${TaskEnum.denom}_timer`] = null; } // chainConfig @Cron(cfg.taskCfg.executeTime.chain, { name: TaskEnum.chain, }) // @Cron('*/10 * * * * *') async syncChain() { this.handleDoTask(TaskEnum.chain, this.ibcChainConfigTaskService.doTask); } @Cron(cfg.taskCfg.executeTime.ibcMonitorCronjob, { name: TaskEnum.monitor, }) // @Cron('*/10 * * * * *') async syncMonitor() { this.handleDoTask(TaskEnum.monitor, this.ibMonitorService.doTask); } //新增交易 @Cron(cfg.taskCfg.executeTime.transferTx, { name: TaskEnum.transferTx, }) // @Cron('*/1 * * * * *') async syncTransferTx() { this.handleDoTask(TaskEnum.transferTx, this.ibcSyncTransferTxTaskService.doTask); } @Cron(cfg.taskCfg.executeTime.updateProcessingTx, { name: TaskEnum.updateProcessingTx, }) // @Cron('*/15 * * * * *') async updateProcessingTx() { this.handleDoTask(TaskEnum.updateProcessingTx, this.ibcUpdateProcessingTxService.doTask); } @Cron(cfg.taskCfg.executeTime.updateSubStateTx, { name: TaskEnum.updateSubStateTx, }) // @Cron('*/15 * * * * *') async upSubstateTx() { this.handleDoTask(TaskEnum.updateSubStateTx, this.ibcUpdateSubstateTxService.doTask); } // ex_ibc_statistics @Cron(cfg.taskCfg.executeTime.statistics, { name: TaskEnum.statistics, }) async syncStatistics() { this.handleDoTask( TaskEnum.statistics, this.ibcStatisticsTaskService.doTask, ); } @Cron(cfg.taskCfg.executeTime.faultTolerance) //@Cron('18 * * * * *') async taskDispatchFaultTolerance() { this.taskDispatchService.taskDispatchFaultTolerance((name: TaskEnum) => { if (this[`${name}_timer`]) { clearInterval(this[`${name}_timer`]); this[`${name}_timer`] = null; } }); } @Cron(cfg.taskCfg.executeTime.ibcTxUpdateCronjob) // @Cron('* */2 * * * *') async ibcTxUpdateCronjob() { this.handleDoTask(TaskEnum.ibcTxUpdateCronJob, this.ibcTxDataUpdateTaskService.doTask); } @Cron(cfg.taskCfg.executeTime.ibcTxLatestMigrate) // @Cron('*/30 * * * * *') async ibcTxMigrateCronjob() { this.handleDoTask(TaskEnum.ibcTxMigrateCronJob, this.ibcTxLatestMigrateTaskService.doTask); } @Cron(cfg.taskCfg.executeTime.ibcDenomCaculateCronjob) // @Cron('*/30 * * * * *') async ibcDenomCaculateCronjob() { this.handleDoTask(TaskEnum.ibcDenomCaculateCronJob, this.ibcDenomCaculateTaskService.doTask); } @Cron(cfg.taskCfg.executeTime.ibcDenomUpdateCronjob) // @Cron('*/30 * * * * *') async ibcDenomUpdateCronjob() { this.handleDoTask(TaskEnum.ibcDenomUpdateCronjob, this.ibcDenomUpdateTaskService.doTask); } async handleDoTask(taskName: TaskEnum, doTask: TaskCallback) { if ( cfg && cfg.taskCfg && cfg.taskCfg.CRON_JOBS && cfg.taskCfg.CRON_JOBS.indexOf(taskName) === -1 ) { return; } // 只执行一次删除定时任务 // if (this['once'] && cfg.taskCfg.DELETE_CRON_JOBS && cfg.taskCfg.DELETE_CRON_JOBS.length) { // cfg.taskCfg.DELETE_CRON_JOBS.forEach(async item => { // this.schedulerRegistry.deleteCronJob(item) // await this.taskDispatchService.deleteOneByName(item) // }) // this['once'] = false // } const needDoTask: boolean = await this.taskDispatchService.needDoTask( taskName, ); Logger.log( `the ip ${getIpAddress()} (process pid is ${ process.pid }) should do task ${taskName}? ${needDoTask}`, ); if (needDoTask) { //一个定时任务的完整周期必须严格按照: //上锁 ---> 更新心率时间 ---> 启动定时更新心率时间任务 ---> 执行定时任务 ---> 释放锁 ---> 清除心率定时任务 //否则如果在执行定时任务未结束之前将锁打开, 那么有可能后面的实例会重新执行同样的任务 //为了清晰的看出完整的周期执行顺序, 为每一次的定时任务新增一个唯一key(大致唯一, 只要跟最近的定时任务不重复即可),并标注执行步骤 let randomKey: IRandomKey = { key: String(Math.random()), step: 0, }; try { //因为一般情况下定时任务执行时间要小于心跳率, 为防止heartbeat_update_time一直不被更新, //所以在任务开始之前先更新一下heartbeat_update_time; await this.updateHeartbeatUpdateTime(taskName, randomKey); const beginTime: number = new Date().getTime(); this[`${taskName}_timer`] = setInterval(() => { this.updateHeartbeatUpdateTime(taskName); }, cfg.taskCfg.interval.heartbeatRate); await doTask(taskName, randomKey); //weather task is completed successfully, lock need to be released; const unlock: boolean = await this.taskDispatchService.unlock( taskName, randomKey, ); taskLoggerHelper( `${taskName}: (ip: ${getIpAddress()}, pid: ${ process.pid }) has released the lock? ${unlock}`, randomKey, ); if (this[`${taskName}_timer`]) { clearInterval(this[`${taskName}_timer`]); this[`${taskName}_timer`] = null; taskLoggerHelper( `${taskName}: timer has been cleared out`, randomKey, ); } taskLoggerHelper( `${taskName}: current task executes end, took ${new Date().getTime() - beginTime}ms`, randomKey, ); } catch (e) { Logger.error( `${taskName}: task executes error, should release lock`, e, ); await this.taskDispatchService.unlock(taskName, randomKey); if (this[`${taskName}_timer`]) { clearInterval(this[`${taskName}_timer`]); this[`${taskName}_timer`] = null; } } } } async updateHeartbeatUpdateTime( name: TaskEnum, randomKey?: IRandomKey, ): Promise<void> { await this.taskDispatchService.updateHeartbeatUpdateTime(name, randomKey); } }
bianjieai/iobscan-ibc-explorer-backend
src/module/ibc_denom_caculate.task.module.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend<gh_stars>1-10 import { Module } from '@nestjs/common'; import { IbcDenomCaculateTaskService } from '../task/ibc_denom_caculate.task.service'; @Module({ providers: [IbcDenomCaculateTaskService], exports: [IbcDenomCaculateTaskService], }) export class IbcDenomCaculateTaskModule {}
bianjieai/iobscan-ibc-explorer-backend
src/types/schemaTypes/ibc_denom.interface.ts
export interface IbcDenomType { chain_id: string; denom: string; base_denom: string; denom_path: string; symbol: string; is_source_chain: boolean; create_at: string; update_at: string; } export interface AggregateBaseDenomCnt { _id:{base_denom?:string,chain_id?:string}; } export class IbcDenomDto { readonly chain_id: string; readonly denom: string; readonly symbol: string; }
bianjieai/iobscan-ibc-explorer-backend
src/schema/config.schema.ts
import * as mongoose from 'mongoose'; import { ConfigType } from '../types/schemaTypes/config.interface'; export const ConfigSchema = new mongoose.Schema( { iobscan: String, }, { versionKey: false }, ); ConfigSchema.statics = { async findRecord(): Promise<ConfigType> { return this.findOne(); }, };
bianjieai/iobscan-ibc-explorer-backend
src/controller/config.controller.ts
<reponame>bianjieai/iobscan-ibc-explorer-backend import { Controller, Get } from '@nestjs/common'; import { ApiTags } from '@nestjs/swagger'; import { Result } from '../api/ApiResult'; import { ConfigService } from '../service/config.service'; import { ConfigResDto } from '../dto/config.dto'; @ApiTags('Config') @Controller('ibc') export class ConfigController { constructor(private readonly configService: ConfigService) {} @Get('config') async getAllRecord(): Promise<Result<ConfigResDto>> { const result: ConfigResDto = await this.configService.findOne(); return new Result<ConfigResDto>(result); } }
bianjieai/iobscan-ibc-explorer-backend
src/task/ibc_denom_caculate.task.service.ts
import { Connection } from 'mongoose'; import {Injectable} from "@nestjs/common"; import {InjectConnection} from "@nestjs/mongoose"; import {TaskEnum} from "../constant"; import {IbcChainConfigSchema} from "../schema/ibc_chain_config.schema"; import {IbcBaseDenomSchema} from "../schema/ibc_base_denom.schema"; import {IbcDenomCaculateSchema} from "../schema/ibc_denom_caculate.schema"; import {IbcChainConfigType} from "../types/schemaTypes/ibc_chain_config.interface"; import {IbcBaseDenomType} from "../types/schemaTypes/ibc_base_denom.interface"; import {IbcDenom} from "../helper/denom.helper"; import {Md5} from "ts-md5"; import {Logger} from "../logger"; @Injectable() export class IbcDenomCaculateTaskService { private chainConfigModel; private ibcBaseDenomModel; private ibcDenomCaculateModel; constructor(@InjectConnection() private connection: Connection) { this.getModels(); this.doTask = this.doTask.bind(this); } async doTask(taskName?: TaskEnum): Promise<void> { this.handleChain(); } async getModels(): Promise<void> { this.ibcBaseDenomModel = await this.connection.model( 'ibcBaseDenomModel', IbcBaseDenomSchema, 'ibc_base_denom', ); this.chainConfigModel = await this.connection.model( 'chainConfigModel', IbcChainConfigSchema, 'chain_config', ); this.ibcDenomCaculateModel = await this.connection.model( 'ibcDenomCaculateModel', IbcDenomCaculateSchema, 'ibc_denom_caculate', ); } async findAllChainConfig(): Promise<IbcChainConfigType[]> { return await this.chainConfigModel.findAll(); } async findAllBaseDenom(): Promise<IbcBaseDenomType[]> { return await this.ibcBaseDenomModel.findAllRecord(); } // get already caculate ibc denom async getCaculateDenomMap(srcChainId) : Promise<any>{ let caculateDenomMap = new Map const caculateDenom = await this.ibcDenomCaculateModel.findCaculateDenom(srcChainId) for (const one of caculateDenom) { if (one?.denom_path && one?.chain_id && one?.base_denom) { //目标chain_id + denom_path + base_denom caculateDenomMap.set(`${one?.chain_id}${one?.denom_path}${one?.base_denom}`,'') } } return caculateDenomMap } async caculateBaseDenom(oneBaseDenom, channelMap) { const chainCfg: IbcChainConfigType = channelMap.get(oneBaseDenom.chain_id) // caculate ibc_info hash to compare with ibc_info_hash_caculate //获取最新的ibc_info的hashCode const hashCode = Md5.hashStr(JSON.stringify(chainCfg.ibc_info)) let ibcDenomInfos = [] //根据baseDenom的chain_id获取已经计算好的denom const caculateDenomMap = await this.getCaculateDenomMap(oneBaseDenom.chain_id) if (hashCode !== oneBaseDenom?.ibc_info_hash_caculate && chainCfg?.ibc_info?.length > 0 && oneBaseDenom?.denom) { for (const ibcInfo of chainCfg.ibc_info) { if (ibcInfo?.chain_id && ibcInfo?.paths?.length > 0) { ibcInfo.paths.forEach(item => { if (item?.counterparty?.port_id && item?.counterparty?.channel_id) { const denomPath = `${item?.counterparty?.port_id}/${item?.counterparty?.channel_id}` const ibcDenom = IbcDenom(denomPath, oneBaseDenom.denom) //目标chain_id + denom_path + base_denom const existKey = `${ibcInfo.chain_id}${denomPath}${oneBaseDenom.denom}` // check if not caculate before push caculate denom to ibcDenomInfos if (!caculateDenomMap?.has(existKey)) { ibcDenomInfos.push({ symbol: oneBaseDenom.symbol, base_denom: oneBaseDenom.denom, denom: ibcDenom, denom_path: denomPath, chain_id: ibcInfo.chain_id, sc_chain_id: oneBaseDenom.chain_id, }) } } }) } } if (ibcDenomInfos?.length > 0) { const session = await this.connection.startSession() session.startTransaction() try { oneBaseDenom.ibc_info_hash_caculate = hashCode await this.ibcDenomCaculateModel.insertDenomCaculate(ibcDenomInfos,session) await this.ibcBaseDenomModel.updateBaseDenomWithSession(oneBaseDenom,session) await session.commitTransaction(); session.endSession(); } catch (e) { Logger.log(e, 'transaction is error') await session.abortTransaction() session.endSession(); } } } } async handleChain() { const chainConfig = await this.findAllChainConfig() const baseDenom = await this.findAllBaseDenom() let channelMap = new Map for (const one of chainConfig) { channelMap.set(`${one.chain_id}`, one) } for (const one of baseDenom) { if (channelMap.has(one.chain_id)) { await this.caculateBaseDenom(one, channelMap) } } } }
bianjieai/iobscan-ibc-explorer-backend
src/monitor/ibc_monitor.service.ts
import {HttpService, Injectable} from "@nestjs/common"; import {InjectConnection} from "@nestjs/mongoose"; import {Connection} from 'mongoose'; import {IbcChainConfigSchema} from "../schema/ibc_chain_config.schema"; import {IbcTxSchema} from "../schema/ibc_tx.schema"; import {TaskEnum} from "../constant"; import {NodeInfoType} from "../types/lcd.interface"; import {Logger} from "../logger"; import {LcdConnectionMetric} from "../monitor/metrics/ibc_chain_lcd_connection.metric"; import {IbcTxProcessingMetric} from "../monitor/metrics/ibc_tx_processing_cnt.metric"; import {IbcTxTable} from "../constant/index"; @Injectable() export class IbcMonitorService { private chainConfigModel; private ibcTxLatestModel; constructor(@InjectConnection() private readonly connection: Connection, private readonly lcdConnectionMetric: LcdConnectionMetric, private readonly ibcTxProcessMetric: IbcTxProcessingMetric) { this.getModels(); this.doTask = this.doTask.bind(this); } async doTask(taskName?: TaskEnum): Promise<void> { const allChains = await this.chainConfigModel.findAll(); for (const one of allChains) { await this.getNodeInfo(one.lcd,one.chain_id) } this.getProcessingCnt() } // getModels async getModels(): Promise<void> { // chainConfigModel this.chainConfigModel = await this.connection.model( 'chainConfigModel', IbcChainConfigSchema, 'chain_config', ); // ibcTxModel this.ibcTxLatestModel = await this.connection.model( 'ibcTxLatestModel', IbcTxSchema, IbcTxTable.IbcTxLatestTableName, ); } async getNodeInfo(lcdAddr,chain) { const nodeInfoUrl = `${lcdAddr}/node_info`; try { const nodeInfo: NodeInfoType= await new HttpService() .get(nodeInfoUrl) .toPromise() .then(result => result.data); if (nodeInfo) { // monitor code await this.lcdConnectionMetric.collect(chain,1) return nodeInfo } else { // monitor code await this.lcdConnectionMetric.collect(chain,0) Logger.warn( 'api-error:', 'there is no result of data from lcd', ); } } catch (e) { // monitor code await this.lcdConnectionMetric.collect(chain,0) Logger.warn(`api-error from ${nodeInfoUrl} error`); } } async getProcessingCnt() { const processingCnt = await this.ibcTxLatestModel.countProcessing(); await this.ibcTxProcessMetric.collect(processingCnt) } }
bianjieai/iobscan-ibc-explorer-backend
src/dto/ibc_denom.dto.ts
<filename>src/dto/ibc_denom.dto.ts<gh_stars>1-10 /* eslint-disable @typescript-eslint/camelcase */ import { IbcDenomType } from '../types/schemaTypes/ibc_denom.interface'; import { BaseResDto } from './base.dto' export class IbcDenomResDto extends BaseResDto { chain_id: string; denom: string; base_denom: string; denom_path: string; is_source_chain: boolean; create_at: string; update_at: string; symbol: string; constructor(value) { super() const { chain_id, denom, base_denom, denom_path, is_source_chain, create_at, update_at, symbol, } = value; this.chain_id = chain_id; this.denom = denom; this.base_denom = base_denom; this.denom_path = denom_path; this.is_source_chain = is_source_chain; this.symbol = symbol; this.create_at = create_at; this.update_at = update_at; } static bundleData(value: IbcDenomType[] = []) { const datas: IbcDenomResDto[] = value.map((item: any) => { return { chain_id: item.chain_id, denom: item.denom, base_denom: item.base_denom, denom_path: item.denom_path, is_source_chain: item.is_source_chain, symbol: item.symbol, create_at: item.create_at, update_at: item.update_at, } }) return datas } }
bianjieai/iobscan-ibc-explorer-backend
src/http/lcd/chain.http.ts
<gh_stars>1-10 /* eslint-disable @typescript-eslint/camelcase */ import {HttpService, Injectable} from '@nestjs/common'; import {Logger} from '../../logger'; import {LcdChannelDto, LcdDenomDto} from '../../dto/http.dto' import {LcdChannelType, DenomType,LcdChannelClientState} from '../../types/lcd.interface' import {cfg} from "../../config/config"; @Injectable() export class ChainHttp { static async getIbcChannels(lcdAddr, channelsPath: string) { let rgexOffset = "\\OFFSET", regexLimit = "\\LIMIT" channelsPath = channelsPath.replace(new RegExp(rgexOffset, "g"), <string>cfg.channels.offset); channelsPath = channelsPath.replace(new RegExp(regexLimit, "g"), <string>cfg.channels.limit); const ibcChannelsUrl = `${lcdAddr}${channelsPath}`; try { const ibcChannels: LcdChannelType[] = await new HttpService() .get(ibcChannelsUrl) .toPromise() .then(result => result.data.channels); if (ibcChannels) { return LcdChannelDto.bundleData(ibcChannels); } else { Logger.warn( 'api-error:', 'there is no result of total_supply from lcd', ); } } catch (e) { // Logger.warn(`api-error from ${ibcChannelsUrl}`, e); Logger.warn(`api-error from ${ibcChannelsUrl} error`); } } static async getDcChainIdByScChannel(lcdAddr, clientStatePath: string, port: string, channel: string) { let rgexPort = "\\PORT", regexChannel = "\\CHANNEL" clientStatePath = clientStatePath.replace(new RegExp(rgexPort, "g"), port); clientStatePath = clientStatePath.replace(new RegExp(regexChannel, "g"), channel); const ibcClientStateUrl = `${lcdAddr}${clientStatePath}`; try { const ibcClientState: LcdChannelClientState = await new HttpService() .get(ibcClientStateUrl) .toPromise() .then(result => result.data); if (ibcClientState) { return ibcClientState.identified_client_state.client_state.chain_id; } else { Logger.warn( 'api-error:', 'there is no result of total_supply from lcd', ); } } catch (e) { // Logger.warn(`api-error from ${ibcChannelsUrl}`, e); Logger.warn(`api-error from ${ibcClientStateUrl} error`); } } static async getDenomByLcdAndHash(lcdAddr, hash) { const ibcDenomTraceUrl = `${lcdAddr}/ibc/applications/transfer/v1beta1/denom_traces/${hash}`; try { const denom_trace: DenomType = await new HttpService() .get(ibcDenomTraceUrl) .toPromise() .then(result => result.data.denom_trace); if (denom_trace) { return new LcdDenomDto(denom_trace); } else { Logger.warn( 'api-error:', 'there is no result of total_supply from lcd', ); } } catch (e) { // Logger.warn(`api-error from ${ibcDenomTraceUrl}`, e); Logger.warn(`api-error from ${ibcDenomTraceUrl} error`); } } }
bianjieai/iobscan-ibc-explorer-backend
src/task/ibc_tx_latest_migrate_task.service.test.ts
import {IbcTxLatestMigrateTaskService} from "./ibc_tx_latest_migrate_task.service"; import {Test} from "@nestjs/testing"; import {AppModule} from "../app.module"; describe('IbcTxLatestMigrateTaskService', () => { let ibcTxLatestMigrateTaskService: IbcTxLatestMigrateTaskService; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [ AppModule ] }).compile(); ibcTxLatestMigrateTaskService = module.get<IbcTxLatestMigrateTaskService>(IbcTxLatestMigrateTaskService); }) describe('migrateData', () => { it('migrateData Test', async () => { jest.setTimeout(1000000) await ibcTxLatestMigrateTaskService.migrateData(5) console.log("=====") }); it('startMigrate Test', async () => { jest.setTimeout(1000000) await ibcTxLatestMigrateTaskService.startMigrate(2690) console.log("=====") }); }); })