package main

import (
	"log"
	"math/big"
	"sync-block/dgn"
	"sync-block/er"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

func main() {

	log.SetFlags(log.LstdFlags | log.Lshortfile)

	ethclient, err := dgn.New("http://3.38.62.211:8545", nil)
	er.Check(err)

	pkey := "d81d044cbf69701d2f93807fee2979fd1028657e455a27a7fbb24206c89d2ca3"

	latestblock, err := ethclient.GetLastBlockNumber()
	log.Println("현재 블록", latestblock)
	er.Check(err)

	//당근토큰 주소
	tokenAddr := "0xA7B737851241eB0d8Fa79323e1250c84bCEcc20f"
	fromAddr := "0x87bac811E0792F33AB05d16814954C264CAAe82D"
	toAddr := "0x703FEA5E56cFaF5a30F73a0b663Fe936406485De"
	//toAddr := "0x30482875c734452dee589ce820d9cca59e537f01"

	//_, gasLimit, err := ethclient.GetEstimatedGasLimit(pkey, tokenAddr, "10000")
	//log.Println(gasLimit)
	//return

	balance, err := ethclient.GetBalance(fromAddr)
	er.Check(err)
	log.Println("현재 from 이더 발란스", balance)
	balance, err = ethclient.GetTokenBalance(tokenAddr, fromAddr)
	er.Check(err)
	log.Println("현재 from 토큰 발란스", balance)
	balance, err = ethclient.GetTokenBalance(tokenAddr, toAddr)
	er.Check(err)
	log.Println("현재 to 토큰 발란스", balance)
	//return

	// _, gasLimit, err := ethclient.GetEstimatedGasLimit(tokenAddr, pkey, toAddr, "10000")
	_, gasLimit, err := ethclient.GetEstimatedGasLimit(tokenAddr, pkey, toAddr, big.NewInt(10000))
	// er.Check(err)
	gasPrice, err := ethclient.GetSuggestedGasPrice()
	// er.Check(err)

	// log.Println(gasPrice, gasLimit)
	// return

	txHash, err := ethclient.TransferToken(tokenAddr, pkey, toAddr, big.NewInt(10000), gasPrice, gasLimit)
	log.Println(txHash, err)
	for {
		er.Check(err)
		tx, err := ethclient.GetTxByHash(txHash)
		er.Check(err)
		if tx.BlockNumber != "" {
			break
		}

		time.Sleep(time.Second)
		log.Println("wait...")
	}

	log.Println("토큰 전송 완료")
	balance, err = ethclient.GetTokenBalance(tokenAddr, fromAddr)
	er.Check(err)
	log.Println("현재 from 토큰 발란스", balance)
	balance, err = ethclient.GetTokenBalance(tokenAddr, toAddr)
	er.Check(err)
	log.Println("현재 to 토큰 발란스", balance)

	rct, err := ethclient.GetTxReceipt(txHash)
	er.Check(err)
	log.Println("tx status", rct.Status, rct.GasUsed, rct.CumulativeGasUsed)
	return

}
