昨天優化了專案結構,現在要來開始將前天寫的code給變成函式庫
首先先設定config檔案,使用的是toml格式,目前先放會用到的設定,之後可能還會增加。
title = "Elrond config"
[server]
url = "https://testnet-api.elrond.com"
[savePath]
path = "/data/privateKey/"
今天先來把使用SDK的部分給function化這樣之後可以整理到internal資料夾中,讓各個程式使用,
package main
import (
"fmt"
"github.com/ElrondNetwork/elrond-sdk/erdgo"
"github.com/sethvargo/go-password/password"
)
func generateNewMnemonic() (string, error) {
return erdgo.GenerateNewMnemonic()
}
func getPrivateKeyFromMnemonic(mnemonic string, account, index uint8) []byte {
return erdgo.GetPrivateKeyFromMnemonic(mnemonic, account, index)
}
func getAddressFromPrivateKey(privateKey []byte) (string, error) {
return erdgo.GetAddressFromPrivateKey(privateKey)
}
func savePrivateKeyToPemFile(privateKey []byte, filePath string) error {
return erdgo.SavePrivateKeyToPemFile(privateKey, filePath+".pem")
}
func savePrivateKeyToJsonFile(privateKey []byte, jsonPass, filePath string) error {
return erdgo.SavePrivateKeyToJsonFile(privateKey, jsonPass, filePath)
}
func loadPrivateKeyFromPemFile(filePath string) ([]byte, error) {
return erdgo.LoadPrivateKeyFromPemFile(filePath)
}
func loadPrivateKeyFromJsonFile(filePath, filePass string) ([]byte, error) {
return erdgo.LoadPrivateKeyFromJsonFile(filePath, filePass)
}
func main() {
// 1. get New Mnemonic
mnemonic, _ := generateNewMnemonic()
fmt.Printf("Generated mnemonic: %s \n", mnemonic)
//// 2. get Private Key from Mnemonic
privateKey := getPrivateKeyFromMnemonic(mnemonic, 0, 0)
fmt.Printf("Generated privateKey: %s \n", privateKey)
//// 3. get Address from private key
address, _ := getAddressFromPrivateKey(privateKey)
fmt.Printf("Generated wallet: %s \n", address)
//// 4. export pem file from private key
err := savePrivateKeyToPemFile(privateKey, address+".pem")
if err != nil {
return
}
//// generate password from json
jsonPass, _ := password.Generate(64, 10, 10, false, false)
fmt.Printf("Generated json password: %s \n", jsonPass)
//// 5. export json file from private key
err = savePrivateKeyToJsonFile(privateKey, jsonPass, address+".json")
if err != nil {
return
}
//// 6. import from pem
pemPrivateKey, _ := loadPrivateKeyFromPemFile(address + ".pem")
fmt.Printf("PrivateKey from pem: %s \n", privateKey)
pemAddress, _ := getAddressFromPrivateKey(pemPrivateKey)
fmt.Printf("Address from pem: %s \n", pemAddress)
//// 7. import from json
jsonPrivateKey, _ := loadPrivateKeyFromJsonFile(address+".json", jsonPass)
fmt.Printf("PrivateKey from json: %s \n", jsonPrivateKey)
jsonAddress, _ := getAddressFromPrivateKey(jsonPrivateKey)
fmt.Printf("Address from json: %s \n", jsonAddress)
}
整理好後執行確認結果與之前的一樣
將這些sdk使用方式function化後就可以開始寫test了,越來越有一個專案的結構了。