今天來開發判斷方向的函式
什麼是判斷方向呢?簡單的說就是Block裡面交易的Sender和Receiver,為什麼要說判斷方向呢,原因是要開發錢包服務要紀錄資產的進出,之前的文章有提到交易所都會檢查鏈上的每一個Block裡面的transaction,主要是檢查裡面的Sender和Receiver是否有自家的地址,如果Sender是的話那就代表是withdraw(提領),如果是Receiver的話就是Desposit(儲值),以自己使用的錢包服務只需要判斷是withdraw(提領)還是Desposit(儲值),但交易所的會複雜一點,之前提到過交易所在收到儲值後會將裡面的所有資產都轉移到內部的地址,而這個內部的地址是用來提領的,所以會有幾個情況,
Customer(非自家地址)、Hot(交易所用戶地址)、Cold(交易所內部地址)
而自己使用的錢包只需要兩個方向
當清楚方向後就可以開始來撰寫判斷的函式了。
這邊會先定義Enum,在Golang是const
internal/utils.go
const (
Withdraw string = "withdraw"
Deposit = "deposit"
Self = "self"
Nothing = "nothing"
Transfer = "transfer"
)
然後新增我們的判斷方向的函式,常常在測試會有自己轉給自己,所以多了這個判斷
func decideDirection(sender, receiver string) string {
if sender == address {
return Withdraw
} else if receiver == address {
return Deposit
} else if sender == address && receiver == address {
return Self
} else {
return Nothing
}
}
再來是檢查Transactions,HyperBlock是存Transactions list,要逐一檢查是否是EGLD交易或是ESDT交易
func CheckTransactions(transactions []model.Transaction) {
for _, transaction := range transactions {
if transaction.Operation == Transfer {
fmt.Println(decideDirection(transaction.Sender, transaction.Receiver))
}
}
}
程式運行結果,查詢Elrond testnet block hight: 1131724, 錢包地址為:erd1e5jayxfyjm4p07nfeepvc006swfzywzda7yvvhpwn5sg5rwpq00s7f4hfr,
成功顯示方向,下面是完整的internal/utils.go code
package internal
import (
"elrondWallet/internal/model"
"encoding/json"
"fmt"
"github.com/pelletier/go-toml"
"io"
"net/http"
)
const (
Withdraw string = "withdraw"
Deposit = "deposit"
Self = "self"
Nothing = "nothing"
Transfer = "transfer"
)
var (
conf, _ = toml.LoadFile("./configs/config.toml")
address = conf.Get("wallet.address").(string)
)
func HttpGet(url string, model any) {
resp, err := http.Get(url)
if err != nil {
// handle error
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
}
}(resp.Body)
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&model)
if err != nil {
return
}
}
func CheckTransactions(transactions []model.Transaction) {
for _, transaction := range transactions {
if transaction.Operation == Transfer {
fmt.Printf("The derection is: %s", decideDirection(transaction.Sender, transaction.Receiver))
}
}
}
func decideDirection(sender, receiver string) string {
if sender == address {
return Withdraw
} else if receiver == address {
return Deposit
} else if sender == address && receiver == address {
return Self
} else {
return Nothing
}
}
config.toml 增加
[wallet]
address = "erd1e5jayxfyjm4p07nfeepvc006swfzywzda7yvvhpwn5sg5rwpq00s7f4hfr"