Skip to content

Commit

Permalink
chore(refactor): treewide refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
imsk17 committed Nov 1, 2024
1 parent a92c3fb commit 0255d04
Show file tree
Hide file tree
Showing 25 changed files with 309 additions and 278 deletions.
4 changes: 2 additions & 2 deletions src/handler/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { listenEvents } from "./lock-listener";
export { listenStakeEvents } from "./stake-listener";
export { listenEvents } from "./lock-listener/lock-listener";
export { listenStakeEvents } from "./stake-listener/stake-listener";
2 changes: 2 additions & 0 deletions src/handler/lock-listener/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./lock-listener";
export * from "./process-fail-safe";
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@ import { Mutex } from "async-mutex";
import type { AxiosInstance } from "axios";
import axios from "axios";
import type { JsonRpcProvider } from "ethers";
import type { TSupportedChains } from "../config";
import type { BridgeStorage } from "../contractsTypes/evm";
import { LockedEvent } from "../persistence/entities/locked";
import { eventBuilder } from "./event-builder";
import type { TSupportedChains } from "../../config";
import type { BridgeStorage } from "../../contractsTypes/evm";
import { LockedEvent } from "../../persistence/entities/locked";
import { eventBuilder } from "../event-builder";
import type {
LockEvent,
LogInstance,
THandler,
TNftTransferDetailsObject,
} from "./types";
import { fetchHttpOrIpfs, retry, useMutexAndRelease } from "./utils";
} from "../types";
import { fetchHttpOrIpfs, retry, useMutexAndRelease } from "../utils";
import { processEventsFailSafe } from "./process-fail-safe";

