-
Notifications
You must be signed in to change notification settings - Fork 9
/
compile.go
83 lines (71 loc) · 2.17 KB
/
compile.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
package api
import (
"strings"
chainjson "github.com/bytom/vapor/encoding/json"
"github.com/bytom/vapor/equity/compiler"
"github.com/bytom/vapor/errors"
"github.com/bytom/vapor/protocol/vm"
)
// pre-define contract error types
var (
ErrCompileContract = errors.New("compile contract failed")
ErrInstContract = errors.New("instantiate contract failed")
)
type (
compileReq struct {
Contract string `json:"contract"`
Args []compiler.ContractArg `json:"args"`
}
compileResp struct {
Name string `json:"name"`
Source string `json:"source"`
Program chainjson.HexBytes `json:"program"`
Params []*compiler.Param `json:"params"`
Value string `json:"value"`
Clauses []*compiler.Clause `json:"clause_info"`
Opcodes string `json:"opcodes"`
Error string `json:"error"`
}
)
func compileEquity(req compileReq) (*compileResp, error) {
compiled, err := compiler.Compile(strings.NewReader(req.Contract))
if err != nil {
return nil, errors.WithDetail(ErrCompileContract, err.Error())
}
// if source contract maybe contain import statement, multiple contract objects will be generated
// after the compilation, and the last object is what we need.
contract := compiled[len(compiled)-1]
resp := &compileResp{
Name: contract.Name,
Source: req.Contract,
Program: contract.Body,
Value: contract.Value.Amount + " of " + contract.Value.Asset,
Clauses: contract.Clauses,
Opcodes: contract.Opcodes,
}
if req.Args != nil {
resp.Program, err = compiler.Instantiate(contract.Body, contract.Params, contract.Recursive, req.Args)
if err != nil {
return nil, errors.WithDetail(ErrInstContract, err.Error())
}
resp.Opcodes, err = vm.Disassemble(resp.Program)
if err != nil {
return nil, err
}
}
for _, param := range contract.Params {
if param.InferredType != "" {
param.Type = param.InferredType
param.InferredType = ""
}
resp.Params = append(resp.Params, param)
}
return resp, nil
}
func (a *API) compileEquity(req compileReq) Response {
resp, err := compileEquity(req)
if err != nil {
return NewErrorResponse(err)
}
return NewSuccessResponse(&resp)
}