Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
"dependencies": {
"@0x/contract-addresses": "^8.2.0",
"@indexed-finance/multicall": "^2.0.0",
"@uniswap/sdk-core": "^7.7.2",
"@uniswap/smart-order-router": "^4.21.1",
"@uniswap/v3-sdk": "^3.25.2",
"@uniswap/v4-sdk": "^1.21.4",
"axios": "^0.27.2",
"dotenv": "^16.0.1",
"ethers": "^5.6.8",
Expand Down
3 changes: 2 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const Markets: MarketConfig[] = [
maxSellUnit: 25,
minIntervalSeconds: 60 * 5,
maxIntervalSeconds: 60 * 10,
maxGasValueInGwei: 100
maxGasValueInGwei: 100,
tradeSource: 'UNIV3'
}
]
5 changes: 4 additions & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,7 @@ export const MINIMUM_ALLOWANCE_THRESHOLD = BigNumber.from(1000).mul(10).pow(18);

export const MAX_ALLOWANCE = BigNumber.from(2).pow(256).sub(1);

export const IS_SIMULATION = process.env.IS_SIMULATION === 'false' ? false : true;
export const IS_SIMULATION = process.env.IS_SIMULATION === 'false' ? false : true;

export const V3_SWAP_ROUTER_ADDRESS =
'0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45'
11 changes: 8 additions & 3 deletions src/erc20.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { getProvider, getSigner } from "./provider";
import { ChainId, getContractAddressesForChainOrThrow } from '@0x/contract-addresses';
import { MarketConfig, MarketData, Token } from "./types";
import { ethers } from "ethers";
import { ERC20Abi, IS_SIMULATION, MAX_ALLOWANCE, MINIMUM_ALLOWANCE_THRESHOLD } from "./constants";
import { ERC20Abi, IS_SIMULATION, MAX_ALLOWANCE, MINIMUM_ALLOWANCE_THRESHOLD, V3_SWAP_ROUTER_ADDRESS } from "./constants";
import { Interface } from "ethers/lib/utils";
import { getGasEstimation } from "./gasEstimator";

Expand All @@ -23,8 +23,13 @@ export const prepare = async (marketConfig: MarketConfig): Promise<MarketData> =
const owner = await signer.getAddress();
console.log(`bot address is ${owner}`);


const spender = getContractAddressesForChainOrThrow(chainId).exchangeProxy;
let spender
if(marketConfig.tradeSource === 'UNIV3'){
spender = V3_SWAP_ROUTER_ADDRESS;
}else{
spender = getContractAddressesForChainOrThrow(chainId).exchangeProxy;
}


const tokens = [baseToken, quoteToken];
console.log('fetching metadata');
Expand Down
6 changes: 6 additions & 0 deletions src/provider.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ChainId } from '@0x/contract-addresses';
import { ethers } from 'ethers';

export const CHAIN_ID_BASE = 8453;

