forked from stellar/go
/
main.go
105 lines (84 loc) · 1.81 KB
/
main.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
package friendbot
import (
"errors"
"sync"
. "github.com/stellar/go/build"
"github.com/stellar/go/keypair"
"github.com/stellar/go/services/horizon/internal/txsub"
"golang.org/x/net/context"
)
// Bot represents the friendbot subsystem.
type Bot struct {
Submitter *txsub.System
Secret string
Network string
sequence uint64
lock sync.Mutex
}
// Pay funds the account at `address`
func (bot *Bot) Pay(ctx context.Context, address string) (result txsub.Result) {
// establish initial sequence if needed
if bot.sequence == 0 {
result.Err = bot.refreshSequence(ctx)
if result.Err != nil {
return
}
}
var envelope string
envelope, result.Err = bot.makeTx(address)
if result.Err != nil {
return
}
resultChan := bot.Submitter.Submit(ctx, envelope)
select {
case result := <-resultChan:
if result.Err != nil {
bot.refreshSequence(ctx)
}
return result
case <-ctx.Done():
return txsub.Result{Err: txsub.ErrCanceled}
}
}
func (bot *Bot) makeTx(address string) (string, error) {
bot.lock.Lock()
defer bot.lock.Unlock()
tx, err := Transaction(
SourceAccount{bot.Secret},
Sequence{bot.sequence + 1},
Network{bot.Network},
CreateAccount(
Destination{address},
NativeAmount{"10000.00"},
),
)
if err != nil {
return "", err
}
bot.sequence++
txe, err := tx.Sign(bot.Secret)
if err != nil {
return "", err
}
return txe.Base64()
}
func (bot *Bot) refreshSequence(ctx context.Context) error {
bot.lock.Lock()
defer bot.lock.Unlock()
addy := bot.address()
sp := bot.Submitter.Sequences
seqs, err := sp.Get([]string{addy})
if err != nil {
return err
}
seq, ok := seqs[addy]
if !ok {
return errors.New("friendbot account not found")
}
bot.sequence = seq
return nil
}
func (bot *Bot) address() string {
kp := keypair.MustParse(bot.Secret)
return kp.Address()
}