2021-02-01 12:40:07 +00:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math/big"
|
|
|
|
|
2023-03-07 13:38:26 +00:00
|
|
|
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/user"
|
2021-02-01 12:40:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type TransferTable struct {
|
|
|
|
txs map[string]map[string]*TransferTx
|
|
|
|
}
|
|
|
|
|
|
|
|
type TransferTx struct {
|
2022-05-31 17:00:41 +00:00
|
|
|
From, To user.ID
|
2021-02-01 12:40:07 +00:00
|
|
|
|
|
|
|
Amount *big.Int
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewTransferTable() *TransferTable {
|
|
|
|
return &TransferTable{
|
|
|
|
txs: make(map[string]map[string]*TransferTx),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *TransferTable) Transfer(tx *TransferTx) {
|
2022-05-31 17:00:41 +00:00
|
|
|
if tx.From.Equals(tx.To) {
|
2021-02-01 12:40:07 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-05-31 17:00:41 +00:00
|
|
|
from, to := tx.From.EncodeToString(), tx.To.EncodeToString()
|
2021-05-31 10:30:59 +00:00
|
|
|
|
2021-02-01 12:40:07 +00:00
|
|
|
m, ok := t.txs[from]
|
|
|
|
if !ok {
|
|
|
|
if m, ok = t.txs[to]; ok {
|
|
|
|
to = from // ignore `From = To` swap because `From` doesn't require
|
|
|
|
tx.Amount.Neg(tx.Amount)
|
|
|
|
} else {
|
|
|
|
m = make(map[string]*TransferTx, 1)
|
|
|
|
t.txs[from] = m
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
tgt, ok := m[to]
|
|
|
|
if !ok {
|
|
|
|
m[to] = tx
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
tgt.Amount.Add(tgt.Amount, tx.Amount)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *TransferTable) Iterate(f func(*TransferTx)) {
|
|
|
|
for _, m := range t.txs {
|
|
|
|
for _, tx := range m {
|
|
|
|
f(tx)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-07 12:12:36 +00:00
|
|
|
func TransferAssets(e Exchanger, t *TransferTable, details []byte) {
|
2021-02-01 12:40:07 +00:00
|
|
|
t.Iterate(func(tx *TransferTx) {
|
|
|
|
sign := tx.Amount.Sign()
|
|
|
|
if sign == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if sign < 0 {
|
|
|
|
tx.From, tx.To = tx.To, tx.From
|
|
|
|
tx.Amount.Neg(tx.Amount)
|
|
|
|
}
|
|
|
|
|
2021-04-07 12:12:36 +00:00
|
|
|
e.Transfer(tx.From, tx.To, tx.Amount, details)
|
2021-02-01 12:40:07 +00:00
|
|
|
})
|
|
|
|
}
|