GithubHelp home page GithubHelp logo

haehnchen / uniswap-arbitrage-flash-swap Goto Github PK

View Code? Open in Web Editor NEW
431.0 21.0 219.0 196 KB

Uniswap flash swap arbitrage solidity contracts

License: MIT License

Solidity 29.68% JavaScript 70.32%
binance smart-contracts uniswap flashloan flashswap bsc ethereum polygon binance-smart-chain dex

uniswap-arbitrage-flash-swap's Introduction

Uniswap Arbitrage Flash Swap Contract

You want to play with "millions" on the blockchain then try https://uniswap.org/docs/v2/smart-contract-integration/using-flash-swaps/. This contract is able to arbitrage between DEX on the blockchain without providing any own capital. Basically is usable on the Binance Smart Chain and provides callbacks for common DEX, feel free to extend.

This is not a full project, build your or own infrastructure around it!

Links

Transactions

transactions

Improvements

All examples are more or less overengineered for a quick start, so here we have a KISS solution.

  • Reduce overall contract size for low gas fee on deployment
  • Provide a on chain validation contract method to let nodes check arbitrage opportunities
  • Stop arbitrage opportunity execution as soon as possible if its already gone to reduce gas fee on failure
  • Interface callbacks for common DEX on "Binance Smart Chain" are included

Infrastructure

Basically arbitrage opportunity dont last long, your transaction must make it into the next block. So you have <3 seconds watching for opportunities, decide and execute transaction. Sometimes there are also a chance to 2-3 have block, see example below.

[7920960] [6/1/2021, 5:50:37 PM]: alive (bsc-ws-node.nariox.org) - took 308.42 ms
[7920991] [6/1/2021, 5:52:09 PM]: [bsc-ws-node.nariox.org] [BAKE/BNB ape>bakery] Arbitrage opportunity found! Expected profit: 0.007 $2.43 - 0.10%
[7920991] [6/1/2021, 5:52:09 PM] [bsc-ws-node.nariox.org]: [BAKE/BNB ape>bakery] and go:  {"profit":"$1.79","profitWithoutGasCost":"$2.43","gasCost":"$0.64","duration":"539.35 ms","provider":"bsc-ws-node.nariox.org"}
[7920992] [6/1/2021, 5:52:13 PM]: [bsc-ws-node.nariox.org] [BAKE/BNB ape>bakery] Arbitrage opportunity found! Expected profit: 0.007 $2.43 - 0.10%
[7920992] [6/1/2021, 5:52:13 PM] [bsc-ws-node.nariox.org]: [BAKE/BNB ape>bakery] and go:  {"profit":"$1.76","profitWithoutGasCost":"$2.43","gasCost":"$0.67","duration":"556.28 ms","provider":"bsc-ws-node.nariox.org"}
[7921000] [6/1/2021, 5:52:37 PM]: alive (bsc-ws-node.nariox.org) - took 280.54 ms

Requirements / Hints

  • You have a time window of 1000ms every 3 seconds (blocktime on BSC) and you should make it into the next transaction
  • Websocket connection is needed to listen directly for new incoming blocks
  • Public provided Websocket are useless bsc-ws-node.nariox.org simply they are way behind notify new blocks
  • Use a non public provider; or build your own node (light node helps) and better have multiple owns; let the fastest win
  • Spread your transaction execution around all possible providers, first one wins (in any case transactions are only execute once based on nonce)
  • Find suitable pairs with liquidity but not with much transaction
  • You can play with full pair liquidity, but dont be too greedy think of a price impact you would have
  • Common opportunities are just between 0,5 - 1%
  • Do not estimate transaction fee, just calculate it once and provide a static gas limit. Simply its takes to long
  • There is block parameter until the transaction is valid, so you can abort execution eg after +3 blocks
  • Payback is directly calculated by calling the foreign contracts so its project independent (no hardcoded fee calculation)
  • The profit is transferred to the owner / creator of the contract :)

Function

The contract is plain and simple [contracts/Flashswap.sol] some basic hints:

Check arbitrage opportunity between DEX. Read only method the one blockchain

    function check(
        address _tokenBorrow, // example: BUSD
        uint256 _amountTokenPay, // example: BNB => 10 * 1e18
        address _tokenPay, // example: BNB
        address _sourceRouter,
        address _targetRouter
    ) public view returns(int256, uint256) {

Starts the execution. You are able to estimate the gas usage of the function, its also directly validating the opportunity. Its slow depending on connected nodes.

    function start(
        uint _maxBlockNumber,
        address _tokenBorrow, // example BUSD
        uint256 _amountTokenPay,
        address _tokenPay, // our profit and what we will get; example BNB
        address _sourceRouter,
        address _targetRouter,
        address _sourceFactory
    ) external {

As all developers are lazy and just forking projects around without any rename a common implementation is possible. Basically the pair contract call the foreign method of the contract. You can find them the naming in any pair contract inside the swap() method.

Example: https://bscscan.com/address/0x0eD7e52944161450477ee417DE9Cd3a859b14fD0#code: if (data.length > 0) IPancakeCallee(to).pancakeCall(msg.sender, amount0Out, amount1Out, data);

Extend method if needed:

# internal callback 
function execute(address _sender, uint256 _amount0, uint256 _amount1, bytes calldata _data) internal

# foreign methods that get called
function pancakeCall(address _sender, uint256 _amount0, uint256 _amount1, bytes calldata _data) external
function uniswapV2Call(address _sender, uint256 _amount0, uint256 _amount1, bytes calldata _data) external

Run it

Its not a full infrastructure, but a working workflow, if you deploy the contract.

cp env.template .env # replace values inside ".env"
node watcher.js
started: wallet 0xXXXX - gasPrice 5000000000 - contract owner: 0xXXXX
[bsc-ws-node.nariox.org] You are connected on 0xXXXX
[8124531] [6/8/2021, 7:53:20 PM]: [bsc-ws-node.nariox.org] [BUSD/BNB pancake>panther] Arbitrage checked! Expected profit: -0.015 $-4.99 - -0.15%
[8124532] [6/8/2021, 7:53:21 PM]: [bsc-ws-node.nariox.org] [BUSD/BNB pancake>panther] Arbitrage checked! Expected profit: -0.015 $-4.99 - -0.15%
[8124533] [6/8/2021, 7:53:24 PM]: [bsc-ws-node.nariox.org] [BUSD/BNB pancake>panther] Arbitrage checked! Expected profit: -0.014 $-4.71 - -0.14%
[8124534] [6/8/2021, 7:53:27 PM]: [bsc-ws-node.nariox.org] [BUSD/BNB pancake>panther] Arbitrage checked! Expected profit: -0.014 $-4.61 - -0.14%

Hints

  • Designed to have multiple chain connectivities, play with some non public providers to be faster then the public once. Its all designed as "first win"

uniswap-arbitrage-flash-swap's People

Contributors

haehnchen avatar rodolfopatane avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uniswap-arbitrage-flash-swap's Issues

Weird profits

Hi,

Thanks for sharing this code.

I'm learning and testing it on the mainnet with default pairs settings. I'm suprised to get such profits.
Is it possible ? is there something i'm missing ?

image

How to add 1 inch support

i have just updated factory and router in address
{
router: "0x11111112542D85B3EF69AE05771c2dCCff4fAa26",
factory: "0xD41B24bbA51fAc0E4827b6F94C0D6DDeB183cD64"
},
in the file
file but getting this error
error Error: Returned error: execution reverted
at Object.ErrorResponse (C:\bsc\node_modules\web3-core-helpers\lib\errors.js:28:19)
at Object.callback (C:\bsc\node_modules\web3-core-requestmanager\lib\index.js:303:36)
at C:\bsc\node_modules\web3-providers-ws\lib\index.js:114:45
at Array.forEach ()
at WebsocketProvider._onMessage (C:\bsc\node_modules\web3-providers-ws\lib\index.js:102:69)
at W3CWebSocket._dispatchEvent [as dispatchEvent] (C:\bsc\node_modules\yaeti\lib\EventTarget.js:115:12)
at W3CWebSocket.onMessage (C:\bsc\node_modules\websocket\lib\W3CWebSocket.js:234:14)
at WebSocketConnection. (C:\bsc\node_modules\websocket\lib\W3CWebSocket.js:205:19)
at WebSocketConnection.emit (events.js:376:20)
at WebSocketConnection.processFrame (C:\bsc\node_modules\websocket\lib\WebSocketConnection.js:554:26)
at C:\bsc\node_modules\websocket\lib\WebSocketConnection.js:323:40
at processTicksAndRejections (internal/process/task_queues.js:77:11) {
data: null
}
^C

Please help me Out thanks in advance !!!

TypeError

Getting a js TypeError
F650C680-453E-4B71-96D1-45A0A85249ED
saying "request" is not a function. Was wondering how to fix this?

No suitable peers available

When broadcasting a lot of read operations to the contracts to own BSC light node - it starts giving the following errors:

Error: Returned error: getDeleteStateObject (0x0000000...) error: no suitable peers available

Why you return a int on check function?

I don't understand why you are returning a int, when probably your most chances of get arbitrages are close to 1.00XXX
and you have to sub and estimated gas fee

Swap pairs

Firstly, thanks for sharing this code with us. I am looking for the part to input pairs to swap. Do we have to input them manually or will the code look for the best pair on the dex and go through with the flashswap?

no working example

Hi,

Looks like part of the code is missing. Please could you share a working example?

Thanks

After Change Token address getting error

const BNB_MAINNET = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c';
const BUSD_MAINNET = '0x3710cd84e0e331c99c70a34b8c6c136c2cdf91c4';

const prices = {};
const flashswap = new web3.eth.Contract(FlashswapApi, FLASHSWAP_CONTRACT);

const pairs = [
{
name: 'BUSD/BNB pancake>panther',
tokenBorrow: BUSD_MAINNET,
amountTokenPay: 10,

Error msg
error Error: Returned error: execution reverted
at Object.ErrorResponse (C:\not\node_modules\web3-core-helpers\lib\errors.js:28:19)
at Object.callback (C:\not\node_modules\web3-core-requestmanager\lib\index.js:303:36)
at C:\not\node_modules\web3-providers-ws\lib\index.js:114:45
at Array.forEach ()
at WebsocketProvider._onMessage (C:\not\node_modules\web3-providers-ws\lib\index.js:102:69)
at W3CWebSocket._dispatchEvent [as dispatchEvent] (C:\not\node_modules\yaeti\lib\EventTarget.js:115:12)
at W3CWebSocket.onMessage (C:\not\node_modules\websocket\lib\W3CWebSocket.js:234:14)
at WebSocketConnection. (C:\not\node_modules\websocket\lib\W3CWebSocket.js:205:19)
at WebSocketConnection.emit (events.js:376:20)
at WebSocketConnection.processFrame (C:\not\node_modules\websocket\lib\WebSocketConnection.js:554:26)
at C:\not\node_modules\websocket\lib\WebSocketConnection.js:323:40
at processTicksAndRejections (internal/process/task_queues.js:77:11) {
data: null

Light node error

Installed lite client node and its running
Stats of node
curl http://127.0.0.1:27147/status
{
"jsonrpc": "2.0",
"id": "",
"result": {
"node_info": {
"protocol_version": {
"p2p": "7",
"block": "10",
"app": "0"
},
"id": "782303c9060d46211225662fdd1dd411c638263a",
"listen_addr": "52.197.243.252:27146",
"network": "Binance-Chain-Tigris",
"version": "0.32.3",
"channels": "36402021222330380041",
"moniker": "data-seed-0",
"other": {
"tx_index": "on",
"rpc_address": "tcp://0.0.0.0:27147"
}
},
"sync_info": {
"latest_block_hash": "2EA1BC407C5F9EFB18888B1FF82A96FE491B4516A320E03C5900 B189DF10B98C",
"latest_app_hash": "4131F9E2D980A426FA831830688178DD3F742760083D1E72322A53 BF59F1CC13",
"latest_block_height": "171146334",
"latest_block_time": "2021-06-21T18:15:13.448450195Z",
"catching_up": false,
"index_height": "171146334"
},
"validator_info": {
"address": "A88BAB486162E44380AA456DFA7C1DCD997985D9",
"pub_key": {
"type": "tendermint/PubKeyEd25519",
"value": "TYgEeiyMDbt8drIPkoyAMcISvlTNVQGU6NUsL4uWEG0="
},
"voting_power": "0"
}
}

.env file updated with
WSS_BLOCKS=tcp://127.0.0.1:27147
BSC_HTTPS=http://127.0.0.1:27147

Any idea what's missing ? please help me out !!!

Nodes (Quicknode, own AWS light node, public node)

So Quicknode BSC mainnet gives the best latency of less than 80ms.

Own AWS light node at lightsale with largest ($160/month instance) gives about 800 ms latency, script is running on the same server as my node.

Public BSC ws node that comes by defaut has about 500ms latency.

500 ms is not enough as all transactions fail with the error "e00" in the contract.

Which node do you use? The region, configuration?

Not a single opportunity with Full Node

After 5 days running my own full node on AWS, I didn't get a single opportunity found. I'm monitoring 5 pairs at same time. I tried also with only 1 with no results. German zone.

I'm not sure where I should start optimizing. Any thoughts?

Coingecko Prices

Hey from my knowledge Coingecko prices are kinda behind do you know how to implement other possibility to get prices maybe from coinmarketcap api?

deploy not working

im trying to deploy: truffle migrate --network mainnet

nothing happens
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.