export async function listenEvents(
chains: Array<THandler>,
Expand Down Expand Up @@ -46,14 +47,14 @@ export async function listenEvents(
const sourceChain = map.get(ev.sourceChain as TSupportedChains);
if (!sourceChain) {
log.warn(
`Unsupported src chain: ${sourceChain} for ${ev.transactionHash}`,
`Unsupported src chain: ${ev.sourceChain} for ${ev.transactionHash} on ${ev.listenerChain}`,
);
return;
}
const destinationChain = map.get(ev.destinationChain as TSupportedChains);
if (!destinationChain) {
log.warn(
`Unsupported dest chain: ${destinationChain} for ${ev.transactionHash} ${destinationChain} ${ev.destinationChain}`,
`Unsupported dest chain: ${ev.destinationChain} for ${ev.transactionHash} on ${ev.listenerChain}`,
);
return;
}
Expand Down Expand Up @@ -234,22 +235,3 @@ export async function listenEvents(
serverLinkHandler === undefined ? poolEvents(chain) : pollEvents(chain);
}
}

const processEventsFailSafe = async (
chain: THandler,
ev: LockEvent,
log: LogInstance,
processEvent: (chain: THandler, ev: LockEvent) => Promise<void>,
) => {
let success = false;
while (!success) {
try {
await processEvent(chain, ev);
success = true;
} catch (e) {
log.error("Error processing poll events", ev, e);
log.info("Awaiting 2s");
await setTimeout(2 * 1000);
}
}
};
22 changes: 22 additions & 0 deletions src/handler/lock-listener/process-fail-safe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { setTimeout } from "node:timers/promises";
import type { LockEvent } from "../types";
import type { LogInstance, THandler } from "../types";

export const processEventsFailSafe = async (
chain: THandler,
ev: LockEvent,
log: LogInstance,
processEvent: (chain: THandler, ev: LockEvent) => Promise<void>,
) => {
let success = false;
while (!success) {
try {
await processEvent(chain, ev);
success = true;
} catch (e) {
log.error("Error processing poll events", ev, e);
log.info("Awaiting 2s");
await setTimeout(2 * 1000);
}
}
};
2 changes: 2 additions & 0 deletions src/handler/stake-listener/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./stake-listener";
export * from "./stake-tokens";
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { EntityManager } from "@mikro-orm/sqlite";
import type { TSupportedChainTypes } from "../config";
import type { BridgeStorage } from "../contractsTypes/evm";
import { eventBuilder } from "./event-builder";
import type { LogInstance, THandler, TStakingHandler } from "./types";
import { retry } from "./utils";
import type { TSupportedChainTypes } from "../../config";
import type { BridgeStorage } from "../../contractsTypes/evm";
import { eventBuilder } from "../event-builder";
import type { LogInstance, THandler, TStakingHandler } from "../types";
import { retry } from "../utils";

export async function listenStakeEvents(
chains: Array<THandler>,
Expand Down
59 changes: 59 additions & 0 deletions src/handler/stake-listener/stake-tokens.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { JsonRpcProvider, Wallet } from "ethers";
import {
ERC20Staking__factory,
ERC20__factory,
} from "../../contractsTypes/evm";
import type { IGeneratedWallets, IStakingConfig } from "../../types";
import type { LogInstance, THandler } from "../types";

export async function stakeTokens(
conf: IStakingConfig,
secrets: IGeneratedWallets,
chains: THandler[],
logger: LogInstance,
) {
const others = chains.filter((e) => e.chainType !== "evm");
const provider = new JsonRpcProvider(conf.rpcURL);
const signer = new Wallet(secrets.evmWallet.privateKey, provider);
const staker = ERC20Staking__factory.connect(conf.contractAddress, signer);
const token = ERC20__factory.connect(conf.coinAddress, signer);
const staked = await staker.stakingBalances(secrets.evmWallet.address);
if (staked > 0n) {
logger.info(
`Already staked ${staked} ${conf.coinSymbol} in contract ${conf.contractAddress}`,
);
return;
}
const amtToStake = await staker.stakingAmount();
logger.info("Awaiting completion of approve transaction.");

const approve = await (
await token.approve(conf.contractAddress, amtToStake * amtToStake)
).wait();

logger.info("Approved to stake: ✅");
if (!approve || approve.status !== 1) {
throw new Error("Failed to approve staking");
}

const data = [
{
validatorAddress: secrets.evmWallet.address,
chainType: "evm",
},
...others.map((e) => {
return {
validatorAddress: e.publicKey,
chainType: e.chainType,
};
}),
];

logger.info("Awaiting completion of stake transaction.");
const staking = await (await staker.stakeERC20(data)).wait();
logger.info("Stake complete: ✅");

if (!staking || staking.status !== 1) {
throw new Error("Failed to stake");
}
}
87 changes: 0 additions & 87 deletions src/handler/types.ts

This file was deleted.

4 changes: 4 additions & 0 deletions src/handler/types/event-iterators.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import type { LockEvent, StakeEvent } from ".";

export type LockEventIter = (event: LockEvent) => Promise<void>;
export type StakeEventIter = (event: StakeEvent) => Promise<void>;
9 changes: 9 additions & 0 deletions src/handler/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export * from "./lock-event";
export * from "./stake-event";
export * from "./lock-handler";
export * from "./stake-handler";
export * from "./event-iterators";
export * from "./lock-handler";
export * from "./nft-data";
export * from "./nft-transfer-details-object";
export * from "./logger";
12 changes: 12 additions & 0 deletions src/handler/types/lock-event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export type LockEvent = {
listenerChain: string;
tokenId: string;
destinationChain: string;
destinationUserAddress: string;
sourceNftContractAddress: string;
tokenAmount: string;
nftType: string;
sourceChain: string;
transactionHash: string;
metaDataUri: string;
};
31 changes: 31 additions & 0 deletions src/handler/types/lock-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { TNftTransferDetailsObject } from ".";
import type { LockEventIter, LogInstance, TNftData } from ".";
import type { TSupportedChainTypes, TSupportedChains } from "../../config";
import type { EventBuilder } from "../event-builder";

export interface THandler {
addSelfAsValidator(): Promise<"success" | "failure">;
listenForLockEvents(builder: EventBuilder, cb: LockEventIter): Promise<void>;
pollForLockEvents(builder: EventBuilder, cb: LockEventIter): Promise<void>;
signClaimData(
nfto: TNftTransferDetailsObject,
): Promise<{ signer: string; signature: string }>;
signData(buf: string): Promise<{ signer: string; signature: string }>;
nftData(
tokenId: string,
contract: string,
logger: LogInstance,
): Promise<TNftData>;
validateNftData(
data: TNftData,
): { valid: false; reason: string } | { valid: true };
chainIdent: TSupportedChains;
selfIsValidator(): Promise<boolean>;
getBalance(): Promise<bigint>;
initialFunds: bigint;
currency: string;
address: string;
chainType: TSupportedChainTypes;
publicKey: string;
decimals: bigint;
}
3 changes: 3 additions & 0 deletions src/handler/types/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import type { Logger } from "tslog";

export type LogInstance = Logger<unknown>;
6 changes: 6 additions & 0 deletions src/handler/types/nft-data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export type TNftData = {
name: string;
symbol: string;
metadata: string;
royalty: bigint;
};
18 changes: 18 additions & 0 deletions src/handler/types/nft-transfer-details-object.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export type TNftTransferDetailsObject = {
tokenId: string;
sourceChain: string;
destinationChain: string;
destinationUserAddress: string;
sourceNftContractAddress: string;
name: string;
symbol: string;
royalty: string;
royaltyReceiver: string;
metadata: string;
transactionHash: string;
tokenAmount: string;
nftType: string;
fee: string;
lockTxChain: string;
imgUri?: string;
};
7 changes: 7 additions & 0 deletions src/handler/types/stake-event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { TSupportedChainTypes } from "../../config";

export type StakeEvent = {
validatorAddress: string;
caller: string;
chainType: TSupportedChainTypes;
}[];
9 changes: 9 additions & 0 deletions src/handler/types/stake-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { EventBuilder } from "../event-builder";
import type { StakeEventIter } from "./event-iterators";

export interface TStakingHandler {
listenForStakingEvents(
builder: EventBuilder,
cb: StakeEventIter,
): Promise<void>;
}
Loading

0 comments on commit 0255d04

Please sign in to comment.