package main import ( "bytes" "context" "encoding/json" "fmt" "math/big" "net/http" "os" "path/filepath" "time" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func callData(signature string, args ...[]byte) []byte { data := append([]byte(nil), crypto.Keccak256([]byte(signature))[:4]...) for _, arg := range args { data = append(data, common.LeftPadBytes(arg, 32)...) } return data } func run() error { ctx, cancel := context.WithTimeout(context.Background(), 85*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, "GET", "http://127.0.0.1:7070/api/v5", nil) if err != nil { return err } resp, err := http.DefaultClient.Do(req) if err != nil { return err } defer resp.Body.Close() var wab struct { Protocol string Version string } if resp.StatusCode != 200 || json.NewDecoder(resp.Body).Decode(&wab) != nil || wab.Protocol != "WAB" { return fmt.Errorf("WAB API preflight failed") } rpc, err := ethclient.DialContext(ctx, "https://ethereum-sepolia-rpc.publicnode.com") if err != nil { return err } defer rpc.Close() chain, err := rpc.ChainID(ctx) if err != nil || chain.Cmp(big.NewInt(11155111)) != 0 { return fmt.Errorf("Sepolia chain check failed: %v", err) } home, err := os.UserHomeDir() if err != nil { return err } privateDir := filepath.Join(home, ".local", "share", "wab-sepolia") raw, err := os.ReadFile(filepath.Join(privateDir, "wallet.key")) if err != nil { return err } key, err := crypto.ToECDSA(raw) clear(raw) if err != nil { return err } owner := crypto.PubkeyToAddress(key.PublicKey) if owner != common.HexToAddress("0x5148e363afbe929a37ef255423e1bd08543687be") { return fmt.Errorf("unexpected lab wallet") } router := common.HexToAddress("0x3bFA4769FB09eefC5a80d6E87c3B9C650f7Ae48E") quoter := common.HexToAddress("0xEd1f6473345F45b75F8179591dd5bA1888cf2FB3") weth := common.HexToAddress("0xfff9976782d46cc05630d1f6ebab18b2324d6b14") usdc := common.HexToAddress("0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238") amount := big.NewInt(1_000_000_000_000_000) tokenBalance := func() (*big.Int, error) { result, err := rpc.CallContract(ctx, ethereum.CallMsg{To: &usdc, Data: callData("balanceOf(address)", owner.Bytes())}, nil) if err != nil { return nil, err } if len(result) != 32 { return nil, fmt.Errorf("invalid token balance reply") } return new(big.Int).SetBytes(result), nil } before, err := tokenBalance() if err != nil { return err } var quote *big.Int var fee int64 for _, candidate := range []int64{500, 3000, 10000, 100} { result, err := rpc.CallContract(ctx, ethereum.CallMsg{To: "er, Data: callData("quoteExactInputSingle((address,address,uint256,uint24,uint160))", weth.Bytes(), usdc.Bytes(), amount.Bytes(), big.NewInt(candidate).Bytes(), nil)}, nil) if err != nil || len(result) < 32 { continue } output := new(big.Int).SetBytes(result[:32]) if output.Sign() > 0 && (quote == nil || output.Cmp(quote) > 0) { quote, fee = output, candidate } } if quote == nil { return fmt.Errorf("no funded Sepolia pool returned a quote") } minOut := new(big.Int).Quo(new(big.Int).Mul(quote, big.NewInt(99)), big.NewInt(100)) if minOut.Sign() == 0 { return fmt.Errorf("minimum output rounds to zero") } data := callData("exactInputSingle((address,address,uint24,address,uint256,uint256,uint160))", weth.Bytes(), usdc.Bytes(), big.NewInt(fee).Bytes(), owner.Bytes(), amount.Bytes(), minOut.Bytes(), nil) msg := ethereum.CallMsg{From: owner, To: &router, Value: amount, Data: data} simulated, err := rpc.CallContract(ctx, msg, nil) if err != nil || len(simulated) != 32 || new(big.Int).SetBytes(simulated).Cmp(minOut) < 0 { return fmt.Errorf("swap simulation failed: %v", err) } report := map[string]any{"chain_id": chain.String(), "wab_version": wab.Version, "address": owner.Hex(), "router": router.Hex(), "token_out": usdc.Hex(), "amount_in_wei": amount.String(), "fee_tier": fee, "quote_usdc_units": quote.String(), "minimum_usdc_units": minOut.String(), "simulated_usdc_units": new(big.Int).SetBytes(simulated).String(), "before_usdc_units": before.String()} if len(os.Args) == 1 { return json.NewEncoder(os.Stdout).Encode(report) } if len(os.Args) != 2 || os.Args[1] != "--broadcast-testnet" { return fmt.Errorf("unknown argument") } gas, err := rpc.EstimateGas(ctx, msg) if err != nil { return err } price, err := rpc.SuggestGasPrice(ctx) if err != nil { return err } if gas > 400_000 || price.Cmp(big.NewInt(10_000_000_000)) > 0 { return fmt.Errorf("gas exceeds test budget") } nonce, err := rpc.PendingNonceAt(ctx, owner) if err != nil { return err } tx := types.NewTx(&types.LegacyTx{Nonce: nonce, To: &router, Value: amount, Gas: gas + gas/5, GasPrice: price, Data: data}) signed, err := types.SignTx(tx, types.LatestSignerForChainID(chain), key) if err != nil { return err } receiptPath := filepath.Join(privateDir, "swap-once.tx") f, err := os.OpenFile(receiptPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) if err != nil { return fmt.Errorf("broadcast guard: %w", err) } if _, err = fmt.Fprintln(f, signed.Hash().Hex()); err != nil { f.Close() return err } if err = f.Close(); err != nil { return err } fmt.Fprintln(os.Stderr, "Sepolia swap transaction:", signed.Hash()) if err = rpc.SendTransaction(ctx, signed); err != nil { return err } ticker := time.NewTicker(3 * time.Second) defer ticker.Stop() for { receipt, err := rpc.TransactionReceipt(ctx, signed.Hash()) if err == nil { if receipt.Status != types.ReceiptStatusSuccessful { return fmt.Errorf("swap reverted") } transferTopic := crypto.Keccak256Hash([]byte("Transfer(address,address,uint256)")) received := new(big.Int) for _, entry := range receipt.Logs { if entry.Address == usdc && len(entry.Topics) == 3 && entry.Topics[0] == transferTopic && bytes.Equal(entry.Topics[2].Bytes()[12:], owner.Bytes()) && len(entry.Data) == 32 { received.Add(received, new(big.Int).SetBytes(entry.Data)) } } after, err := tokenBalance() if err != nil { return err } if received.Cmp(minOut) < 0 || new(big.Int).Sub(after, before).Cmp(received) != 0 { return fmt.Errorf("receipt and token balance do not reconcile") } report["swap_tx"] = signed.Hash().Hex() report["block"] = receipt.BlockNumber.String() report["received_usdc_units"] = received.String() report["after_usdc_units"] = after.String() return json.NewEncoder(os.Stdout).Encode(report) } select { case <-ctx.Done(): return ctx.Err() case <-ticker.C: } } } func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }