Skip to content

Commit

Permalink
Add Uniswap E2E tests (0xPolygonHermez#600)
Browse files Browse the repository at this point in the history
  • Loading branch information
tclemos authored Apr 22, 2022
1 parent a67a447 commit 32a3dac
Show file tree
Hide file tree
Showing 6 changed files with 198 additions and 112 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,13 @@ build-docker: ## Builds a docker image with the core binary

.PHONY: test
test: compile-scs ## Runs only short tests without checking race conditions
$(STOPDB) || true
$(STOPDB)
$(RUNDB); sleep 5
trap '$(STOPDB)' EXIT; go test -short -p 1 ./...

.PHONY: test-full
test-full: build-docker compile-scs ## Runs all tests checking race conditions
$(STOPDB) || true
$(STOPDB)
$(RUNDB); sleep 5
trap '$(STOPDB)' EXIT; MallocNanoZone=0 go test -race -p 1 -timeout 600s ./...

Expand Down
68 changes: 45 additions & 23 deletions scripts/deploy_sc/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"fmt"
"math/big"
"strings"
"time"
Expand All @@ -18,6 +19,7 @@ import (
"github.com/hermeznetwork/hermez-core/test/contracts/bin/Counter"
"github.com/hermeznetwork/hermez-core/test/contracts/bin/ERC20"
"github.com/hermeznetwork/hermez-core/test/contracts/bin/EmitLog"
"github.com/hermeznetwork/hermez-core/test/contracts/bin/Storage"
)

const (
Expand All @@ -42,56 +44,53 @@ func main() {

balance, err := client.BalanceAt(ctx, auth.From, nil)
chkErr(err)

log.Debugf("ETH Balance for %v: %v", auth.From, balance)

// Valid ETH Transfer
to := common.HexToAddress(receiverAddr)
amount, _ := big.NewInt(0).SetString("9000000000000000000", encoding.Base10)
tx := ethTransfer(ctx, client, auth, to, amount, nil)

// Invalid ETH Transfer
amount, _ = big.NewInt(0).SetString("9000000000000000000", encoding.Base10)
nonce := tx.Nonce() + 1
ethTransfer(ctx, client, auth, to, amount, &nonce)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
chkErr(err)

// Counter
log.Debugf("Sending TX to deploy Counter SC")
_, tx, counterSC, err := Counter.DeployCounter(auth, client)
chkErr(err)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
chkErr(err)
log.Debugf("Calling Increment method from Counter SC")
tx, err = counterSC.Increment(auth)
chkErr(err)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
chkErr(err)
fmt.Println()

// EmitLog
log.Debugf("Sending TX to deploy EmitLog SC")
_, tx, emitLogSC, err := EmitLog.DeployEmitLog(auth, client)
chkErr(err)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
chkErr(err)
log.Debugf("Calling EmitLogs method from EmitLog SC")
tx, err = emitLogSC.EmitLogs(auth)
chkErr(err)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
chkErr(err)
fmt.Println()

// ERC20
mintAmount, _ := big.NewInt(0).SetString("1000000000000000000000", encoding.Base10)
log.Debugf("Sending TX to deploy ERC20 SC")
_, tx, erc20SC, err := ERC20.DeployERC20(auth, client, "Test Coin", "TCO")
chkErr(err)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
chkErr(err)
log.Debugf("Sending TX to do a ERC20 mint")
tx, err = erc20SC.Mint(auth, mintAmount)
chkErr(err)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
chkErr(err)
transferAmount, _ := big.NewInt(0).SetString("900000000000000000000", encoding.Base10)
log.Debugf("Sending TX to do a ERC20 transfer")
tx, err = erc20SC.Transfer(auth, common.HexToAddress(receiverAddr), transferAmount)
chkErr(err)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
chkErr(err)
fmt.Println()

// // invalid transfer - no enough balance
// // TODO: Check how to by pass the nonce automatically generated by the code to allow this transaction to be sent
Expand All @@ -102,17 +101,40 @@ func main() {
// _, err = scripts.WaitTxToBeMined(client, tx.Hash(), txMinedTimeoutLimit)
// chkErr(err)

// TODO: Deployment of this SC is not working at the moment, issue: https://github.com/hermeznetwork/hermez-core/issues/582
// Storage
// const numberToStore = 22
// _, tx, storageSC, err := Storage.DeployStorage(auth, client)
// chkErr(err)
// _, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
// chkErr(err)
// tx, err = storageSC.Store(auth, big.NewInt(numberToStore))
// chkErr(err)
// _, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
// chkErr(err)
const numberToStore = 22
log.Debugf("Sending TX to deploy Storage SC")
_, tx, storageSC, err := Storage.DeployStorage(auth, client)
chkErr(err)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
chkErr(err)
log.Debugf("Calling Store method from Storage SC")
tx, err = storageSC.Store(auth, big.NewInt(numberToStore))
chkErr(err)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
chkErr(err)
fmt.Println()

// Valid ETH Transfer
balance, err = client.BalanceAt(ctx, auth.From, nil)
log.Debugf("ETH Balance for %v: %v", auth.From, balance)
chkErr(err)
const halfDivision = 2
transferAmount = balance.Quo(balance, big.NewInt(halfDivision))
log.Debugf("Transfer Amount: %v", transferAmount)

log.Debugf("Sending TX to transfer ETH")
to := common.HexToAddress(receiverAddr)
tx = ethTransfer(ctx, client, auth, to, transferAmount, nil)
fmt.Println()

// Invalid ETH Transfer
log.Debugf("Sending Invalid TX to transfer ETH")
nonce := tx.Nonce() + 1
ethTransfer(ctx, client, auth, to, transferAmount, &nonce)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
chkErr(err)
fmt.Println()
}

func ethTransfer(ctx context.Context, client *ethclient.Client, auth *bind.TransactOpts, to common.Address, amount *big.Int, nonce *uint64) *types.Transaction {
Expand Down
4 changes: 0 additions & 4 deletions scripts/init_network/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,10 +311,6 @@ func sendL2Claim(ctx context.Context, auth *bind.TransactOpts, client *ethclient
log.Infof("waiting L2 Claim tx to be mined")
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
chkErr(err)

log.Infof("wait for the consolidation")
const timeToWaitForTheConsolidation = 30 * time.Second
time.Sleep(timeToWaitForTheConsolidation)
}

func chkErr(err error) {
Expand Down
93 changes: 18 additions & 75 deletions scripts/uniswap/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ func main() {
fmt.Println()

// Deploy wETH Token, it's required by uniswap to swap ETH by tokens
log.Debugf("Deploying wEth SC")
wEthAddr, tx, wethSC, err := WETH.DeployWETH(auth, client)
chkErr(err)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
Expand All @@ -71,6 +72,7 @@ func main() {
fmt.Println()

// Deploy Uniswap Factory
log.Debugf("Deploying Uniswap Factory")
factoryAddr, tx, factory, err := UniswapV2Factory.DeployUniswapV2Factory(auth, client, auth.From)
chkErr(err)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
Expand All @@ -80,6 +82,7 @@ func main() {
fmt.Println()

// Deploy Uniswap Router
log.Debugf("Deploying Uniswap Router")
routerAddr, tx, router, err := UniswapV2Router02.DeployUniswapV2Router02(auth, client, factoryAddr, wEthAddr)
chkErr(err)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
Expand All @@ -89,6 +92,7 @@ func main() {
fmt.Println()

// Deploy Uniswap Interface Multicall
log.Debugf("Deploying Uniswap Multicall")
multicallAddr, tx, _, err := UniswapInterfaceMulticall.DeployUniswapInterfaceMulticall(auth, client)
chkErr(err)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
Expand All @@ -98,6 +102,7 @@ func main() {
fmt.Println()

// Mint balance to tokens
log.Debugf("Minting ERC20 Tokens")
aMintAmount := "1000000000000000000000"
tx = mintERC20(auth, client, aCoin, aMintAmount)
log.Debugf("Mint A Coin tx: %v", tx.Hash().Hex())
Expand All @@ -112,10 +117,10 @@ func main() {
fmt.Println()

// wrapping eth
wethDepositAmount, _ := big.NewInt(0).SetString("20000000000000000", encoding.Base10)
log.Debugf("Depositing %v ETH for account %v on token wEth", wethDepositAmount.Text(encoding.Base10), auth.From)
wethDepositoAmount := "20000000000000000"
log.Debugf("Depositing %v ETH for account %v on token wEth", wethDepositoAmount, auth.From)
wAuth := getAuth(ctx, client, pk)
wAuth.Value = wethDepositAmount
wAuth.Value, _ = big.NewInt(0).SetString(wethDepositoAmount, encoding.Base10)
tx, err = wethSC.Deposit(auth)
chkErr(err)
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
Expand All @@ -128,16 +133,12 @@ func main() {
fmt.Println()
approveERC20(auth, client, cCoin, routerAddr, cMintAmount)
fmt.Println()
approveERC20(auth, client, wethSC, routerAddr, wethDepositAmount.Text(encoding.Base10))
approveERC20(auth, client, wethSC, routerAddr, wethDepositoAmount)
fmt.Println()

const liquidityAmount = "10000000000000000"
const liquidityAmount = "10000000000000000000"

// Add liquidity to the pool
tx = addLiquidity(auth, client, router, aCoinAddr, wEthAddr, liquidityAmount)
log.Debugf("Add Liquidity to Pair A <-> wEth tx: %v", tx.Hash().Hex())
fmt.Println()

tx = addLiquidity(auth, client, router, aCoinAddr, bCoinAddr, liquidityAmount)
log.Debugf("Add Liquidity to Pair A <-> B tx: %v", tx.Hash().Hex())
fmt.Println()
Expand All @@ -147,75 +148,16 @@ func main() {
fmt.Println()

// Execute swaps
const swapExactAmountInNumber = 1000
const swapExactAmountInNumber = 1000000000000000000
swapExactAmountIn := big.NewInt(swapExactAmountInNumber)
ethAuth := getAuth(ctx, client, pk)
ethAuth.Value = swapExactAmountIn
swapExactETHForTokens(auth, client, factory, router, aCoinAddr)
swapExactTokensForETH(auth, client, factory, router, aCoinAddr, swapExactAmountIn)
swapExactTokensForTokens(auth, client, factory, router, aCoinAddr, bCoinAddr, swapExactAmountIn)

// swapETHForExactTokens()
// swapTokensForExactETH()
// swapTokensForExactTokens()
}

func swapExactETHForTokens(auth *bind.TransactOpts, client *ethclient.Client,
factory *UniswapV2Factory.UniswapV2Factory, router *UniswapV2Router02.UniswapV2Router02,
token common.Address) {
tokeWeth, err := router.WETH(nil)
chkErr(err)

logPrefix := fmt.Sprintf("swapExactETHForTokens WETH(%v) <-> %v", tokeWeth.Hex(), token.Hex())

pairAddr, err := factory.GetPair(nil, token, tokeWeth)
chkErr(err)
log.Debug(logPrefix, " pair: ", pairAddr.Hex())

pairSC, err := UniswapV2Pair.NewUniswapV2Pair(pairAddr, client)
chkErr(err)

pairReserves, err := pairSC.GetReserves(nil)
chkErr(err)
log.Debug(logPrefix, " reserves 0: ", pairReserves.Reserve0, " 1: ", pairReserves.Reserve1, " Block Timestamp: ", pairReserves.BlockTimestampLast)

amountOut, err := router.GetAmountOut(nil, auth.Value, pairReserves.Reserve0, pairReserves.Reserve1)
chkErr(err)

tx, err := router.SwapExactETHForTokens(auth, amountOut, []common.Address{token, tokeWeth}, auth.From, getDeadline())
chkErr(err)
log.Debug(logPrefix, " tx: ", tx.Hash().Hex())
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
chkErr(err)
}

func swapExactTokensForETH(auth *bind.TransactOpts, client *ethclient.Client,
factory *UniswapV2Factory.UniswapV2Factory, router *UniswapV2Router02.UniswapV2Router02,
token common.Address, exactAmountIn *big.Int) {
tokeWeth, err := router.WETH(nil)
chkErr(err)

logPrefix := fmt.Sprintf("swapExactTokensForETH %v <-> WETH(%v)", token.Hex(), tokeWeth.Hex())

pairAddr, err := factory.GetPair(nil, token, tokeWeth)
chkErr(err)
log.Debug(logPrefix, " pair: ", pairAddr.Hex())

pairSC, err := UniswapV2Pair.NewUniswapV2Pair(pairAddr, client)
chkErr(err)

pairReserves, err := pairSC.GetReserves(nil)
chkErr(err)
log.Debug(logPrefix, " reserves 0: ", pairReserves.Reserve0, " 1: ", pairReserves.Reserve1, " Block Timestamp: ", pairReserves.BlockTimestampLast)

amountOut, err := router.GetAmountOut(nil, exactAmountIn, pairReserves.Reserve0, pairReserves.Reserve1)
chkErr(err)
log.Debugf("Swaping tokens from A <-> B")
swapExactTokensForTokens(auth, client, factory, router, aCoinAddr, bCoinAddr, swapExactAmountIn)
fmt.Println()

tx, err := router.SwapExactETHForTokens(auth, amountOut, []common.Address{token, tokeWeth}, auth.From, getDeadline())
chkErr(err)
log.Debug(logPrefix, " tx: ", tx.Hash().Hex())
_, err = scripts.WaitTxToBeMined(client, tx.Hash(), txTimeout)
chkErr(err)
log.Debugf("Swaping tokens from B <-> C")
swapExactTokensForTokens(auth, client, factory, router, bCoinAddr, cCoinAddr, swapExactAmountIn)
fmt.Println()
}

func swapExactTokensForTokens(auth *bind.TransactOpts, client *ethclient.Client,
Expand All @@ -235,6 +177,7 @@ func swapExactTokensForTokens(auth *bind.TransactOpts, client *ethclient.Client,

amountOut, err := router.GetAmountOut(nil, exactAmountIn, pairReserves.Reserve0, pairReserves.Reserve1)
chkErr(err)
log.Debug(logPrefix, " exactAmountIn: ", exactAmountIn, " amountOut: ", amountOut)

tx, err := router.SwapExactTokensForTokens(auth, exactAmountIn, amountOut, []common.Address{tokenA, tokenB}, auth.From, getDeadline())
chkErr(err)
Expand Down
Loading

0 comments on commit 32a3dac

Please sign in to comment.