|
| 1 | +// Example 05: Read ERC-20 token data using the ERC20 convenience module |
| 2 | +// |
| 3 | +// Requires Anvil running at localhost:8545 with a deployed ERC-20 token. |
| 4 | +// This example demonstrates the API -- it will fail without a deployed contract. |
| 5 | + |
| 6 | +const std = @import("std"); |
| 7 | +const eth = @import("eth"); |
| 8 | + |
| 9 | +pub fn main() !void { |
| 10 | + var buf: [4096]u8 = undefined; |
| 11 | + var stdout_impl = std.fs.File.stdout().writer(&buf); |
| 12 | + const stdout = &stdout_impl.interface; |
| 13 | + |
| 14 | + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; |
| 15 | + defer _ = gpa.deinit(); |
| 16 | + const allocator = gpa.allocator(); |
| 17 | + |
| 18 | + // Connect to local node |
| 19 | + var transport = eth.http_transport.HttpTransport.init(allocator, "http://127.0.0.1:8545"); |
| 20 | + defer transport.deinit(); |
| 21 | + var provider = eth.provider.Provider.init(allocator, &transport); |
| 22 | + |
| 23 | + // Test connection |
| 24 | + _ = provider.getChainId() catch |err| { |
| 25 | + try stdout.print("Failed to connect to RPC: {}\n", .{err}); |
| 26 | + try stdout.print("\nTo run this example, start Anvil:\n anvil\n", .{}); |
| 27 | + try stdout.flush(); |
| 28 | + return; |
| 29 | + }; |
| 30 | + |
| 31 | + // Show the ERC-20 module API |
| 32 | + try stdout.print("ERC-20 Module API:\n\n", .{}); |
| 33 | + try stdout.print("Comptime selectors (zero runtime cost):\n", .{}); |
| 34 | + try stdout.print(" transfer: 0x", .{}); |
| 35 | + for (eth.erc20.selectors.transfer) |b| try stdout.print("{x:0>2}", .{b}); |
| 36 | + try stdout.print("\n balanceOf: 0x", .{}); |
| 37 | + for (eth.erc20.selectors.balanceOf) |b| try stdout.print("{x:0>2}", .{b}); |
| 38 | + try stdout.print("\n approve: 0x", .{}); |
| 39 | + for (eth.erc20.selectors.approve) |b| try stdout.print("{x:0>2}", .{b}); |
| 40 | + try stdout.print("\n totalSupply: 0x", .{}); |
| 41 | + for (eth.erc20.selectors.totalSupply) |b| try stdout.print("{x:0>2}", .{b}); |
| 42 | + try stdout.print("\n\n", .{}); |
| 43 | + |
| 44 | + // Show how you would use it with a real token contract: |
| 45 | + try stdout.print("Usage:\n", .{}); |
| 46 | + try stdout.print(" var token = eth.erc20.ERC20.init(allocator, token_addr, &provider);\n", .{}); |
| 47 | + try stdout.print(" const balance = try token.balanceOf(holder_addr);\n", .{}); |
| 48 | + try stdout.print(" const name = try token.name();\n", .{}); |
| 49 | + try stdout.print(" defer allocator.free(name);\n", .{}); |
| 50 | + try stdout.flush(); |
| 51 | +} |
0 commit comments