Skip to content

Instantly share code, notes, and snippets.

@MaxMoskalenko
Last active February 16, 2023 10:41
Show Gist options
  • Save MaxMoskalenko/f70ba49b3496de3484bf5e321f43ea8d to your computer and use it in GitHub Desktop.
Save MaxMoskalenko/f70ba49b3496de3484bf5e321f43ea8d to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
)
type Transaction struct {
Args []interface{} `json:"args"`
}
const txPath string = "./result/tx/DUCKIES/"
const outputPath string = "./output.sql"
const sqlTemplate string = "INSERT INTO balances (address, balance) VALUES('%s',%d) ON CONFLICT (address) DO UPDATE SET balance = balances.balance + %d;\n"
const zeroAddress string = "0x0000000000000000000000000000000000000000"
func parseHex(hexStr string) int64 {
cleaned := strings.Replace(hexStr, "0x", "", -1)
result, _ := strconv.ParseUint(cleaned, 16, 64)
return int64(result)
}
func walkFunc(path string, writes chan<- string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
bytes, _ := ioutil.ReadAll(f)
var transactions []Transaction
json.Unmarshal(bytes, &transactions)
for _, transaction := range transactions {
value := transaction.Args[2].(map[string]interface{})["hex"]
parsedValue := parseHex(value.(string))
if transaction.Args[0] == zeroAddress { //mint
writes <- fmt.Sprintf(sqlTemplate, transaction.Args[1], parsedValue, parsedValue)
} else if transaction.Args[1] == zeroAddress { //burn
writes <- fmt.Sprintf(sqlTemplate, transaction.Args[0], -parsedValue, -parsedValue)
} else {
writes <- fmt.Sprintf(sqlTemplate, transaction.Args[0], -parsedValue, -parsedValue)
writes <- fmt.Sprintf(sqlTemplate, transaction.Args[1], parsedValue, parsedValue)
}
}
return nil
}
func main() {
f, err := os.Create(outputPath)
if err != nil {
fmt.Println(err)
return
}
w := bufio.NewWriter(f)
var writes = make(chan (string))
go func() {
err = filepath.Walk(txPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
return walkFunc(path, writes)
})
if err != nil {
fmt.Println(err)
return
}
close(writes)
}()
var i uint64 = 0
for record := range writes {
if i%5000 == 0 {
fmt.Println("Number of records", i)
}
w.WriteString(record)
i++
}
w.Flush()
f.Close()
fmt.Println("Success")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment