frostfs-node/pkg/innerring/processors/settlement/common/util.go
Alex Vanin 3e9c578e62 [] settlement: Use unified details format for all asset transfers
Unified format uses transfer type as the first byte
and extra details next. List of transfer types used in
contracts defined in `details.go`. It includes:
- audit settlement,
- basic income collection,
- basic income distribution.

Signed-off-by: Alex Vanin <alexey@nspcc.ru>
2021-04-08 17:01:00 +03:00

73 lines
1.2 KiB
Go

package common
import (
"math/big"
"github.com/nspcc-dev/neofs-api-go/pkg/owner"
)
type TransferTable struct {
txs map[string]map[string]*TransferTx
}
type TransferTx struct {
From, To *owner.ID
Amount *big.Int
}
func NewTransferTable() *TransferTable {
return &TransferTable{
txs: make(map[string]map[string]*TransferTx),
}
}
func (t *TransferTable) Transfer(tx *TransferTx) {
from, to := tx.From.String(), tx.To.String()
if from == to {
return
}
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)
}
}
}
func TransferAssets(e Exchanger, t *TransferTable, details []byte) {
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)
}
e.Transfer(tx.From, tx.To, tx.Amount, details)
})
}