Skip to content

Commit

Permalink
Update README, add examples
Browse files Browse the repository at this point in the history
  • Loading branch information
MDobak committed Nov 17, 2023
1 parent 673e7ba commit 3580793
Show file tree
Hide file tree
Showing 17 changed files with 1,469 additions and 328 deletions.
815 changes: 487 additions & 328 deletions README.md

Large diffs are not rendered by default.

43 changes: 43 additions & 0 deletions examples/abi-enc-dec-prog/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package main

import (
"fmt"

"github.com/defiweb/go-eth/abi"
"github.com/defiweb/go-eth/hexutil"
)

func main() {
// Create ABI type:
dataABI := abi.NewTupleType(
abi.TupleTypeElem{
Name: "intVal",
Type: abi.NewIntType(256),
},
abi.TupleTypeElem{
Name: "boolVal",
Type: abi.NewBoolType(),
},
abi.TupleTypeElem{
Name: "stringVal",
Type: abi.NewStringType(),
},
)

// Encode data:
encodedData := abi.MustEncodeValues(dataABI, 42, true, "Hello, world!")

// Print encoded data:
fmt.Printf("Encoded data: %s\n", hexutil.BytesToHex(encodedData))

// Decode data:
var (
intVal int
boolVal bool
stringVal string
)
abi.MustDecodeValues(dataABI, encodedData, &intVal, &boolVal, &stringVal)

// Print decoded data:
fmt.Printf("Decoded data: %d, %t, %s\n", intVal, boolVal, stringVal)
}
37 changes: 37 additions & 0 deletions examples/abi-enc-dec-struct/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package main

import (
"fmt"

"github.com/defiweb/go-eth/abi"
"github.com/defiweb/go-eth/hexutil"
)

// Data is a struct that represents the data we want to encode and decode.
type Data struct {
IntValue int `abi:"intVal"`
BoolValue bool `abi:"boolVal"`
StringValue string `abi:"stringVal"`
}

func main() {
// Parse ABI type:
dataABI := abi.MustParseStruct(`struct Data { int256 intVal; bool boolVal; string stringVal; }`)

// Encode data:
encodedData := abi.MustEncodeValue(dataABI, Data{
IntValue: 42,
BoolValue: true,
StringValue: "Hello, world!",
})

// Print encoded data:
fmt.Printf("Encoded data: %s\n", hexutil.BytesToHex(encodedData))

// Decode data:
var decodedData Data
abi.MustDecodeValue(dataABI, encodedData, &decodedData)

// Print decoded data:
fmt.Printf("Decoded data: %+v\n", decodedData)
}
30 changes: 30 additions & 0 deletions examples/abi-enc-dec-vars/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package main

import (
"fmt"

"github.com/defiweb/go-eth/abi"
"github.com/defiweb/go-eth/hexutil"
)

func main() {
// Parse ABI type:
dataABI := abi.MustParseStruct(`struct Data { int256 intVal; bool boolVal; string stringVal; }`)

// Encode data:
encodedData := abi.MustEncodeValues(dataABI, 42, true, "Hello, world!")

// Print encoded data:
fmt.Printf("Encoded data: %s\n", hexutil.BytesToHex(encodedData))

// Decode data:
var (
intVal int
boolVal bool
stringVal string
)
abi.MustDecodeValues(dataABI, encodedData, &intVal, &boolVal, &stringVal)

// Print decoded data:
fmt.Printf("Decoded data: %d, %t, %s\n", intVal, boolVal, stringVal)
}
99 changes: 99 additions & 0 deletions examples/call-abi/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package main

import (
"context"
"fmt"

"github.com/defiweb/go-eth/abi"
"github.com/defiweb/go-eth/rpc"
"github.com/defiweb/go-eth/rpc/transport"
"github.com/defiweb/go-eth/types"
)

type Call3 struct {
Target types.Address `abi:"target"`
AllowFailure bool `abi:"allowFailure"`
CallData []byte `abi:"callData"`
}

type Result struct {
Success bool `abi:"success"`
ReturnData []byte `abi:"returnData"`
}

func main() {
// Create transport.
t, err := transport.NewHTTP(transport.HTTPOptions{URL: "https://ethereum.publicnode.com"})
if err != nil {
panic(err)
}

// Create a JSON-RPC client.
c, err := rpc.NewClient(rpc.WithTransport(t))
if err != nil {
panic(err)
}

// Parse contract ABI.
multicall := abi.MustParseSignatures(
"struct Call { address target; bytes callData; }",
"struct Call3 { address target; bool allowFailure; bytes callData; }",
"struct Call3Value { address target; bool allowFailure; uint256 value; bytes callData; }",
"struct Result { bool success; bytes returnData; }",
"function aggregate(Call[] calldata calls) public payable returns (uint256 blockNumber, bytes[] memory returnData)",
"function aggregate3(Call3[] calldata calls) public payable returns (Result[] memory returnData)",
"function aggregate3Value(Call3Value[] calldata calls) public payable returns (Result[] memory returnData)",
"function blockAndAggregate(Call[] calldata calls) public payable returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData)",
"function getBasefee() view returns (uint256 basefee)",
"function getBlockHash(uint256 blockNumber) view returns (bytes32 blockHash)",
"function getBlockNumber() view returns (uint256 blockNumber)",
"function getChainId() view returns (uint256 chainid)",
"function getCurrentBlockCoinbase() view returns (address coinbase)",
"function getCurrentBlockDifficulty() view returns (uint256 difficulty)",
"function getCurrentBlockGasLimit() view returns (uint256 gaslimit)",
"function getCurrentBlockTimestamp() view returns (uint256 timestamp)",
"function getEthBalance(address addr) view returns (uint256 balance)",
"function getLastBlockHash() view returns (bytes32 blockHash)",
"function tryAggregate(bool requireSuccess, Call[] calldata calls) public payable returns (Result[] memory returnData)",
"function tryBlockAndAggregate(bool requireSuccess, Call[] calldata calls) public payable returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData)",
)

// Prepare a calldata.
// In this example we will call the `getCurrentBlockGasLimit` and `getCurrentBlockTimestamp` methods
// on the Multicall3 contract.
calldata := multicall.Methods["aggregate3"].MustEncodeArgs([]Call3{
{
Target: types.MustAddressFromHex("0xcA11bde05977b3631167028862bE2a173976CA11"),
CallData: multicall.Methods["getCurrentBlockGasLimit"].MustEncodeArgs(),
},
{
Target: types.MustAddressFromHex("0xcA11bde05977b3631167028862bE2a173976CA11"),
CallData: multicall.Methods["getCurrentBlockTimestamp"].MustEncodeArgs(),
},
})

// Prepare a call.
call := types.NewCall().
SetTo(types.MustAddressFromHex("0xcA11bde05977b3631167028862bE2a173976CA11")).
SetInput(calldata)

// Call the contract.
b, _, err := c.Call(context.Background(), *call, types.LatestBlockNumber)
if err != nil {
panic(err)
}

// Decode the result.
var (
results []Result
gasLimit uint64
timestamp uint64
)
multicall.Methods["aggregate3"].MustDecodeValues(b, &results)
multicall.Methods["getCurrentBlockGasLimit"].MustDecodeValues(results[0].ReturnData, &gasLimit)
multicall.Methods["getCurrentBlockTimestamp"].MustDecodeValues(results[1].ReturnData, &timestamp)

// Print the result.
fmt.Println("Gas limit:", gasLimit)
fmt.Println("Timestamp:", timestamp)
}
50 changes: 50 additions & 0 deletions examples/call/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package main

import (
"context"
"fmt"
"math/big"

"github.com/defiweb/go-eth/abi"
"github.com/defiweb/go-eth/rpc"
"github.com/defiweb/go-eth/rpc/transport"
"github.com/defiweb/go-eth/types"
)

func main() {
// Create transport.
t, err := transport.NewHTTP(transport.HTTPOptions{URL: "https://ethereum.publicnode.com"})
if err != nil {
panic(err)
}

// Create a JSON-RPC client.
c, err := rpc.NewClient(rpc.WithTransport(t))
if err != nil {
panic(err)
}

// Parse method signature.
balanceOf := abi.MustParseMethod("balanceOf(address)(uint256)")

// Prepare a calldata.
calldata := balanceOf.MustEncodeArgs("0xd8da6bf26964af9d7eed9e03e53415d37aa96045")

// Prepare a call.
call := types.NewCall().
SetTo(types.MustAddressFromHex("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48")).
SetInput(calldata)

// Call balanceOf.
b, _, err := c.Call(context.Background(), *call, types.LatestBlockNumber)
if err != nil {
panic(err)
}

// Decode the result.
var balance *big.Int
balanceOf.MustDecodeValues(b, &balance)

// Print the result.
fmt.Printf("Balance: %s\n", balance.String())
}
35 changes: 35 additions & 0 deletions examples/connect/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

import (
"context"
"fmt"

"github.com/defiweb/go-eth/rpc"
"github.com/defiweb/go-eth/rpc/transport"
)

func main() {
// Create transport.
//
// There are several other transports available:
// - HTTP (NewHTTP)
// - WebSocket (NewWebsocket)
// - IPC (NewIPC)
t, err := transport.NewHTTP(transport.HTTPOptions{URL: "https://ethereum.publicnode.com"})
if err != nil {
panic(err)
}

// Create a JSON-RPC client.
c, err := rpc.NewClient(rpc.WithTransport(t))
if err != nil {
panic(err)
}

// Get the latest block number.
b, err := c.BlockNumber(context.Background())
if err != nil {
panic(err)
}
fmt.Println("Latest block number:", b)
}
38 changes: 38 additions & 0 deletions examples/contract-hra-abi/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import (
"fmt"
"math/big"

"github.com/defiweb/go-eth/abi"
)

func main() {
erc20, err := abi.ParseSignatures(
"function name() public view returns (string)",
"function symbol() public view returns (string)",
"function decimals() public view returns (uint8)",
"function totalSupply() public view returns (uint256)",
"function balanceOf(address _owner) public view returns (uint256 balance)",
"function transfer(address _to, uint256 _value) public returns (bool success)",
"function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)",
"function approve(address _spender, uint256 _value) public returns (bool success)",
"function allowance(address _owner, address _spender) public view returns (uint256 remaining)",
"event Transfer(address indexed _from, address indexed _to, uint256 _value)",
"event Approval(address indexed _owner, address indexed _spender, uint256 _value)",
)
if err != nil {
panic(err)
}

transfer := erc20.Methods["transfer"]
calldata, err := transfer.EncodeArgs(
"0x1234567890123456789012345678901234567890",
big.NewInt(1e18),
)
if err != nil {
panic(err)
}

fmt.Printf("Transfer calldata: 0x%x\n", calldata)
}
Loading

0 comments on commit 3580793

Please sign in to comment.