-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathaccount.go
62 lines (53 loc) · 1.3 KB
/
account.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package digitalwallet
import (
"math/big"
"sync"
)
type Account struct {
ID string
User *User
AccountNumber string
Currency Currency
balance *big.Float
transactions []*Transaction
mu sync.RWMutex
}
func NewAccount(id string, user *User, accountNumber string, currency Currency) *Account {
return &Account{
ID: id,
User: user,
AccountNumber: accountNumber,
Currency: currency,
balance: big.NewFloat(0),
transactions: make([]*Transaction, 0),
}
}
func (a *Account) Deposit(amount *big.Float) {
a.mu.Lock()
defer a.mu.Unlock()
a.balance.Add(a.balance, amount)
}
func (a *Account) Withdraw(amount *big.Float) error {
a.mu.Lock()
defer a.mu.Unlock()
if a.balance.Cmp(amount) >= 0 {
a.balance.Sub(a.balance, amount)
return nil
}
return NewInsufficientFundsError("Insufficient funds in the account")
}
func (a *Account) AddTransaction(transaction *Transaction) {
a.mu.Lock()
defer a.mu.Unlock()
a.transactions = append(a.transactions, transaction)
}
func (a *Account) GetBalance() *big.Float {
a.mu.RLock()
defer a.mu.RUnlock()
return new(big.Float).Copy(a.balance)
}
func (a *Account) GetTransactions() []*Transaction {
a.mu.RLock()
defer a.mu.RUnlock()
return append([]*Transaction{}, a.transactions...)
}