swap.go
TEXT FILE6.7 KB · Public source code for developers, search crawlers and AI agents
1package main
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "math/big"
9 "net/http"
10 "os"
11 "path/filepath"
12 "time"
13
14 "github.com/ethereum/go-ethereum"
15 "github.com/ethereum/go-ethereum/common"
16 "github.com/ethereum/go-ethereum/core/types"
17 "github.com/ethereum/go-ethereum/crypto"
18 "github.com/ethereum/go-ethereum/ethclient"
19)
20
21func callData(signature string, args ...[]byte) []byte {
22 data := append([]byte(nil), crypto.Keccak256([]byte(signature))[:4]...)
23 for _, arg := range args {
24 data = append(data, common.LeftPadBytes(arg, 32)...)
25 }
26 return data
27}
28func run() error {
29 ctx, cancel := context.WithTimeout(context.Background(), 85*time.Second)
30 defer cancel()
31 req, err := http.NewRequestWithContext(ctx, "GET", "http://127.0.0.1:7070/api/v5", nil)
32 if err != nil {
33 return err
34 }
35 resp, err := http.DefaultClient.Do(req)
36 if err != nil {
37 return err
38 }
39 defer resp.Body.Close()
40 var wab struct {
41 Protocol string
42 Version string
43 }
44 if resp.StatusCode != 200 || json.NewDecoder(resp.Body).Decode(&wab) != nil || wab.Protocol != "WAB" {
45 return fmt.Errorf("WAB API preflight failed")
46 }
47 rpc, err := ethclient.DialContext(ctx, "https://ethereum-sepolia-rpc.publicnode.com")
48 if err != nil {
49 return err
50 }
51 defer rpc.Close()
52 chain, err := rpc.ChainID(ctx)
53 if err != nil || chain.Cmp(big.NewInt(11155111)) != 0 {
54 return fmt.Errorf("Sepolia chain check failed: %v", err)
55 }
56 home, err := os.UserHomeDir()
57 if err != nil {
58 return err
59 }
60 privateDir := filepath.Join(home, ".local", "share", "wab-sepolia")
61 raw, err := os.ReadFile(filepath.Join(privateDir, "wallet.key"))
62 if err != nil {
63 return err
64 }
65 key, err := crypto.ToECDSA(raw)
66 clear(raw)
67 if err != nil {
68 return err
69 }
70 owner := crypto.PubkeyToAddress(key.PublicKey)
71 if owner != common.HexToAddress("0x5148e363afbe929a37ef255423e1bd08543687be") {
72 return fmt.Errorf("unexpected lab wallet")
73 }
74 router := common.HexToAddress("0x3bFA4769FB09eefC5a80d6E87c3B9C650f7Ae48E")
75 quoter := common.HexToAddress("0xEd1f6473345F45b75F8179591dd5bA1888cf2FB3")
76 weth := common.HexToAddress("0xfff9976782d46cc05630d1f6ebab18b2324d6b14")
77 usdc := common.HexToAddress("0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238")
78 amount := big.NewInt(1_000_000_000_000_000)
79 tokenBalance := func() (*big.Int, error) {
80 result, err := rpc.CallContract(ctx, ethereum.CallMsg{To: &usdc, Data: callData("balanceOf(address)", owner.Bytes())}, nil)
81 if err != nil {
82 return nil, err
83 }
84 if len(result) != 32 {
85 return nil, fmt.Errorf("invalid token balance reply")
86 }
87 return new(big.Int).SetBytes(result), nil
88 }
89 before, err := tokenBalance()
90 if err != nil {
91 return err
92 }
93 var quote *big.Int
94 var fee int64
95 for _, candidate := range []int64{500, 3000, 10000, 100} {
96 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)
97 if err != nil || len(result) < 32 {
98 continue
99 }
100 output := new(big.Int).SetBytes(result[:32])
101 if output.Sign() > 0 && (quote == nil || output.Cmp(quote) > 0) {
102 quote, fee = output, candidate
103 }
104 }
105 if quote == nil {
106 return fmt.Errorf("no funded Sepolia pool returned a quote")
107 }
108 minOut := new(big.Int).Quo(new(big.Int).Mul(quote, big.NewInt(99)), big.NewInt(100))
109 if minOut.Sign() == 0 {
110 return fmt.Errorf("minimum output rounds to zero")
111 }
112 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)
113 msg := ethereum.CallMsg{From: owner, To: &router, Value: amount, Data: data}
114 simulated, err := rpc.CallContract(ctx, msg, nil)
115 if err != nil || len(simulated) != 32 || new(big.Int).SetBytes(simulated).Cmp(minOut) < 0 {
116 return fmt.Errorf("swap simulation failed: %v", err)
117 }
118 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()}
119 if len(os.Args) == 1 {
120 return json.NewEncoder(os.Stdout).Encode(report)
121 }
122 if len(os.Args) != 2 || os.Args[1] != "--broadcast-testnet" {
123 return fmt.Errorf("unknown argument")
124 }
125 gas, err := rpc.EstimateGas(ctx, msg)
126 if err != nil {
127 return err
128 }
129 price, err := rpc.SuggestGasPrice(ctx)
130 if err != nil {
131 return err
132 }
133 if gas > 400_000 || price.Cmp(big.NewInt(10_000_000_000)) > 0 {
134 return fmt.Errorf("gas exceeds test budget")
135 }
136 nonce, err := rpc.PendingNonceAt(ctx, owner)
137 if err != nil {
138 return err
139 }
140 tx := types.NewTx(&types.LegacyTx{Nonce: nonce, To: &router, Value: amount, Gas: gas + gas/5, GasPrice: price, Data: data})
141 signed, err := types.SignTx(tx, types.LatestSignerForChainID(chain), key)
142 if err != nil {
143 return err
144 }
145 receiptPath := filepath.Join(privateDir, "swap-once.tx")
146 f, err := os.OpenFile(receiptPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
147 if err != nil {
148 return fmt.Errorf("broadcast guard: %w", err)
149 }
150 if _, err = fmt.Fprintln(f, signed.Hash().Hex()); err != nil {
151 f.Close()
152 return err
153 }
154 if err = f.Close(); err != nil {
155 return err
156 }
157 fmt.Fprintln(os.Stderr, "Sepolia swap transaction:", signed.Hash())
158 if err = rpc.SendTransaction(ctx, signed); err != nil {
159 return err
160 }
161 ticker := time.NewTicker(3 * time.Second)
162 defer ticker.Stop()
163 for {
164 receipt, err := rpc.TransactionReceipt(ctx, signed.Hash())
165 if err == nil {
166 if receipt.Status != types.ReceiptStatusSuccessful {
167 return fmt.Errorf("swap reverted")
168 }
169 transferTopic := crypto.Keccak256Hash([]byte("Transfer(address,address,uint256)"))
170 received := new(big.Int)
171 for _, entry := range receipt.Logs {
172 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 {
173 received.Add(received, new(big.Int).SetBytes(entry.Data))
174 }
175 }
176 after, err := tokenBalance()
177 if err != nil {
178 return err
179 }
180 if received.Cmp(minOut) < 0 || new(big.Int).Sub(after, before).Cmp(received) != 0 {
181 return fmt.Errorf("receipt and token balance do not reconcile")
182 }
183 report["swap_tx"] = signed.Hash().Hex()
184 report["block"] = receipt.BlockNumber.String()
185 report["received_usdc_units"] = received.String()
186 report["after_usdc_units"] = after.String()
187 return json.NewEncoder(os.Stdout).Encode(report)
188 }
189 select {
190 case <-ctx.Done():
191 return ctx.Err()
192 case <-ticker.C:
193 }
194 }
195}
196func main() {
197 if err := run(); err != nil {
198 fmt.Fprintln(os.Stderr, err)
199 os.Exit(1)
200 }
201}Read-only source · Select a line number to link directly · Raw download above
