Skip to content

Commit

Permalink
refactor: Solve Merge Conflicts, rename vars
Browse files Browse the repository at this point in the history
Changes after Feedback
  • Loading branch information
nick134-bit committed May 28, 2023
1 parent 7f10d39 commit 499e070
Show file tree
Hide file tree
Showing 11 changed files with 108 additions and 103 deletions.
4 changes: 2 additions & 2 deletions .env.injective.example
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ USE_SKIP="1"
SKIP_URL="https://injective-1-api.skip.money"
SKIP_BID_WALLET="inj17yqtnk08ly94lgz3fzagfu2twsws33z7sfsv46"
SKIP_BID_RATE="0.1" #e.g. 20% of the profit is used as a bid to win the auction
TRY_WO_SKIP="0" # Try without skip if the next Validator is not using skip. Send a standard Tx through the Mempool. More Risk! 0 == false
TIMEOUT_FOR_DUR="100" # Timeout Duration for Addresses that send failed Arbitrage opportunities
TRY_WITHOUT_SKIP="0" # Try without skip if the next Validator is not using skip. Send a standard Tx through the Mempool. More Risk! 0 == false

# Addresses to Blacklist. Needed against Spam Txs.
# For more Info Discord Channel Developers/Bot-Support
IGNORE_ADDRESSES='[""]'
TIMEOUT_DURATION="100" # Timeout Duration for Addresses in Blocks

## INJECTIVE SETTINGS
BASE_DENOM="peggy0xdAC17F958D2ee523a2206206994597C13D831ec7"
Expand Down
5 changes: 3 additions & 2 deletions .env.juno.example
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@ USE_SKIP= "1"
SKIP_URL= "http://juno-1-api.skip.money"
SKIP_BID_WALLET= "juno1qan7ffv9kqpp704ywevq26hw53997ppdkwzs74"
SKIP_BID_RATE="0.31" #e.g. 31% of the profit is used as a bid to win the auction
TRY_WO_SKIP="0" # Try without skip if the next Validator is not using skip. Send a standard Tx through the Mempool. More Risk! 0 == false
TIMEOUT_FOR_DUR="100" # Timeout Duration for Addresses that send failed Arbitrage opportunities
TRY_WITHOUT_SKIP="0" # Try without skip if the next Validator is not using skip. Send a standard Tx through the Mempool. More Risk! 0 == false


# Addresses to Blacklist. Needed against Spam Txs.
# For more Info Discord Channel Developers/Bot-Support
IGNORE_ADDRESSES='[""]'
TIMEOUT_DURATION="100" # Timeout Duration for Addresses in Blocks

##JUNO SETTINGS
BASE_DENOM="ujuno" # The asset denom to be used as base asset. This should be the denom of a Native Token only.
Expand Down
6 changes: 3 additions & 3 deletions .env.terra.example
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ SIGN_OF_LIFE="30" #Sign of Life in Minutes. E.g. "30"
##SKIP SPECIFIC ENVIRONMENT VARIABLES FOR CURRENT CHAIN
USE_SKIP = "1"
SKIP_URL= "http://phoenix-1-api.skip.money"
SKIP_BID_WALLET= "terra1lgex5ks77r7f5u6k8y5l6j5q0uc3te8k7wsymk"
SKIP_BID_WALLET= "terra1kdx075ghexr2l6mx4mgn37deshu9fn59r9zq9v"
SKIP_BID_RATE="0.1" #e.g. 10% of the profit is used as a bid to win the auction
TRY_WO_SKIP="0" # Try without skip if the next Validator is not using skip. Send a standard Tx through the Mempool. More Risk! 0 == false
TIMEOUT_FOR_DUR="100" # Timeout Duration for Addresses that send failed Arbitrage opportunities
TRY_WITHOUT_SKIP="0" # Try without skip if the next Validator is not using skip. Send a standard Tx through the Mempool. More Risk! 0 == false

# Addresses to Blacklist. Needed against Spam Txs.
# For more Info Discord Channel Developers/Bot-Support
IGNORE_ADDRESSES='[""]'
TIMEOUT_DURATION="100" # Timeout Duration for Addresses in Blocks

