• Stars
    star
    116
  • Rank 303,894 (Top 6 %)
  • Language
    TypeScript
  • Created over 1 year ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Client library for Flashbots MEV-share Matchmaker.

Flashbots MEV-Share Client

Client library for MEV-Share written in Typescript.

Based on MEV-Share Spec.

quickstart

Install from npm:

yarn add @flashbots/mev-share-client
# or
npm i @flashbots/mev-share-client

Alternatively, clone the library & build from source:

git clone https://github.com/flashbots/mev-share-client-ts
cd mev-share-client-ts
yarn install && yarn build
# in your project, assuming it has the same parent directory as mev-share-client-ts
yarn add ../mev-share-client-ts

use mev-share-client in your project

⚠️ Variables denoted in ALL_CAPS are placeholders; the code does not compile. examples/ contains compilable demos.

In your project:

import { Wallet, JsonRpcProvider } from "ethers"
import MevShareClient, {
    BundleParams,
    HintPreferences,
    IPendingBundle,
    IPendingTransaction,
    TransactionOptions
} from "@flashbots/mev-share-client"

const provider = new JsonRpcProvider(RPC_URL)
const authSigner = new Wallet(FB_REPUTATION_PRIVATE_KEY, provider)

The MevShareClient class has built-in initializers for networks supported by Flashbots.

Connect to Ethereum Mainnet

const mevshare = MevShareClient.useEthereumMainnet(authSigner)

Connect to Ethereum Goerli

const mevshare = MevShareClient.useEthereumGoerli(authSigner)

Connect with an Ethers Provider or Chain ID

Networks supported by Flashbots have presets built-in. If it's more convenient, you can instantiate a MevShareClient using a chainId (or a ethers.js Network object, which has a chainId param).

import { JsonRpcProvider, Wallet } from "ethers" // ethers v6

/** connects to Flashbots MEV-Share node on goerli */
const provider = new JsonRpcProvider("http://localhost:8545", {chainId: 5, name: "goerli"})
const authSigner = new Wallet("0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80")
    .connect(provider)

const mevshare = MevShareClient.fromNetwork(authSigner, provider._network)

// manually with a chainId:
const mevshare = MevShareClient.fromNetwork(authSigner, {chainId: 5})

Connect to a custom network

To use custom network parameters, you can instantiate a new MevShareClient instance directly. This example is what the client uses to connect to mainnet:

const mevshare = new MevShareClient(authSigner, {
    name: "mainnet",
    chainId: 1,
    streamUrl: "https://mev-share.flashbots.net",
    apiUrl: "https://relay.flashbots.net"
})

See MevShareNetwork in src/api/interfaces for more details.

examples

Source code

ℹ️ Examples require a .env file (or that you populate your environment directly with the appropriate variables).

cd src/examples
cp .env.example .env
vim .env

send a tx with hints

This example sends a transaction to the Flashbots MEV-Share node on Goerli from the account specified by SENDER_PRIVATE_KEY with a hex-encoded string as calldata.

yarn example.tx

backrun a pending tx

This example watches the mev-share streaming endpoint for pending mev-share transactions and attempts to backrun them all. The example runs until a backrun has been included on-chain.

yarn example.backrun

query event history

This example queries event history, starting from the beginning, until it finds events that share transactions and logs.

yarn example.history

Usage

See src/api/interfaces.ts for interface definitions.

on

Use on to start listening for events on mev-share. The function registers the provided callback to be called when a new event is detected.

const handler = mevshare.on("transaction", (tx: IPendingTransaction) => {
    // handle pending tx
})

// ... before terminating program
handler.close()

sendTransaction

Sends a private transaction to the Flashbots MEV-Share node with specified hint parameters.

const wallet = new Wallet(PRIVATE_KEY)
const tx = {
    to: "0xfb000000387627910184cc42fc92995913806333",
    value: BigInt(1e13 * 275), // price of a beer if ETH is $2000
    data: "0x646f637320626179626565652121",
    gasLimit: 42000,
    maxFeePerGas: BigInt(1e9) * BigInt(42), // 42 gwei / gas
    maxPriorityFeePerGas: BigInt(1e9) * BigInt(2), // 2 gwei / gas
    chainId: 5,
    type: 2,
}

// privacy & inclusion settings
const shareTxParams: TransactionOptions = {
    hints: {
        logs: true,
        calldata: false,
        functionSelector: true,
        contractAddress: true,
    },
    maxBlockNumber: undefined,
    builders: ["flashbots"]
}

const signedTx = await wallet.signTransaction(tx)
await mevshare.sendTransaction(SIGNED_TX, shareTxParams)

sendBundle

Sends a bundle; an array of transactions with parameters to specify conditions for inclusion and MEV kickbacks. Transactions are placed in the body parameter with wrappers to indicate whether they're a new signed transaction or a pending transaction from the event stream.

See MEV-Share Docs for detailed descriptions of these parameters.

const targetBlock = 1 + await provider.getBlockNumber()
const bundleParams: BundleParams = {
    inclusion: {
        block: targetBlock,
    },
    body: [
        {hash: TX_HASH_FROM_EVENT_STREAM},
        {tx: SIGNED_TX, canRevert: false},
    ],
}
await mevshare.sendBundle(bundleParams)

Bundles that only contain signed transactions can share hints about the transactions in their bundle by setting the privacy parameter:

const targetBlock = 1 + await provider.getBlockNumber()
const bundleParams: BundleParams = {
    inclusion: {
        block: targetBlock,
        maxBlock: targetBlock + 5, // allow bundle to land in next 5 blocks
    },
    body: [
        {tx: await wallet.signTransaction(TX1), canRevert: false},
        {tx: await wallet.signTransaction(TX2), canRevert: false},
    ],
    privacy: {
        hints: {
            txHash: true,
            calldata: true,
            logs: true,
            functionSelector: true,
            contractAddress: true,
        },
    }
}
const backrunResult = await mevshare.sendBundle(bundleParams)

simulateBundle

Simulates a bundle. Accepts options to modify block header for simulation.

const bundle: BundleParams = {
    inclusion: {
        block: TARGET_BLOCK,
        maxBlock: TARGET_BLOCK + 3,
    },
    body: [
        {hash: "0xTARGET_TX_HASH"},
        {tx: "0xSIGNED_BACKRUN_TX", canRevert: false}
    ],
    // ...
}

// ...
// assume you sent the bundle and it didn't land, and you want to see if it would have landed in the previous block, but need the tx to think it's in the target block

const simBundleOptions: SimBundleOptions = {
    parentBlock: TARGET_BLOCK - 1,
    blockNumber: TARGET_BLOCK,
    /*
    Set any of these (block header) fields to override their respective values in the simulation context: 
    */
    // coinbase: string,
    // timestamp: number,
    // gasLimit: number,
    // baseFee: bigint,
    // timeout: number,
}

const simResult = await mevshare.simulateBundle(bundle, simBundleOptions)

This example uses the state of parentBlock, but overrides the state's blockNumber value. Setting more fields in SimBundleOptions is useful when testing smart contracts which have specific criteria that must be met, like the block being a certain number, or a specific timestamp having passed.

getEventHistoryInfo

Get information about the event history endpoint for use in getEventHistory.

Example:

const info = await mevshare.getEventHistoryInfo()
console.log(info)

returns something like this:

{
  count: 56934,
  minBlock: 9091377,
  maxBlock: 9190024,
  minTimestamp: 1685452445,
  maxTimestamp: 1686943324,
  maxLimit: 500
}

getEventHistory

Get historical event stream data.

Using the data from our getEventHistoryInfo call, we can read events starting from the beginning. The data is paginated, so to read all of it, you'll have to make multiple calls to iterate through the it.

const info = await mevshare.getEventHistoryInfo()

// read every event
for (let i = 0; i < Math.ceil(info.count / info.maxLimit); i++) {
    const events = await mevshare.getEventHistory({
        limit: info.maxLimit,
        offset: i * info.maxLimit,
        blockStart: info.minBlock,
    })
    console.log(events)
}

You can also filter events by timestamp:

const events = await mevshare.getEventHistory({
    limit: info.maxLimit,
    offset: i * info.maxLimit,
    timestampStart: 1686942023,
})

More Repositories

1

pm

Everything there is to know about Flashbots
2,482
star
2

simple-arbitrage

Example arbitrage bot using Flashbots
TypeScript
1,963
star
3

mev-boost

MEV-Boost allows Ethereum validators to source high-MEV blocks from a competitive builder marketplace
Go
1,172
star
4

mev-research

Project management for MEV Research
884
star
5

mev-inspect-py

🔎 an MEV inspector for Ethereum 🔎
Python
819
star
6

mev-job-board

Need a bot?
727
star
7

ethers-provider-flashbots-bundle

Flashbots provider for ethers.js
TypeScript
548
star
8

mev-inspect-rs

Discover historic Miner Extractable Value (MEV) opportunities
Rust
548
star
9

mev-boost-relay

MEV-Boost Relay for Ethereum proposer/builder separation (PBS)
Go
417
star
10

builder

Flashbots MEV-Boost Block Builder
Go
409
star
11

web3-flashbots

Web3.py plugin for using Flashbots' bundle APIs
Python
405
star
12

searcher-sponsored-tx

TypeScript
360
star
13

simple-blind-arbitrage

Solidity
343
star
14

searcher-minter

Solidity
229
star
15

mempool-dumpster

Dump all the mempool transactions 🗑️ ♻️ (in Parquet + CSV)
Go
206
star
16

flashbots-docs

TypeScript
190
star
17

suave-geth

Go
188
star
18

rpc-endpoint

Flashbots RPC endpoint, to be used with wallets (eg. MetaMask)
Go
180
star
19

mev-share

Protocol for orderflow auctions
129
star
20

hindsight

Retroactively estimate Uniswap-ish MEV on Flashbots MEV-Share by simulating backrun-arbitrages.
Rust
116
star
21

