/
function_executor.go
113 lines (98 loc) · 2.58 KB
/
function_executor.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
package lib
import (
phoenixchain "github.com/PhoenixGlobal/Phoenix-Chain-SDK"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/commands/chaintool/core"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/ethereum/core/types"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/ethereum/ethclient"
"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/common"
"context"
"encoding/json"
"math/big"
)
type FunctionExecutor struct {
httpEntry string
chainId *big.Int
contractAddr string
credentials *Credentials
}
type CallResponse struct {
Code uint64 `json:"Code"`
Ret json.RawMessage `json:"Ret"`
}
func (fe *FunctionExecutor) SendWithRaw(f *Function) (string, error) {
to := fe.credentials.MustStringToAddress(fe.contractAddr)
data := f.ToBytes()
gasPrice := fe.getDefaultGasPrice(f)
gasLimit := fe.getDefaultGasLimit(f)
chainId := fe.chainId
r, err := fe.doSendRawTx(chainId, to, data, nil, gasPrice, gasLimit)
if err != nil {
return "", err
}
//fmt.Println("[SendWithRaw] Http Response: " + string(r))
return r, nil
}
func (fe *FunctionExecutor) SendWithResult(f *Function, result *string) error {
raw, err := fe.SendWithRaw(f)
if err != nil {
return err
}
*result=raw
return err
}
func (fe *FunctionExecutor) getDefaultGasPrice(f *Function) *big.Int {
price := new(big.Int)
switch f.Type {
default:
price = big.NewInt(0)
}
return price
}
func (fe *FunctionExecutor) getDefaultGasLimit(f *Function) uint64 {
if IsLocalSupportFunction(f.Type) {
return GetGasLimit(f)
} else {
return 0
}
}
func (fe *FunctionExecutor) doSendRawTx(chainId *big.Int, to common.Address, data []byte, value *big.Int, gasPrice *big.Int, gasLimit uint64) (string, error) {
client, err := ethclient.Dial(fe.httpEntry)
if err != nil {
return "", err
}
ctx := context.Background()
if gasPrice.Cmp(big.NewInt(0)) == 0 {
gasPrice, err = client.SuggestGasPrice(ctx)
if err != nil {
return "", err
}
}
fromAddr := fe.credentials.Address()
nonce:=core.GetNonce(fromAddr.String())
//nonce, err := client.NonceAt(ctx, fromAddr, "pending")
//if err != nil {
// return nil, err
//}
if gasLimit == 0 {
msg := phoenixchain.CallMsg{
From: fromAddr,
To: &to,
Gas: 0,
GasPrice: gasPrice,
Value: value,
Data: data,
}
gasLimit, err = client.EstimateGas(ctx, msg)
if err != nil {
return "", err
}
}
tx := types.NewTransaction(nonce, to, value, gasLimit, gasPrice, data)
signedTx, err := fe.credentials.SignTx(tx, chainId)
if err != nil {
return "", err
}
err=client.SendTransaction(ctx, signedTx)
hash:=signedTx.Hash().String()
return hash,err
}