export const ropstenProvider = new ethers.providers.JsonRpcProvider(
`https://ropsten.infura.io/v3/${process.env.ROPSTEN_ALCHEMY_KEY}`
Expand Down Expand Up @@ -33,6 +34,10 @@ export const ethProvider = new ethers.providers.JsonRpcProvider(
'https://eth.llamarpc.com', ChainId.Mainnet
)

export const baseProvider = new ethers.providers.JsonRpcProvider(
'https://mainnet.base.org', CHAIN_ID_BASE
)


export const JSON_RPC_PROVIDERS: {
[key: number]: ethers.providers.JsonRpcProvider;
Expand All @@ -44,6 +49,7 @@ export const JSON_RPC_PROVIDERS: {
[ChainId.Fantom]: fantomProvider,
[ChainId.Avalanche]: avalancheProvider,
[ChainId.Mainnet]: ethProvider,
[CHAIN_ID_BASE]: baseProvider,
};

const standardPath = "m/44'/60'/0'/0";
Expand Down
120 changes: 120 additions & 0 deletions src/trade_uniV3.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { BigNumber } from "@ethersproject/bignumber";
import { ethers } from "ethers";
import { formatUnits, parseUnits } from "ethers/lib/utils";
import { IS_SIMULATION } from "./constants";
import { getProvider, getSigner } from "./provider";
import { MarketData } from "./types";
import { getSwapQuote } from "./zerox_service";
import { generateRoute } from "./uniswap-v3/executeTrade";
import { V3_SWAP_ROUTER_ADDRESS } from "./uniswap-v3/constants";




export const executeTrade = async (market: MarketData) => {
const signer = getSigner(market.chainId);
const quoteTokenBalanceUnits = formatUnits(market.quoteTokenBalance.balance, market.quoteTokenBalance.token.decimals);
const isBuy = Math.round(Math.random()) === 0;
const takerAddress = await signer.getAddress();
if (isBuy) {
try {
const sellToken = market.quoteTokenBalance.token.address;
const buyToken = market.baseTokenBalance.token.address;
const sellTokenDecimals = market.quoteTokenBalance.token.decimals;
const buyTokenDecimals = market.baseTokenBalance.token.decimals;
const slippagePercentage = market.slippagePercentage;

let randomBuyAmount = market.minBuyUnit + market.maxBuyUnit * Math.random();
if (randomBuyAmount > market.maxBuyUnit) {
randomBuyAmount = market.maxBuyUnit;
}
if (randomBuyAmount > Number(quoteTokenBalanceUnits)) {
randomBuyAmount = Number(quoteTokenBalanceUnits);
}
const sellAmount = parseUnits(randomBuyAmount.toFixed(6), market.quoteTokenBalance.token.decimals).toString();
if (Number(randomBuyAmount) > market.minBuyUnit) {
const route = await generateRoute({address: takerAddress, chainId: market.chainId, provider: getProvider(market.chainId), tokenIn: {address: sellToken, decimals: sellTokenDecimals }, tokenOut: {address: buyToken, decimals: buyTokenDecimals }, amountIn: Number(sellAmount)}

)

/* if (market.maxGasValueInGwei && quote.data.gasPrice) {
const wei = ethers.utils.parseUnits(String(market.maxGasValueInGwei), 'gwei');
if (BigNumber.from(quote.data.gasPrice).gte(wei)) {
console.log(`gas higher than threshold: current gas: ${ethers.utils.formatUnits(quote.data.gasPrice, "gwei")} gwei`)
return;
}
}*/


if (!IS_SIMULATION) {
if(route){
const tx = await signer.sendTransaction({ data: route.methodParameters?.calldata, to: V3_SWAP_ROUTER_ADDRESS, value: route?.methodParameters?.value });
await tx.wait();

}


}

} else {
console.log('minimum amount to buy not reached, please add more quote Tokens to Bot')
}
} catch (e) {
console.log(e);
console.log('error processing a buy');
}



} else {
try {
const sellToken = market.baseTokenBalance.token.address;
const buyToken = market.quoteTokenBalance.token.address;
const sellTokenDecimals = market.baseTokenBalance.token.decimals;
const buyTokenDecimals = market.quoteTokenBalance.token.decimals;
const slippagePercentage = market.slippagePercentage;
let randomSellAmount = market.minSellUnit + market.maxSellUnit * Math.random();
if (randomSellAmount > market.maxSellUnit) {
randomSellAmount = market.maxSellUnit;
}
const buyAmount = parseUnits(randomSellAmount.toFixed(6), market.quoteTokenBalance.token.decimals).toString();
const route = await generateRoute({address: takerAddress, chainId: market.chainId, provider: getProvider(market.chainId), tokenIn: {address: sellToken, decimals: sellTokenDecimals }, tokenOut: {address: buyToken, decimals: buyTokenDecimals }, amountIn: Number(buyAmount)});

if(!route){
return;
}

console.log();

if (BigNumber.from(route.quote.toExact()).lt(market.baseTokenBalance.balance)) {
//const sellAmount = market.baseTokenBalance.balance.toString();

console.log(`bot doing a sell worth ${randomSellAmount}`);
const route = await generateRoute({address: takerAddress, chainId: market.chainId, provider: getProvider(market.chainId), tokenIn: {address: sellToken, decimals: sellTokenDecimals }, tokenOut: {address: buyToken, decimals: buyTokenDecimals }, amountIn: Number(buyAmount)});
/* if (market.maxGasValueInGwei && quote.data.gasPrice) {
const wei = ethers.utils.parseUnits(String(market.maxGasValueInGwei), 'gwei');
if (BigNumber.from(quote.data.gasPrice).gte(wei)) {
console.log(`gas higher than threshold: current gas: ${ethers.utils.formatUnits(quote.data.gasPrice, "gwei")} gwei`);
return;
}
}*/


if (!IS_SIMULATION) {
if(route){
const tx = await signer.sendTransaction({ data: route.methodParameters?.calldata, to: V3_SWAP_ROUTER_ADDRESS, value: route?.methodParameters?.value });
await tx.wait();

}
}


} else {
console.log('minimum amount to sell not reached, please add more base Tokens to Bot')
}
} catch (e) {
console.log(e);
console.log('error processing a sell');
}
}
}
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export interface MarketConfig {
accountIndex?: number;
slippagePercentage?: number;
maxGasValueInGwei?: number;
tradeSource: 'UNIV3' | 'ZRX_API'
}

export interface MarketData {
Expand Down
38 changes: 38 additions & 0 deletions src/uniswap-v3/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Token } from '@uniswap/sdk-core'
import { FeeAmount } from '@uniswap/v3-sdk'
import { USDC_TOKEN, WETH_TOKEN } from './constants'

// Inputs that configure this example to run
export interface ExampleConfig {
rpc: {
local: string
mainnet: string
}
tokens: {
in: Token
amountIn: number
out: Token
poolFee: number
}
}

// Example Configuration

export const CurrentConfig: ExampleConfig = {
rpc: {
local: 'http://localhost:8545',
mainnet: '',
},
tokens: {
in: USDC_TOKEN,
amountIn: 1000,
out: WETH_TOKEN,
poolFee: FeeAmount.MEDIUM,
},
}

export enum Environment {
LOCAL,
MAINNET,
WALLET_EXTENSION,
}
62 changes: 62 additions & 0 deletions src/uniswap-v3/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// This file stores web3 related constants such as addresses, token definitions, ETH currency references and ABI's

import { SUPPORTED_CHAINS, Token } from '@uniswap/sdk-core'

// Addresses

export const V3_SWAP_ROUTER_ADDRESS =
'0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45'

export const SWAP_ROUTER_ADDRESS = '0xE592427A0AEce92De3Edee1F18E0157C05861564'

export const POOL_FACTORY_CONTRACT_ADDRESS =
'0x1F98431c8aD98523631AE4a59f267346ea31F984'
export const QUOTER_CONTRACT_ADDRESS =
'0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6'

// Currencies and Tokens

export const WETH_TOKEN = new Token(
SUPPORTED_CHAINS[0],
'0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
18,
'WETH',
'Wrapped Ether'
)

export const USDC_TOKEN = new Token(
SUPPORTED_CHAINS[0],
'0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
6,
'USDC',
'USD//C'
)


export const ERC20_ABI = [
// Read-Only Functions
'function balanceOf(address owner) view returns (uint256)',
'function decimals() view returns (uint8)',
'function symbol() view returns (string)',

// Authenticated Functions
'function transfer(address to, uint amount) returns (bool)',
'function approve(address _spender, uint256 _value) returns (bool)',

// Events
'event Transfer(address indexed from, address indexed to, uint amount)',
]

export const WETH_ABI = [
// Wrap ETH
'function deposit() payable',

// Unwrap ETH
'function withdraw(uint wad) public',
]

// Transactions

export const MAX_FEE_PER_GAS = 100000000000
export const MAX_PRIORITY_FEE_PER_GAS = 100000000000
export const TOKEN_AMOUNT_TO_APPROVE_FOR_TRANSFER = 2000
16 changes: 16 additions & 0 deletions src/uniswap-v3/conversion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { BigNumber, ethers } from 'ethers'

const READABLE_FORM_LEN = 4

export function fromReadableAmount(
amount: number,
decimals: number
): BigNumber {
return ethers.utils.parseUnits(amount.toString(), decimals)
}

export function toReadableAmount(rawAmount: number, decimals: number): string {
return ethers.utils
.formatUnits(rawAmount, decimals)
.slice(0, READABLE_FORM_LEN)
}
Loading