forked from eoscanada/eos-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_api_transfer_eos_test.go
70 lines (56 loc) · 1.88 KB
/
example_api_transfer_eos_test.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
package eos_test
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"os"
eos "github.com/eoscanada/eos-go"
"github.com/eoscanada/eos-go/token"
)
func ExampleAPI_PushTransaction_transfer_EOS() {
api := eos.New(getAPIURL())
keyBag := &eos.KeyBag{}
err := keyBag.ImportPrivateKey(context.Background(), readPrivateKey())
if err != nil {
panic(fmt.Errorf("import private key: %w", err))
}
api.SetSigner(keyBag)
from := eos.AccountName("eosuser1")
to := eos.AccountName("eosuser2")
quantity, err := eos.NewEOSAssetFromString("1.0000 EOS")
memo := ""
if err != nil {
panic(fmt.Errorf("invalid quantity: %w", err))
}
txOpts := &eos.TxOptions{}
if err := txOpts.FillFromChain(context.Background(), api); err != nil {
panic(fmt.Errorf("filling tx opts: %w", err))
}
tx := eos.NewTransaction([]*eos.Action{token.NewTransfer(from, to, quantity, memo)}, txOpts)
signedTx, packedTx, err := api.SignTransaction(context.Background(), tx, txOpts.ChainID, eos.CompressionNone)
if err != nil {
panic(fmt.Errorf("sign transaction: %w", err))
}
content, err := json.MarshalIndent(signedTx, "", " ")
if err != nil {
panic(fmt.Errorf("json marshalling transaction: %w", err))
}
fmt.Println(string(content))
fmt.Println()
response, err := api.PushTransaction(context.Background(), packedTx)
if err != nil {
panic(fmt.Errorf("push transaction: %w", err))
}
fmt.Printf("Transaction [%s] submitted to the network succesfully.\n", hex.EncodeToString(response.Processed.ID))
}
func readPrivateKey() string {
// Right now, the key is read from an environment variable, it's an example after all.
// In a real-world scenario, would you probably integrate with a real wallet or something similar
envName := "EOS_GO_PRIVATE_KEY"
privateKey := os.Getenv(envName)
if privateKey == "" {
panic(fmt.Errorf("private key environment variable %q must be set", envName))
}
return privateKey
}