Skip to content

Instantly share code, notes, and snippets.

@trungdlp-wolffun
Created May 20, 2024 04:48
Show Gist options
  • Save trungdlp-wolffun/971f2ec7437bc787cc82f56c7fc98e54 to your computer and use it in GitHub Desktop.
Save trungdlp-wolffun/971f2ec7437bc787cc82f56c7fc98e54 to your computer and use it in GitHub Desktop.
Get THG/USDT price
package main
import (
"fmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/lmittmann/w3"
"github.com/lmittmann/w3/module/eth"
)
var (
pancakeSwapFactory = w3.A("0xca143ce32fe78f1f7019d7d551a6402fc5350c73")
funcGetPair = w3.MustNewFunc("getPair(address, address)", "address")
funcGetReserves = w3.MustNewFunc("getReserves()", "uint112, uint112, uint32")
tokenBNB = w3.A("0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c")
tokenUSDT = w3.A("0x55d398326f99059ff775485246999027b3197955")
tokenTHG = w3.A("0x9fd87aefe02441b123c3c32466cd9db4c578618f")
)
func main() {
// connect to RPC endpoint
client := w3.MustDial("https://binance.llamarpc.com")
defer client.Close()
liquidityPoolAddress := common.Address{} // THG/BNB pair
if err := client.Call(
eth.CallFunc(pancakeSwapFactory, funcGetPair, tokenBNB, tokenTHG).Returns(&liquidityPoolAddress),
); err != nil {
fmt.Printf("Call failed: %v\n", err)
return
}
fmt.Println("THG/BNB liquidity pool address: ", liquidityPoolAddress.Hex())
reserveTHG, reserveBNB, blockTimestampLast := w3.Big0, w3.Big0, uint32(0)
if err := client.Call(
eth.CallFunc(liquidityPoolAddress, funcGetReserves).Returns(&reserveTHG, &reserveBNB, &blockTimestampLast),
); err != nil {
fmt.Printf("Call failed: %v\n", err)
}
fmt.Println("THG/BNB reserves: ", reserveTHG, reserveBNB, time.Unix(int64(blockTimestampLast), 0))
aa := big.NewRat(0, 1).SetInt(reserveTHG)
bb := big.NewRat(0, 1).SetInt(reserveBNB)
zz := new(big.Rat).Quo(bb, aa)
fmt.Println("THG/BNB price: ", zz.FloatString(18))
// =================================
liquidityPoolAddress2 := common.Address{} // THG/BNB pair
if err := client.Call(
eth.CallFunc(pancakeSwapFactory, funcGetPair, tokenBNB, tokenUSDT).Returns(&liquidityPoolAddress2),
); err != nil {
fmt.Printf("Call failed: %v\n", err)
return
}
fmt.Println("USDT/BNB liquidity pool address: ", liquidityPoolAddress2.Hex())
reserveUSDT2, reserveBNB2, blockTimestampLast2 := w3.Big0, w3.Big0, uint32(0)
if err := client.Call(
eth.CallFunc(liquidityPoolAddress2, funcGetReserves).Returns(&reserveUSDT2, &reserveBNB2, &blockTimestampLast2),
); err != nil {
fmt.Printf("Call failed: %v\n", err)
}
aa2 := big.NewRat(0, 1).SetInt(reserveBNB2)
bb2 := big.NewRat(0, 1).SetInt(reserveUSDT2)
zz2 := new(big.Rat).Quo(bb2, aa2)
fmt.Println("USDT/BNB price: ", zz2.FloatString(18))
zz3 := new(big.Rat).Mul(zz, zz2)
fmt.Println("THG/USDT price: ", zz3.FloatString(18))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment