/
transaction_extended.go
119 lines (98 loc) · 2.35 KB
/
transaction_extended.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package core
import (
"context"
"fmt"
)
const defaultTimeToLiveInc = 200
func (b *TxBuilder) SetProtocolParametersAndTTL(
ctx context.Context, retriever ITxDataRetriever, timeToLiveInc uint64,
) error {
if timeToLiveInc == 0 {
timeToLiveInc = defaultTimeToLiveInc
}
protocolParams, err := retriever.GetProtocolParameters(ctx)
if err != nil {
return err
}
tip, err := retriever.GetTip(ctx)
if err != nil {
return err
}
b.SetProtocolParameters(protocolParams).SetTimeToLive(tip.Slot + timeToLiveInc)
return nil
}
type TxInputs struct {
Inputs []TxInput
Sum uint64
}
func GetUTXOsForAmount(ctx context.Context, retriever IUTxORetriever, addr string, desired uint64) (TxInputs, error) {
utxos, err := retriever.GetUtxos(ctx, addr)
if err != nil {
return TxInputs{}, err
}
// Loop through utxos to find first input with enough tokens
// If we don't have this UTXO we need to use more of them
//nolint:prealloc
var (
amountSum = uint64(0)
chosenUTXOs []TxInput
)
for _, utxo := range utxos {
if utxo.Amount >= desired {
return TxInputs{
Inputs: []TxInput{
{
Hash: utxo.Hash,
Index: utxo.Index,
},
},
Sum: utxo.Amount,
}, nil
}
amountSum += utxo.Amount
chosenUTXOs = append(chosenUTXOs, TxInput{
Hash: utxo.Hash,
Index: utxo.Index,
})
if amountSum >= desired {
return TxInputs{
Inputs: chosenUTXOs,
Sum: amountSum,
}, nil
}
}
return TxInputs{}, fmt.Errorf(
"not enough funds to generate the transaction: %d available vs %d required", amountSum, desired)
}
func GetUTXOs(ctx context.Context, retriever IUTxORetriever, addr string, desired uint64) (TxInputs, error) {
utxos, err := retriever.GetUtxos(ctx, addr)
if err != nil {
return TxInputs{}, err
}
//nolint:prealloc
var (
amountSum = uint64(0)
chosenUTXOs []TxInput
)
for _, utxo := range utxos {
amountSum += utxo.Amount
chosenUTXOs = append(chosenUTXOs, TxInput{
Hash: utxo.Hash,
Index: utxo.Index,
})
}
if amountSum >= desired {
return TxInputs{
Inputs: chosenUTXOs,
Sum: amountSum,
}, nil
}
return TxInputs{}, fmt.Errorf(
"not enough funds to generate the transaction: %d available vs %d required", amountSum, desired)
}
func GetOutputsSum(outputs []TxOutput) (receiversSum uint64) {
for _, x := range outputs {
receiversSum += x.Amount
}
return receiversSum
}