-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFA2.py
607 lines (570 loc) · 24.6 KB
/
FA2.py
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
##
## ## Introduction
##
## See the FA2 standard definition:
## <https://gitlab.com/tzip/tzip/-/blob/master/proposals/tzip-12/>
##
## See more examples/documentation at
## <https://gitlab.com/smondet/fa2-smartpy/> and
## <https://assets.tqtezos.com/docs/token-contracts/fa2/1-fa2-smartpy/>.
##
import smartpy as sp
##
## ## Meta-Programming Configuration
##
## The `FA2_config` class holds the meta-programming configuration.
##
class FA2_config:
def __init__(self,
debug_mode = False,
single_asset = False,
non_fungible = False,
add_mutez_transfer = False,
readable = True,
force_layouts = True,
support_operator = True,
assume_consecutive_token_ids = True,
add_permissions_descriptor = False,
lazy_entry_points = False,
lazy_entry_points_multiple = False
):
if debug_mode:
self.my_map = sp.map
else:
self.my_map = sp.big_map
# The option `debug_mode` makes the code generation use
# regular maps instead of big-maps, hence it makes inspection
# of the state of the contract easier.
self.single_asset = single_asset
# This makes the contract save some gas and storage by
# working only for the token-id `0`.
self.non_fungible = non_fungible
# Enforce the non-fungibility of the tokens, i.e. the fact
# that total supply has to be 1.
self.readable = readable
# The `readable` option is a legacy setting that we keep around
# only for benchmarking purposes.
#
# User-accounts are kept in a big-map:
# `(user-address * token-id) -> ownership-info`.
#
# For the Babylon protocol, one had to use `readable = False`
# in order to use `PACK` on the keys of the big-map.
self.force_layouts = force_layouts
# The specification requires all interface-fronting records
# and variants to be *right-combs;* we keep
# this parameter to be able to compare performance & code-size.
self.support_operator = support_operator
# The operator entry-points always have to be there, but there is
# definitely a use-case for having them completely empty (saving
# storage and gas when `support_operator` is `False).
self.assume_consecutive_token_ids = assume_consecutive_token_ids
# For a previous version of the TZIP specification, it was
# necessary to keep track of the set of all tokens in the contract.
#
# The set of tokens is for now still available; this parameter
# guides how to implement it:
# If `true` we don't need a real set of token ids, just to know how
# many there are.
self.add_mutez_transfer = add_mutez_transfer
# Add an entry point for the administrator to transfer tez potentially
# in the contract's balance.
self.add_permissions_descriptor = add_permissions_descriptor
# Add the `permissions_descriptor` entry-point; it is an
# optional part of the specification and
# costs gas and storage so we keep the option of not adding it.
#
# Note that if `support_operator` is `False`, the
# permissions-descriptor becomes technically required.
self.lazy_entry_points = lazy_entry_points
self.lazy_entry_points_multiple = lazy_entry_points_multiple
#
# Those are “compilation” options of SmartPy into Michelson.
#
if lazy_entry_points and lazy_entry_points_multiple:
raise Exception(
"Cannot provide lazy_entry_points and lazy_entry_points_multiple")
name = "FA2"
if debug_mode:
name += "-debug"
if single_asset:
name += "-single_asset"
if non_fungible:
name += "-nft"
if add_mutez_transfer:
name += "-mutez"
if not readable:
name += "-no_readable"
if not force_layouts:
name += "-no_layout"
if not support_operator:
name += "-no_ops"
if not assume_consecutive_token_ids:
name += "-no_toknat"
if add_permissions_descriptor:
name += "-perm_desc"
if lazy_entry_points:
name += "-lep"
if lazy_entry_points_multiple:
name += "-lepm"
self.name = name
## ## Auxiliary Classes and Values
##
## The definitions below implement SmartML-types and functions for various
## important types.
##
token_id_type = sp.TNat
class Error_message:
def __init__(self, config):
self.config = config
self.prefix = "FA2_"
def make(self, s): return (self.prefix + s)
def token_undefined(self): return self.make("TOKEN_UNDEFINED")
def insufficient_balance(self): return self.make("INSUFFICIENT_BALANCE")
def not_operator(self): return self.make("NOT_OPERATOR")
def not_owner(self): return self.make("NOT_OWNER")
def operators_unsupported(self): return self.make("OPERATORS_UNSUPPORTED")
## The current type for a batched transfer in the specification is as
## follows:
##
## ```ocaml
## type transfer = {
## from_ : address;
## txs: {
## to_ : address;
## token_id : token_id;
## amount : nat;
## } list
## } list
## ```
##
## This class provides helpers to create and force the type of such elements.
## It uses the `FA2_config` to decide whether to set the right-comb layouts.
class Batch_transfer:
def __init__(self, config):
self.config = config
def get_transfer_type(self):
tx_type = sp.TRecord(to_ = sp.TAddress,
token_id = token_id_type,
amount = sp.TNat)
if self.config.force_layouts:
tx_type = tx_type.layout(
("to_", ("token_id", "amount"))
)
transfer_type = sp.TRecord(from_ = sp.TAddress,
txs = sp.TList(tx_type)).layout(
("from_", "txs"))
return transfer_type
def get_type(self):
return sp.TList(self.get_transfer_type())
def item(self, from_, txs):
v = sp.record(from_ = from_, txs = txs)
return sp.set_type_expr(v, self.get_transfer_type())
##
## `Operator_param` defines type types for the `%update_operators` entry-point.
class Operator_param:
def __init__(self, config):
self.config = config
def get_type(self):
t = sp.TRecord(
owner = sp.TAddress,
operator = sp.TAddress,
token_id = token_id_type)
if self.config.force_layouts:
t = t.layout(("owner", ("operator", "token_id")))
return t
def make(self, owner, operator, token_id):
r = sp.record(owner = owner,
operator = operator,
token_id = token_id)
return sp.set_type_expr(r, self.get_type())
## The class `Ledger_key` defines the key type for the main ledger (big-)map:
##
## - In *“Babylon mode”* we also have to call `sp.pack`.
## - In *“single-asset mode”* we can just use the user's address.
class Ledger_key:
def __init__(self, config):
self.config = config
def make(self, user, token):
user = sp.set_type_expr(user, sp.TAddress)
token = sp.set_type_expr(token, token_id_type)
if self.config.single_asset:
result = user
else:
result = sp.pair(user, token)
if self.config.readable:
return result
else:
return sp.pack(result)
## For now a value in the ledger is just the user's balance. Previous
## versions of the specification required more information; potential
## extensions may require other fields.
class Ledger_value:
def get_type():
return sp.TRecord(balance = sp.TNat)
def make(balance):
return sp.record(balance = balance)
## The link between operators and the addresses they operate is kept
## in a *lazy set* of `(owner × operator × token-id)` values.
##
## A lazy set is a big-map whose keys are the elements of the set and
## values are all `Unit`.
class Operator_set:
def __init__(self, config):
self.config = config
def inner_type(self):
return sp.TRecord(owner = sp.TAddress,
operator = sp.TAddress,
token_id = token_id_type
).layout(("owner", ("operator", "token_id")))
def key_type(self):
if self.config.readable:
return self.inner_type()
else:
return sp.TBytes
def make(self):
return self.config.my_map(tkey = self.key_type(), tvalue = sp.TUnit)
def make_key(self, owner, operator, token_id):
metakey = sp.record(owner = owner,
operator = operator,
token_id = token_id)
metakey = sp.set_type_expr(metakey, self.inner_type())
if self.config.readable:
return metakey
else:
return sp.pack(metakey)
def add(self, set, owner, operator, token_id):
set[self.make_key(owner, operator, token_id)] = sp.unit
def remove(self, set, owner, operator, token_id):
del set[self.make_key(owner, operator, token_id)]
def is_member(self, set, owner, operator, token_id):
return set.contains(self.make_key(owner, operator, token_id))
class Balance_of:
def request_type():
return sp.TRecord(
owner = sp.TAddress,
token_id = token_id_type).layout(("owner", "token_id"))
def response_type():
return sp.TList(
sp.TRecord(
request = Balance_of.request_type(),
balance = sp.TNat).layout(("request", "balance")))
def entry_point_type():
return sp.TRecord(
callback = sp.TContract(Balance_of.response_type()),
requests = sp.TList(Balance_of.request_type())
).layout(("requests", "callback"))
class Token_meta_data:
def __init__(self, config):
self.config = config
def get_type(self):
t = sp.TRecord(
token_id = token_id_type,
token_metadata_map = sp.TMap(sp.TString, sp.TBytes)
)
if self.config.force_layouts:
t = t.layout(("token_id",
("token_metadata_map")))
return t
def set_type_and_layout(self, expr):
sp.set_type(expr, self.get_type())
def request_type(self):
return token_id_type
class Permissions_descriptor:
def __init__(self, config):
self.config = config
def get_type(self):
operator_transfer_policy = sp.TVariant(
no_transfer = sp.TUnit,
owner_transfer = sp.TUnit,
owner_or_operator_transfer = sp.TUnit)
if self.config.force_layouts:
operator_transfer_policy = operator_transfer_policy.layout(
("no_transfer",
("owner_transfer",
"owner_or_operator_transfer")))
owner_transfer_policy = sp.TVariant(
owner_no_hook = sp.TUnit,
optional_owner_hook = sp.TUnit,
required_owner_hook = sp.TUnit)
if self.config.force_layouts:
owner_transfer_policy = owner_transfer_policy.layout(
("owner_no_hook",
("optional_owner_hook",
"required_owner_hook")))
custom_permission_policy = sp.TRecord(
tag = sp.TString,
config_api = sp.TOption(sp.TAddress))
main = sp.TRecord(
operator = operator_transfer_policy,
receiver = owner_transfer_policy,
sender = owner_transfer_policy,
custom = sp.TOption(custom_permission_policy))
if self.config.force_layouts:
main = main.layout(("operator",
("receiver",
("sender", "custom"))))
return main
def set_type_and_layout(self, expr):
sp.set_type(expr, self.get_type())
def make(self):
def uv(s):
return sp.variant(s, sp.unit)
operator = ("owner_or_operator_transfer"
if self.config.support_operator
else "owner_transfer")
v = sp.record(
operator = uv(operator),
receiver = uv("owner_no_hook"),
sender = uv("owner_no_hook"),
custom = sp.none
)
v = sp.set_type_expr(v, self.get_type())
return v
## The set of all tokens is represented by a `nat` if we assume that token-ids
## are consecutive, or by an actual `(set nat)` if not.
##
## - Knowing the set of tokens is useful for throwing accurate error messages.
## - Previous versions of the specification required this set for functional
## behavior (operators worked per-token).
class Token_id_set:
def __init__(self, config):
self.config = config
def empty(self):
if self.config.assume_consecutive_token_ids:
# The "set" is its cardinal.
return sp.nat(0)
else:
return sp.set(t = token_id_type)
def add(self, metaset, v):
if self.config.assume_consecutive_token_ids:
metaset.set(sp.max(metaset, v + 1))
else:
metaset.add(v)
def contains(self, metaset, v):
if self.config.assume_consecutive_token_ids:
return (v < metaset)
else:
metaset.contains(v)
##
## ## Implementation of the Contract
##
## `mutez_transfer` is an optional entry-point, hence we define it “outside” the
## class:
def mutez_transfer(contract, params):
sp.verify(sp.sender == contract.data.administrator)
sp.set_type(params.destination, sp.TAddress)
sp.set_type(params.amount, sp.TMutez)
sp.send(params.destination, params.amount)
##
## The `FA2` class builds a contract according to an `FA2_config` and an
## administrator address.
## It is inheriting from `FA2_core` which implements the strict
## standard and a few other classes to add other common features.
##
## - We see the use of
## [`sp.entry_point`](https://www.smartpy.io/reference.html#_entry_points)
## as a function instead of using annotations in order to allow
## optional entry points.
## - The storage field `metadata_string` is a placeholder, the build
## system replaces the field annotation with a specific version-string, such
## as `"version_20200602_tzip_b916f32"`: the version of FA2-smartpy and
## the git commit in the TZIP [repository](https://gitlab.com/tzip/tzip) that
## the contract should obey.
class FA2_core(sp.Contract):
def __init__(self, config, **extra_storage):
self.config = config
self.error_message = Error_message(self.config)
self.operator_set = Operator_set(self.config)
self.operator_param = Operator_param(self.config)
self.token_id_set = Token_id_set(self.config)
self.ledger_key = Ledger_key(self.config)
self.token_meta_data = Token_meta_data(self.config)
self.permissions_descriptor_ = Permissions_descriptor(self.config)
self.batch_transfer = Batch_transfer(self.config)
if self.config.add_mutez_transfer:
self.transfer_mutez = sp.entry_point(mutez_transfer)
if self.config.add_permissions_descriptor:
def permissions_descriptor(self, params):
sp.set_type(params, sp.TContract(self.permissions_descriptor_.get_type()))
v = self.permissions_descriptor_.make()
sp.transfer(v, sp.mutez(0), params)
self.permissions_descriptor = sp.entry_point(permissions_descriptor)
if config.lazy_entry_points:
self.add_flag("lazy_entry_points")
if config.lazy_entry_points_multiple:
self.add_flag("lazy_entry_points_multiple")
self.exception_optimization_level = "DefaultLine"
self.init(
ledger =
self.config.my_map(tvalue = Ledger_value.get_type()),
token_metadata =
self.config.my_map(tvalue = self.token_meta_data.get_type()),
operators = self.operator_set.make(),
all_tokens = self.token_id_set.empty(),
**extra_storage
)
@sp.entry_point
def transfer(self, params):
sp.verify( ~self.is_paused() )
sp.set_type(params, self.batch_transfer.get_type())
sp.for transfer in params:
current_from = transfer.from_
sp.for tx in transfer.txs:
#sp.verify(tx.amount > 0, message = "TRANSFER_OF_ZERO")
if self.config.single_asset:
sp.verify(tx.token_id == 0, "single-asset: token-id <> 0")
if self.config.support_operator:
sp.verify(
(self.is_administrator(sp.sender)) |
(current_from == sp.sender) |
self.operator_set.is_member(self.data.operators,
current_from,
sp.sender,
tx.token_id),
message = self.error_message.not_operator())
else:
sp.verify(
(self.is_administrator(sp.sender)) |
(current_from == sp.sender),
message = self.error_message.not_owner())
sp.verify(self.data.token_metadata.contains(tx.token_id),
message = self.error_message.token_undefined())
# If amount is 0 we do nothing now:
sp.if (tx.amount > 0):
from_user = self.ledger_key.make(current_from, tx.token_id)
sp.verify(
(self.data.ledger[from_user].balance >= tx.amount),
message = self.error_message.insufficient_balance())
to_user = self.ledger_key.make(tx.to_, tx.token_id)
self.data.ledger[from_user].balance = sp.as_nat(
self.data.ledger[from_user].balance - tx.amount)
sp.if self.data.ledger.contains(to_user):
self.data.ledger[to_user].balance += tx.amount
sp.else:
self.data.ledger[to_user] = Ledger_value.make(tx.amount)
sp.else:
pass
@sp.entry_point
def balance_of(self, params):
# paused may mean that balances are meaningless:
sp.verify( ~self.is_paused() )
sp.set_type(params, Balance_of.entry_point_type())
def f_process_request(req):
user = self.ledger_key.make(req.owner, req.token_id)
sp.verify(self.data.token_metadata.contains(req.token_id),
message = self.error_message.token_undefined())
sp.if self.data.ledger.contains(user):
balance = self.data.ledger[user].balance
sp.result(
sp.record(
request = sp.record(
owner = sp.set_type_expr(req.owner, sp.TAddress),
token_id = sp.set_type_expr(req.token_id, sp.TNat)),
balance = balance))
sp.else:
sp.result(
sp.record(
request = sp.record(
owner = sp.set_type_expr(req.owner, sp.TAddress),
token_id = sp.set_type_expr(req.token_id, sp.TNat)),
balance = 0))
res = sp.local("responses", params.requests.map(f_process_request))
destination = sp.set_type_expr(params.callback,
sp.TContract(Balance_of.response_type()))
sp.transfer(res.value, sp.mutez(0), destination)
@sp.entry_point
def update_operators(self, params):
sp.set_type(params, sp.TList(
sp.TVariant(
add_operator = self.operator_param.get_type(),
remove_operator = self.operator_param.get_type())))
if self.config.support_operator:
sp.for update in params:
with update.match_cases() as arg:
with arg.match("add_operator") as upd:
sp.verify((upd.owner == sp.sender) |
(self.is_administrator(sp.sender)))
self.operator_set.add(self.data.operators,
upd.owner,
upd.operator,
upd.token_id)
with arg.match("remove_operator") as upd:
sp.verify((upd.owner == sp.sender) |
(self.is_administrator(sp.sender)))
self.operator_set.remove(self.data.operators,
upd.owner,
upd.operator,
upd.token_id)
else:
sp.failwith(self.error_message.operators_unsupported())
# this is not part of the standard but can be supported through inheritance.
def is_paused(self):
return sp.bool(False)
# this is not part of the standard but can be supported through inheritance.
def is_administrator(self, sender):
return sp.bool(False)
class FA2_administrator(FA2_core):
def is_administrator(self, sender):
return sender == self.data.administrator
@sp.entry_point
def set_administrator(self, params):
sp.verify(self.is_administrator(sp.sender))
self.data.administrator = params
class FA2_pause(FA2_core):
def is_paused(self):
return self.data.paused
@sp.entry_point
def set_pause(self, params):
sp.verify(self.is_administrator(sp.sender))
self.data.paused = params
class FA2_mint(FA2_core):
@sp.entry_point
def mint(self, params):
sp.verify(self.is_administrator(sp.sender))
# We don't check for pauseness because we're the admin.
if self.config.single_asset:
sp.verify(params.token_id == 0, "single-asset: token-id <> 0")
if self.config.non_fungible:
sp.verify(params.amount == 1, "NFT-asset: amount <> 1")
sp.verify(~ self.token_id_set.contains(self.data.all_tokens,
params.token_id),
"NFT-asset: cannot mint twice same token")
user = self.ledger_key.make(params.address, params.token_id)
self.token_id_set.add(self.data.all_tokens, params.token_id)
sp.if self.data.ledger.contains(user):
self.data.ledger[user].balance += params.amount
sp.else:
self.data.ledger[user] = Ledger_value.make(params.amount)
sp.if self.data.token_metadata.contains(params.token_id):
pass
sp.else:
self.data.token_metadata[params.token_id] = sp.record(
token_id=params.token_id,
token_info=params.token_info
)
""" sp.record(
token_id = params.token_id,
symbol = params.symbol,
cid = "",
name = "", # Consered useless here
decimals = 0
) """
class FA2_token_metadata(FA2_core):
@sp.entry_point
def token_metadata(self, params):
sp.verify( ~self.is_paused() )
sp.set_type(params,
sp.TRecord(
token_ids = sp.TList(sp.TNat),
handler = sp.TLambda(
sp.TList(self.token_meta_data.get_type()),
sp.TUnit)
).layout(("token_ids", "handler")))
def f_on_request(req):
self.token_meta_data.set_type_and_layout(self.data.token_metadata[req])
sp.result(self.data.token_metadata[req])
sp.compute(params.handler(params.token_ids.map(f_on_request)))
class FA2(FA2_token_metadata, FA2_mint, FA2_administrator, FA2_pause, FA2_core):
def __init__(self, config, admin, meta):
FA2_core.__init__(self, config, paused = False, administrator = admin, metadata = meta)