-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: introduce wallet index for saving wallet txn
- Loading branch information
1 parent
4ab4c19
commit a4c78a1
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package blockchain | ||
|
||
import "log" | ||
|
||
type WalletTransactionIndex struct { | ||
BlockHeight int `json:"block_height"` | ||
TransactionIndex int `json:"transaction_index"` | ||
Transaction *Transaction `json:transactions"` | ||
} | ||
|
||
type WalletIndex struct { | ||
Transactions map[string][]*WalletTransactionIndex `json:"transactions"` | ||
} | ||
|
||
func NewWalletIndex() *WalletIndex { | ||
return &WalletIndex{ | ||
Transactions: make(map[string][]*WalletTransactionIndex), | ||
} | ||
} | ||
|
||
func (w *WalletIndex) AddTransaction(address string, blockHeight int, txIndex int, transaction *Transaction) { | ||
if w.Transactions == nil { | ||
w.Transactions = make(map[string][]*WalletTransactionIndex) | ||
} | ||
|
||
wti := &WalletTransactionIndex{ | ||
BlockHeight: blockHeight, | ||
TransactionIndex: txIndex, | ||
Transaction: transaction, | ||
} | ||
|
||
log.Printf("Adding transaction: Address=%s, BlockHeight=%d, TxIndex=%d", address, blockHeight, txIndex) | ||
w.Transactions[address] = append(w.Transactions[address], wti) | ||
log.Printf("Transactions for %s: %+v", address, w.Transactions[address]) | ||
} | ||
|
||
func (w *WalletIndex) CalculateBalance(address string) int { | ||
bal := 0 | ||
|
||
for _, txn := range w.Transactions[address] { | ||
if txn.Transaction.From == address { | ||
bal -= int(txn.Transaction.Value) | ||
} else if txn.Transaction.To == address { | ||
bal += int(txn.Transaction.Value) | ||
} | ||
} | ||
|
||
return bal | ||
} |