This repository has been archived by the owner on May 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
contract.go
369 lines (316 loc) · 8.37 KB
/
contract.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// Copyright (c) 2020-2022 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package contract
import (
"context"
"fmt"
"blockwatch.cc/tzgo/codec"
"blockwatch.cc/tzgo/micheline"
"blockwatch.cc/tzgo/rpc"
"blockwatch.cc/tzgo/tezos"
)
type CallArguments interface {
WithSource(tezos.Address) CallArguments
WithDestination(tezos.Address) CallArguments
WithAmount(tezos.N) CallArguments
Encode() *codec.Transaction
Parameters() *micheline.Parameters
}
type TxArgs struct {
Source tezos.Address
Destination tezos.Address
Amount tezos.N
Params micheline.Parameters
}
func NewTxArgs() *TxArgs {
return &TxArgs{}
}
func (a *TxArgs) WithSource(addr tezos.Address) CallArguments {
a.Source = addr.Clone()
return a
}
func (a *TxArgs) WithDestination(addr tezos.Address) CallArguments {
a.Destination = addr.Clone()
return a
}
func (a *TxArgs) WithAmount(amount tezos.N) CallArguments {
a.Amount = amount
return a
}
func (a *TxArgs) WithParameters(params micheline.Parameters) {
a.Params = params
}
func (a *TxArgs) Parameters() *micheline.Parameters {
return &a.Params
}
func (a *TxArgs) Encode() *codec.Transaction {
return &codec.Transaction{
Manager: codec.Manager{
Source: a.Source,
},
Destination: a.Destination,
Parameters: &a.Params,
}
}
type Contract struct {
addr tezos.Address // contract address
script *micheline.Script // script (type info + code)
store *micheline.Prim // current storage value
meta *Tz16 // Tzip16 metadata
rpc *rpc.Client // the RPC client to use for queries and calls
}
func NewContract(addr tezos.Address, cli *rpc.Client) *Contract {
return &Contract{
addr: addr,
rpc: cli,
}
}
func NewEmptyContract(cli *rpc.Client) *Contract {
return &Contract{
rpc: cli,
}
}
func (c *Contract) Client() *rpc.Client {
return c.rpc
}
func (c *Contract) Resolve(ctx context.Context) error {
// use normalized script to have the node embed global constants
script, err := c.rpc.GetNormalizedScript(ctx, c.addr, rpc.UnparsingModeReadable)
if err != nil {
return err
}
store, err := c.rpc.GetContractStorage(ctx, c.addr, rpc.Head)
if err != nil {
return err
}
c.script = script
c.store = &store
return nil
}
func (c *Contract) Reload(ctx context.Context) error {
store, err := c.rpc.GetContractStorage(ctx, c.addr, rpc.Head)
if err != nil {
return err
}
c.store = &store
return nil
}
func (c *Contract) ResolveMetadata(ctx context.Context) (*Tz16, error) {
if c.meta != nil {
return c.meta, nil
}
if c.script == nil {
if err := c.Resolve(ctx); err != nil {
return nil, err
}
}
tz16 := &Tz16{}
if err := c.resolveStorageUri(ctx, "tezos-storage:", tz16, nil); err != nil {
return nil, err
}
c.meta = tz16
return tz16, nil
}
func (c *Contract) WithScript(script *micheline.Script) *Contract {
c.script = script
return c
}
func (c *Contract) DecodeScript(data []byte) error {
var script micheline.Script
if err := script.UnmarshalBinary(data); err != nil {
return err
}
c.script = &script
return nil
}
func (c *Contract) WithStorage(store *micheline.Prim) *Contract {
c.store = store
return c
}
func (c *Contract) DecodeStorage(data []byte) error {
var store micheline.Prim
if err := store.UnmarshalBinary(data); err != nil {
return err
}
c.store = &store
return nil
}
func (c Contract) Address() tezos.Address {
return c.addr
}
func (c Contract) IsManagerTz() bool {
return c.script != nil && c.script.Implements(micheline.IManager)
}
func (c Contract) IsToken() bool {
return c.IsFA1() || c.IsFA12() || c.IsFA2()
}
func (c Contract) TokenKind() TokenKind {
switch {
case c.IsFA1():
return TokenKindFA1
case c.IsFA12():
return TokenKindFA1_2
case c.IsFA2():
return TokenKindFA2
default:
return TokenKindInvalid
}
}
func (c Contract) IsFA1() bool {
return c.script != nil && c.script.Implements(micheline.ITzip5)
}
func (c Contract) IsFA12() bool {
return c.script != nil && c.script.Implements(micheline.ITzip7)
}
func (c Contract) IsFA2() bool {
return c.script != nil && c.script.Implements(micheline.ITzip12)
}
// func (c *Contract) IsNFT() bool {}
func (c *Contract) AsFA1() *FA1Token {
return &FA1Token{
Address: c.addr,
contract: c,
}
}
func (c *Contract) AsFA2(id int64) *FA2Token {
fa2 := &FA2Token{
Address: c.addr,
contract: c,
}
fa2.TokenId.SetInt64(id)
return fa2
}
// func (c *Contract) AsNFT() (*NFTToken, error) {}
func (c *Contract) Metadata() *Tz16 {
return c.meta
}
func (c Contract) Script() *micheline.Script {
return c.script
}
func (c Contract) Storage() *micheline.Prim {
return c.store
}
func (c Contract) StorageValue() micheline.Value {
return micheline.NewValue(c.script.StorageType(), *c.store)
}
// entrypoints and callbacks
func (c *Contract) Entrypoint(name string) (micheline.Entrypoint, bool) {
if c.script == nil {
return micheline.Entrypoint{}, false
}
eps, _ := c.script.Entrypoints(true)
ep, ok := eps[name]
return ep, ok
}
// on-chain views
func (c *Contract) View(name string) (micheline.View, bool) {
if c.script == nil {
return micheline.View{}, false
}
views, _ := c.script.Views(false, false)
view, ok := views[name]
return view, ok
}
// func (c *Contract) GetStorageValue(path string) (*micheline.Value, error) {}
func (c *Contract) GetBigmapValue(ctx context.Context, path string, args micheline.Prim) (*micheline.Value, error) {
store := c.StorageValue()
bigmap, ok := store.GetInt64(path)
if !ok {
return nil, fmt.Errorf("bigmap %q not found in storage", path)
}
typ, ok := c.script.Code.Storage.FindLabel(path)
if !ok {
return nil, fmt.Errorf("bigmap %q not found in type", path)
}
key, err := micheline.NewKey(micheline.NewType(typ.Args[0]), args)
if err != nil {
return nil, err
}
prim, err := c.rpc.GetActiveBigmapValue(ctx, bigmap, key.Hash())
if err != nil {
return nil, err
}
// fmt.Printf("Bigmap value %s typ %s\n", prim.Dump(), typ.Args[1].Dump())
val := micheline.NewValue(micheline.NewType(typ.Args[1]), prim)
return &val, nil
}
// Executes TZIP-4 fake views from callback entrypoints
func (c *Contract) RunView(ctx context.Context, name string, args micheline.Prim) (micheline.Prim, error) {
req := rpc.RunViewRequest{
Contract: c.addr,
Entrypoint: name,
Input: args,
ChainId: c.rpc.ChainId,
Source: tezos.ZeroAddress,
Payer: tezos.ZeroAddress,
Gas: tezos.N(1_000_000), // guess
Mode: "Readable",
}
var res rpc.RunViewResponse
err := c.rpc.RunView(ctx, rpc.Head, &req, &res)
return res.Data, err
}
func (c *Contract) RunViewExt(ctx context.Context, name string, args micheline.Prim, source, payer tezos.Address, gas int64) (micheline.Prim, error) {
req := rpc.RunViewRequest{
Contract: c.addr,
Entrypoint: name,
Input: args,
ChainId: c.rpc.ChainId,
Source: source,
Payer: payer,
Gas: tezos.N(gas),
Mode: "Readable",
}
var res rpc.RunViewResponse
err := c.rpc.RunView(ctx, rpc.Head, &req, &res)
return res.Data, err
}
func (c *Contract) Call(ctx context.Context, args CallArguments, opts *rpc.CallOptions) (*rpc.Receipt, error) {
return c.CallMulti(ctx, []CallArguments{args}, opts)
}
func (c *Contract) CallMulti(ctx context.Context, args []CallArguments, opts *rpc.CallOptions) (*rpc.Receipt, error) {
if opts == nil {
opts = &rpc.DefaultOptions
}
// assemble batch transaction
op := codec.NewOp().WithTTL(opts.TTL)
for _, arg := range args {
if arg == nil {
continue
}
arg.WithDestination(c.addr)
op.WithContents(arg.Encode())
}
// prepare, sign and broadcast
return c.rpc.Send(ctx, op, opts)
}
func (c *Contract) Deploy(ctx context.Context, opts *rpc.CallOptions) (*rpc.Receipt, error) {
return c.DeployExt(ctx, tezos.Address{}, 0, opts)
}
func (c *Contract) DeployExt(ctx context.Context, delegate tezos.Address, balance tezos.N, opts *rpc.CallOptions) (*rpc.Receipt, error) {
if opts == nil {
opts = &rpc.DefaultOptions
}
// assemble origination op
orig := &codec.Origination{
Script: *c.script,
}
if delegate.IsValid() {
orig.Delegate = delegate
}
if !balance.IsZero() {
orig.Balance = balance
}
op := codec.NewOp().WithTTL(opts.TTL).WithContents(orig)
// prepare, sign and broadcast
rcpt, err := c.rpc.Send(ctx, op, opts)
if err != nil {
return nil, err
}
// set contract address from deployment result if successful
if !rcpt.IsSuccess() {
return nil, rcpt.Error()
}
c.addr = rcpt.Op.Contents[0].Result().OriginatedContracts[0]
return rcpt, nil
}