-
Notifications
You must be signed in to change notification settings - Fork 212
/
vault.go
92 lines (76 loc) · 2.15 KB
/
vault.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package vault
import (
"errors"
"math/big"
"github.com/spacemeshos/go-scale"
"github.com/spacemeshos/go-spacemesh/genvm/core"
)
var (
// ErrNotOwner is raised if Spend is not executed by a principal that matches owner.
ErrNotOwner = errors.New("vault: not an owner")
// ErrAmountNotAvailable if Spend overlows available amount (see method with the same name).
ErrAmountNotAvailable = errors.New("vault: amount not available")
)
const (
VAULT_STATE_SIZE = core.ACCOUNT_HEADER_SIZE + 56
DRAINED_SIZE = 8
)
//go:generate scalegen
type Vault struct {
Owner core.Address
TotalAmount uint64
InitialUnlockAmount uint64
VestingStart core.LayerID
VestingEnd core.LayerID
DrainedSoFar uint64
}
func (v *Vault) isOwner(address core.Address) bool {
return v.Owner == address
}
func (v *Vault) Available(lid core.LayerID) uint64 {
if lid.Before(v.VestingStart) {
return 0
}
if !lid.Before(v.VestingEnd) {
return v.TotalAmount
}
incremental := new(big.Int).SetUint64(v.TotalAmount - v.InitialUnlockAmount)
incremental.Mul(incremental, new(big.Int).SetUint64(uint64(lid.Difference(v.VestingStart))))
incremental.Div(incremental, new(big.Int).SetUint64(uint64(v.VestingEnd.Difference(v.VestingStart))))
return v.InitialUnlockAmount + incremental.Uint64()
}
// Spend transaction.
func (v *Vault) Spend(host core.Host, to core.Address, amount uint64) error {
if !v.isOwner(host.Principal()) {
return ErrNotOwner
}
available := v.Available(host.Layer())
if available > v.TotalAmount {
panic("wrong math")
}
if amount > available-v.DrainedSoFar {
return ErrAmountNotAvailable
}
if err := host.Transfer(to, amount); err != nil {
return err
}
v.DrainedSoFar += amount
return nil
}
// MaxSpend is noop for this template type, principal of this account type can't submit transactions.
func (v *Vault) MaxSpend(uint8, any) (uint64, error) {
return 0, nil
}
func (v *Vault) BaseGas(uint8) uint64 {
return 0
}
func (v *Vault) LoadGas() uint64 {
return 0
}
func (v *Vault) ExecGas(uint8) uint64 {
return 0
}
// Verify always returns false.
func (v *Vault) Verify(core.Host, []byte, *scale.Decoder) bool {
return false
}