##TERRA SETTINGS
BASE_DENOM="uluna"
Expand Down
7 changes: 6 additions & 1 deletion src/core/chainOperator/chainoperator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,13 @@ export class ChainOperator {
async queryContractSmart(address: string, queryMsg: Record<string, unknown>): Promise<JsonObject> {
try {
return await this.client.queryContractSmart(address, queryMsg);
} catch (e) {
} catch (e: any) {
//custom error for initPools JunoSwapPoolState
if (e.message.includes("Query failed with (18):")) {
throw new Error(e.message);
}
console.log(e);
await this.client.getNewClients();
await this.client.queryContractSmart(address, queryMsg);
}
}
Expand Down
41 changes: 10 additions & 31 deletions src/core/types/arbitrageloops/mempoolLoop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { ChainOperator } from "../../chainOperator/chainoperator";
import { Logger } from "../../logging";
import { BotConfig } from "../base/botConfig";
import { LogType } from "../base/logging";
import { decodeMempool, flushTxMemory, Mempool, MempoolTx } from "../base/mempool";
import { decodeMempool, flushTxMemory, IgnoredAddresses, Mempool, MempoolTx } from "../base/mempool";
import { Path } from "../base/path";
import { applyMempoolMessagesOnPools, Pool } from "../base/pool";
/**
Expand All @@ -20,7 +20,7 @@ export class MempoolLoop {
pathlib: Array<Path>; //holds all known paths
CDpaths: Map<string, [number, number, number]>; //holds all cooldowned paths' identifiers
chainOperator: ChainOperator;
ignoreAddresses: { [index: string]: { source: boolean; timeout_at: number; duration: number } };
ignoreAddresses: IgnoredAddresses;
botConfig: BotConfig;
logger: Logger | undefined;
// CACHE VALUES
Expand Down Expand Up @@ -56,7 +56,7 @@ export class MempoolLoop {
botConfig: BotConfig,
logger: Logger | undefined,
pathlib: Array<Path>,
ignoreAddresses: { [index: string]: { source: boolean; timeout_at: number; duration: number } },
ignoreAddresses: IgnoredAddresses,
) {
this.pools = pools;
this.CDpaths = new Map<string, [number, number, number]>();
Expand Down Expand Up @@ -95,35 +95,14 @@ export class MempoolLoop {
this.totalBytes = +this.mempool.total_bytes;
}

const mempooltxs: [Array<MempoolTx>, Array<{ sender: string; reciever: string }>] = decodeMempool(
const mempoolTxs: Array<MempoolTx> = decodeMempool(
this.mempool,
this.ignoreAddresses,
this.botConfig.timeoutDuration,
this.iterations,
);

// Checks if there is a SendMsg from a blacklisted Address, if so add the reciever to the timeouted addresses
mempooltxs[1].forEach((Element) => {
if (this.ignoreAddresses[Element.sender]) {
if (
this.ignoreAddresses[Element.sender].source ||
this.ignoreAddresses[Element.sender].timeout_at +
this.ignoreAddresses[Element.sender].duration <=
this.iterations
) {
this.ignoreAddresses[Element.reciever] = {
source: false,
timeout_at: this.iterations,
duration: 100,
};
this.ignoreAddresses[Element.sender].timeout_at = this.iterations;
} else if (
this.ignoreAddresses[Element.sender].timeout_at +
this.ignoreAddresses[Element.sender].duration >=
this.iterations
) {
delete this.ignoreAddresses[Element.sender];
}
}
});
const mempoolTxs: Array<MempoolTx> = mempooltxs[0];
if (mempoolTxs.length === 0) {
continue;
} else {
Expand Down Expand Up @@ -228,12 +207,12 @@ export class MempoolLoop {
/**
*
*/
public clear_ignoreAddresses() {
public clearIgnoreAddresses() {
const keys = Object.keys(this.ignoreAddresses);
for (let i = 0; i < keys.length; i++) {
if (
!this.ignoreAddresses[keys[i]].source &&
this.ignoreAddresses[keys[i]].timeout_at + this.ignoreAddresses[keys[i]].duration <= this.iterations
this.ignoreAddresses[keys[i]].timeoutAt > 0 &&
this.ignoreAddresses[keys[i]].timeoutAt + this.ignoreAddresses[keys[i]].duration <= this.iterations
) {
delete this.ignoreAddresses[keys[i]];
}
Expand Down
2 changes: 1 addition & 1 deletion src/core/types/arbitrageloops/nomempoolLoop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ export class NoMempoolLoop {
/**
*
*/
public clear_ignoreAddresses() {
public clearIgnoreAddresses() {
return;
}
}
Expand Down
60 changes: 16 additions & 44 deletions src/core/types/arbitrageloops/skipLoop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { SkipResult } from "../../chainOperator/skipclients";
import { Logger } from "../../logging";
import { BotConfig } from "../base/botConfig";
import { LogType } from "../base/logging";
import { decodeMempool, MempoolTx } from "../base/mempool";
import { decodeMempool, IgnoredAddresses, MempoolTx } from "../base/mempool";
import { Path } from "../base/path";
import { applyMempoolMessagesOnPools, Pool } from "../base/pool";
import { MempoolLoop } from "./mempoolLoop";
Expand Down Expand Up @@ -47,7 +47,7 @@ export class SkipLoop extends MempoolLoop {
logger: Logger | undefined,

pathlib: Array<Path>,
ignoreAddresses: { [index: string]: { source: boolean; timeout_at: number; duration: number } },
ignoreAddresses: IgnoredAddresses,
) {
super(
pools,
Expand Down Expand Up @@ -88,36 +88,14 @@ export class SkipLoop extends MempoolLoop {
this.totalBytes = +this.mempool.total_bytes;
}

const mempoolTxs: [Array<MempoolTx>, Array<{ sender: string; reciever: string }>] = processMempool(
const mempoolTxs: Array<MempoolTx> = decodeMempool(
this.mempool,
this.ignoreAddresses,
this.botConfig.timeoutDuration,
this.iterations,
);
const mempoolTrades = mempoolTxs[0];
mempoolTxs[1].forEach((Element) => {
if (this.ignoreAddresses[Element.sender]) {
if (
this.ignoreAddresses[Element.sender].source ||
this.ignoreAddresses[Element.sender].timeout_at +
this.ignoreAddresses[Element.sender].duration <=
this.iterations
) {
this.ignoreAddresses[Element.reciever] = {
source: false,
timeout_at: this.iterations,
duration: this.botConfig.skipConfig!.timout_dur,
};
this.ignoreAddresses[Element.sender].timeout_at = this.iterations;
} else if (
this.ignoreAddresses[Element.sender].timeout_at +
this.ignoreAddresses[Element.sender].duration >=
this.iterations
) {
delete this.ignoreAddresses[Element.sender];
}
}
});

if (mempoolTxs[0].length === 0) {
if (mempoolTxs.length === 0) {
continue;
} else {
for (const mempoolTx of mempoolTxs) {
Expand Down Expand Up @@ -150,9 +128,10 @@ export class SkipLoop extends MempoolLoop {
return;
}

const skiprate = Math.max(Math.round(arbTrade.profit * this.botConfig.skipConfig.skipBidRate), 651);
const skipFee = Math.max(Math.round(arbTrade.profit * this.botConfig.skipConfig.skipBidRate), 651);

const bidMsgEncoded = getSendMessage(
String(skiprate),
String(skipFee),
this.botConfig.gasDenom,
this.chainOperator.client.publicAddress,
this.botConfig.skipConfig.skipBidWallet,
Expand Down Expand Up @@ -184,13 +163,13 @@ export class SkipLoop extends MempoolLoop {
let logItem = "";
let logMessage = `**wallet:** ${this.chainOperator.client.publicAddress}\t **block:** ${
res.result.desired_height
}\t **profit:** ${arbTrade.profit - skiprate}`;
}\t **profit:** ${arbTrade.profit - skipFee}`;

if (res.result.code !== 0) {
logMessage += `\t **error code:** ${res.result.code}\n**error:** ${res.result.error}\n`;
}
if (res.result.code === 4) {
console.log("no skip validator up, trying default broadcast");
if (this.botConfig.skipConfig.tryWithoutSkip && res.result.code === 4) {
await this.logger?.sendMessage("no skip validator up, trying default broadcast", LogType.Console);
await this.trade(arbTrade);
}

Expand All @@ -203,9 +182,8 @@ export class SkipLoop extends MempoolLoop {
logMessage = logMessage.concat(logMessageCheckTx);
if (toArbTrade?.message.sender && idx == 0 && item["code"] == "5") {
this.ignoreAddresses[toArbTrade.message.sender] = {
source: false,
timeout_at: this.iterations,
duration: this.botConfig.skipConfig!.timout_dur,
timeoutAt: this.iterations,
duration: this.botConfig.timeoutDuration,
};
await this.logger?.sendMessage(
"Error on Trade from Address: " + toArbTrade.message.sender,
Expand All @@ -225,9 +203,8 @@ export class SkipLoop extends MempoolLoop {
if (idx == 0 && (item["code"] == 10 || item["code"] == 5)) {
if (toArbTrade?.message.sender) {
this.ignoreAddresses[toArbTrade.message.sender] = {
source: false,
timeout_at: this.iterations,
duration: this.botConfig.skipConfig!.timout_dur,
timeoutAt: this.iterations,
duration: this.botConfig.timeoutDuration,
};
await this.logger?.sendMessage(
"Error on Trade from Address: " + toArbTrade.message.sender,
Expand All @@ -248,11 +225,6 @@ export class SkipLoop extends MempoolLoop {
if (res.result.code != 4) {
this.cdPaths(arbTrade.path);
}

if (this.botConfig.skipConfig.trywithout && res.result.code === 4) {
await this.trade(arbTrade);
}

if (res.result.code === 0) {
this.chainOperator.client.sequence = this.chainOperator.client.sequence + 1;
}
Expand Down
17 changes: 9 additions & 8 deletions src/core/types/base/botConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import axios from "axios";
import { assert } from "console";

import { NativeAssetInfo } from "./asset";
import { IgnoredAddresses } from "./mempool";

interface SkipConfig {
useSkip: boolean;
skipRpcUrl: string;
skipBidWallet: string;
skipBidRate: number;
trywithout: boolean;
timout_dur: number;
tryWithoutSkip: boolean;
}

interface LoggerConfig {
Expand All @@ -28,7 +28,7 @@ export interface BotConfig {
grpcUrl: string;
restUrl: string;
useRpcUrlScraper: boolean;
ignoreAddresses: { [index: string]: { source: boolean; timeout_at: number; duration: number } };
ignoreAddresses: IgnoredAddresses;
poolEnvs: Array<{ pool: string; inputfee: number; outputfee: number; LPratio: number }>;
maxPathPools: number;
mappingFactoryRouter: Array<{ factory: string; router: string }>;
Expand All @@ -37,6 +37,7 @@ export interface BotConfig {
offerAssetInfo: NativeAssetInfo;
mnemonic: string;
useMempool: boolean;
timeoutDuration: number;
baseDenom: string;
gasDenom: string;
signOfLife: number;
Expand Down Expand Up @@ -89,12 +90,12 @@ export async function setBotConfig(envs: NodeJS.ProcessEnv): Promise<BotConfig>

const GAS_USAGE_PER_HOP = +envs.GAS_USAGE_PER_HOP;
const MAX_PATH_HOPS = +envs.MAX_PATH_HOPS; //required gas units per trade (hop)

const IGNORE_ADDRS: { [index: string]: { source: boolean; timeout_at: number; duration: number } } = {};
const timeoutDuration = envs.TIMEOUT_DURATION === undefined ? 100 : Number(envs.TIMEOUT_DURATION);
const IGNORE_ADDRS: IgnoredAddresses = {};
// set ignored Addresses
if (envs.IGNORE_ADDRESSES) {
const addrs = JSON.parse(envs.IGNORE_ADDRESSES);
addrs.forEach((element: string) => (IGNORE_ADDRS[element] = { source: true, timeout_at: 0, duration: 1000 }));
addrs.forEach((element: string) => (IGNORE_ADDRS[element] = { timeoutAt: 0, duration: timeoutDuration }));
}
// setup skipconfig if present
let skipConfig;
Expand All @@ -105,8 +106,7 @@ export async function setBotConfig(envs: NodeJS.ProcessEnv): Promise<BotConfig>
skipRpcUrl: envs.SKIP_URL ?? "",
skipBidWallet: envs.SKIP_BID_WALLET ?? "",
skipBidRate: envs.SKIP_BID_RATE === undefined ? 0 : +envs.SKIP_BID_RATE,
trywithout: envs.TRY_WO_SKIP === undefined || envs.TRY_WO_SKIP === "0" ? false : true,
timout_dur: envs.TIMEOUT_FOR_DUR === undefined ? 100 : Number(envs.TIMEOUT_FOR_DUR),
tryWithoutSkip: envs.TRY_WITHOUT_SKIP === undefined || envs.TRY_WITHOUT_SKIP === "0" ? false : true,
};
}

Expand Down Expand Up @@ -163,6 +163,7 @@ export async function setBotConfig(envs: NodeJS.ProcessEnv): Promise<BotConfig>
gasPrice: envs.GAS_UNIT_PRICE,
profitThresholds: PROFIT_THRESHOLDS,
txFees: TX_FEES,
timeoutDuration: timeoutDuration,
skipConfig: skipConfig,
loggerConfig: loggerConfig,
signOfLife: SIGN_OF_LIFE,
Expand Down
Loading

0 comments on commit 499e070

Please sign in to comment.