import Voltaire
// Define ABI (or load from JSON)
let erc20Abi: [AbiItem] = [
.function(
name: "balanceOf",
stateMutability: .view,
inputs: [.init(type: .address, name: "account")],
outputs: [.init(type: .uint256, name: "")]
),
.function(
name: "transfer",
stateMutability: .nonpayable,
inputs: [
.init(type: .address, name: "to"),
.init(type: .uint256, name: "amount")
],
outputs: [.init(type: .bool, name: "")]
),
.event(
name: "Transfer",
inputs: [
.init(type: .address, name: "from", indexed: true),
.init(type: .address, name: "to", indexed: true),
.init(type: .uint256, name: "value", indexed: false)
]
)
]
// Create contract instance
let usdc = Contract(
address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
abi: erc20Abi,
provider: provider
)
// Read balance
let balance: UInt256 = try await usdc.read.balanceOf("0x742d35...")
print("Balance: \(balance)")
// Transfer tokens
let txHash = try await usdc.write.transfer("0x742d35...", 1000)
print("Transaction: \(txHash)")
// Estimate gas
let gas = try await usdc.estimateGas.transfer("0x742d35...", 1000)
print("Gas estimate: \(gas)")
// Stream events
for try await log in usdc.events.Transfer(from: "0x742d35...") {
print("\(log.args.from) -> \(log.args.to): \(log.args.value)")
}