mev-flood

simulates MEV activity from an array of unique searchers; used for testing infra
TypeScript
112
star
22

mev-relay-js

JavaScript
105
star
23

mev-geth-demo

JavaScript
98
star
24

boost-geth-builder

Example builder
Go
93
star
25

mev-share-node

Go
88
star
26

geth-sgx-gramine

Geth-in-SGX provides an example of running go-ethereum in SGX
C
68
star
27

relayscan

Ethereum MEV-Boost Relay Monitoring
Go
67
star
28

eth2-research

Assessing the nature and impact of MEV in eth2.
Jupyter Notebook
66
star
29

mpc-backrun

Proof-of-concept code for backrunning private transactions using MPC.
Python
63
star
30

mev-explore-public

Public repo of MEV-Explore for the community to jam on the dashboard
59
star
31

suapp-examples

SUAVE Application Examples
Go
54
star
32

simple-limit-order-bot

TypeScript
53
star
33

raytracing

Eth2-MEV project with liquid staking (Flashbots-Lido-Nethermind)
Go
52
star
34

builder-playground

Local end-to-end environment for Ethereum L1 block building
Go
51
star
35

reorg-monitor

Ethereum Reorg Monitoring
Go
44
star
36

block-validation-geth

To be deprecated in favor of https://github.com/flashbots/builder
Go
44
star
37

suave-std

Collection of helpful smart contracts to build Suapps
Solidity
43
star
38

rollup-boost

Sidecar to Enable Rollup Extensions
Rust
42
star
39

go-boost-utils

Eth2 builder API types and signing for Golang
Go
41
star
40

suave-specs

☀️ SUAVE Alpha Protocol Specifications
35
star
41

prysm

Our custom Prysm fork for boost relay and builder CL. Sends payload attributes for block building on every slot to trigger building.
Go
34
star
42

sync-proxy

Proxy from consensus client to block builders
Go
33
star
43

go-template

Template for Go projects
Go
33
star
44

suave-viem

Typescript client library to interact with SUAVE.
TypeScript
32
star
45

dowg

Decentralized Orderflow Working Group
31
star
46

suave-andromeda-revm

Andromeda revm execution service
Rust
29
star
47

relay-specs

MEV-Boost Relay API Specs
HTML
28
star
48

prio-load-balancer

Priority JSON-RPC load balancer (with retries, good logging, and other goodies like SGX/SEV attestation support)
Go
27
star
49

mev-proxy

JavaScript
18
star
50

contender

Generate high-volume state contention on EVM-like networks.
Rust
18
star
51

andromeda-sirrah-contracts

forge development env for SUAVE key management
Solidity
18
star
52

flashbots-repository-template

Template to bootstrap and configure new projects maintained by the Flashbots collective
17
star
53

mev-blocks

JavaScript
17
star
54

flashbots-dashboard

TypeScript
17
star
55

flashbots-writings-website

MDX
15
star
56

EIP-712-swap-PoC

Solidity
11
star
57

go-utils

Various reusable Go utilities and modules
Go
11
star
58

eth-sparse-mpt

Caching sparse Merkle Patricia Trie for reth.
Rust
7
star
59

flashbots-airflow-workflows

Python
6
star
60

curve-based-bundle-pricing

Jupyter Notebook
6
star
61

dealer-smart-contract

Integral DEX smart contract
TypeScript
6
star
62

flashbots-data-transparency

Collection, analysis and presentation of Flashbots data.
JavaScript
6
star
63

suave-docs

TypeScript
6
star
64

gramine-andromeda-revm

Python
5
star
65

mev-inspect-logs

Log-based MEV inspections
JavaScript
5
star
66

aleth

C++
5
star
67

research-mev-eip1559

Jupyter Notebook
4
star
68

web3-data-tools

Data tools for Web3
Jupyter Notebook
3
star
69

node-healthchecker

Composite health (sync status) checker for blockchain nodes
Go
3
star
70

yocto-manifests

Repo Manifests for the Yocto Project Build System for reproducible TEE builds
Makefile
3
star
71

builder-olympics-website

HTML
2
star
72

suave-toolchain

JavaScript
2
star
73

protect-explorer

A dashboard designed to illuminate the savings Protect users are enjoying.
TypeScript
2
star
74

prometheus-sns-lambda-slack

Receive prometheus alerts via AWS SNS and publish then to slack channel
Go
2
star
75

flashbots-toolchain

GitHub action to install Flashbots tools
JavaScript
2
star
76

nginx-static-response

nginx image that returns a fixed status code
Dockerfile
1
star
77

yocto-scripts

Shell
1
star
78

rbuilder-relay-measurement

A script to pull data for a specific block number and builder public key from the relay and compare them against those from the builder logs
Python
1
star
79

revm

Revm suited for suave needs
Rust
1
star
80

kube-sidecar-injector

Sidecar injector for k8s
Go
1
star
81

eth-faucet

Faucet for ethereum based chains
Go
1
star