-
Notifications
You must be signed in to change notification settings - Fork 165
/
objects.py
499 lines (436 loc) · 16.9 KB
/
objects.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
# -*- coding: utf-8 -*-
import json
from collections import OrderedDict
from graphenebase.objects import GrapheneObject
from graphenebase.objects import Operation as GrapheneOperation
from graphenebase.objects import isArgsThisClass, Asset
from graphenebase.types import Array, Bool, Bytes, Fixed_array, Id, Int16, Int64, Map
from graphenebase.types import ObjectId as GPHObjectId
from graphenebase.types import (
Optional,
PointInTime,
Set,
Signature,
Static_variant,
String,
Uint8,
Uint16,
Uint32,
Uint64,
Varint32,
Void,
VoteId,
Ripemd160,
)
from .account import PublicKey
from .objecttypes import object_type
from .operationids import operations
default_prefix = "BTS"
BlockId = Ripemd160
class Operation(GrapheneOperation):
"""Need to overwrite a few attributes to load proper operations from bitshares."""
module = "bitsharesbase.operations"
operations = operations
class ObjectId(GPHObjectId):
"""Need to overwrite a few attributes to load proper object_types from bitshares."""
object_types = object_type
def AssetId(asset):
return ObjectId(asset, "asset")
def AccountId(asset):
return ObjectId(asset, "account")
class Memo(GrapheneObject):
def __init__(self, *args, **kwargs):
if isArgsThisClass(self, args):
self.data = args[0].data
else:
if len(args) == 1 and len(kwargs) == 0:
kwargs = args[0]
prefix = kwargs.pop("prefix", default_prefix)
if "message" in kwargs and kwargs["message"]:
super().__init__(
OrderedDict(
[
("from", PublicKey(kwargs["from"], prefix=prefix)),
("to", PublicKey(kwargs["to"], prefix=prefix)),
("nonce", Uint64(int(kwargs["nonce"]))),
("message", Bytes(kwargs["message"])),
]
)
)
else:
super().__init__(None)
class Price(GrapheneObject):
def __init__(self, *args, **kwargs):
if isArgsThisClass(self, args):
self.data = args[0].data
else:
if len(args) == 1 and len(kwargs) == 0:
kwargs = args[0]
super().__init__(
OrderedDict(
[("base", Asset(kwargs["base"])), ("quote", Asset(kwargs["quote"]))]
)
)
class PriceFeed(GrapheneObject):
def __init__(self, *args, **kwargs):
if isArgsThisClass(self, args):
self.data = args[0].data
else:
if len(args) == 1 and len(kwargs) == 0:
kwargs = args[0]
super().__init__(
OrderedDict(
[
("settlement_price", Price(kwargs["settlement_price"])),
(
"maintenance_collateral_ratio",
Uint16(kwargs["maintenance_collateral_ratio"]),
),
(
"maximum_short_squeeze_ratio",
Uint16(kwargs["maximum_short_squeeze_ratio"]),
),
("core_exchange_rate", Price(kwargs["core_exchange_rate"])),
]
)
)
class Permission(GrapheneObject):
def __init__(self, *args, **kwargs):
if isArgsThisClass(self, args):
self.data = args[0].data
else:
prefix = kwargs.pop("prefix", default_prefix)
if len(args) == 1 and len(kwargs) == 0:
kwargs = args[0]
kwargs["key_auths"] = sorted(
kwargs["key_auths"],
key=lambda x: PublicKey(x[0], prefix=prefix),
reverse=False,
)
accountAuths = Map(
[
[ObjectId(e[0], "account"), Uint16(e[1])]
for e in kwargs["account_auths"]
]
)
keyAuths = Map(
[
[PublicKey(e[0], prefix=prefix), Uint16(e[1])]
for e in kwargs["key_auths"]
]
)
super().__init__(
OrderedDict(
[
("weight_threshold", Uint32(int(kwargs["weight_threshold"]))),
("account_auths", accountAuths),
("key_auths", keyAuths),
("extensions", Set([])),
]
)
)
class AccountOptions(GrapheneObject):
def __init__(self, *args, **kwargs):
# Allow for overwrite of prefix
prefix = kwargs.pop("prefix", default_prefix)
if isArgsThisClass(self, args):
self.data = args[0].data
else:
if len(args) == 1 and len(kwargs) == 0:
kwargs = args[0]
# remove dublicates
kwargs["votes"] = list(set(kwargs["votes"]))
# Sort votes
kwargs["votes"] = sorted(
kwargs["votes"], key=lambda x: float(x.split(":")[1])
)
super().__init__(
OrderedDict(
[
("memo_key", PublicKey(kwargs["memo_key"], prefix=prefix)),
(
"voting_account",
ObjectId(kwargs["voting_account"], "account"),
),
("num_witness", Uint16(kwargs["num_witness"])),
("num_committee", Uint16(kwargs["num_committee"])),
("votes", Array([VoteId(o) for o in kwargs["votes"]])),
("extensions", Set([])),
]
)
)
class AssetOptions(GrapheneObject):
def __init__(self, *args, **kwargs):
if isArgsThisClass(self, args):
self.data = args[0].data
else:
if len(args) == 1 and len(kwargs) == 0:
kwargs = args[0]
super().__init__(
OrderedDict(
[
("max_supply", Int64(kwargs["max_supply"])),
("market_fee_percent", Uint16(kwargs["market_fee_percent"])),
("max_market_fee", Int64(kwargs["max_market_fee"])),
("issuer_permissions", Uint16(kwargs["issuer_permissions"])),
("flags", Uint16(kwargs["flags"])),
("core_exchange_rate", Price(kwargs["core_exchange_rate"])),
(
"whitelist_authorities",
Array(
[
ObjectId(x, "account")
for x in kwargs["whitelist_authorities"]
]
),
),
(
"blacklist_authorities",
Array(
[
ObjectId(x, "account")
for x in kwargs["blacklist_authorities"]
]
),
),
(
"whitelist_markets",
Array(
[
ObjectId(x, "asset")
for x in kwargs["whitelist_markets"]
]
),
),
(
"blacklist_markets",
Array(
[
ObjectId(x, "asset")
for x in kwargs["blacklist_markets"]
]
),
),
("description", String(kwargs["description"])),
("extensions", Set([])),
]
)
)
class BitAssetOptions(GrapheneObject):
def __init__(self, *args, **kwargs):
if isArgsThisClass(self, args):
self.data = args[0].data
else:
if len(args) == 1 and len(kwargs) == 0:
kwargs = args[0]
super().__init__(
OrderedDict(
[
("feed_lifetime_sec", Uint32(kwargs["feed_lifetime_sec"])),
("minimum_feeds", Uint8(kwargs["minimum_feeds"])),
(
"force_settlement_delay_sec",
Uint32(kwargs["force_settlement_delay_sec"]),
),
(
"force_settlement_offset_percent",
Uint16(kwargs["force_settlement_offset_percent"]),
),
(
"maximum_force_settlement_volume",
Uint16(kwargs["maximum_force_settlement_volume"]),
),
(
"short_backing_asset",
ObjectId(kwargs["short_backing_asset"], "asset"),
),
("extensions", Set([])),
]
)
)
class Worker_initializer(Static_variant):
def __init__(self, o):
class Burn_worker_initializer(GrapheneObject):
def __init__(self, kwargs):
super().__init__(OrderedDict([]))
class Refund_worker_initializer(GrapheneObject):
def __init__(self, kwargs):
super().__init__(OrderedDict([]))
class Vesting_balance_worker_initializer(GrapheneObject):
def __init__(self, *args, **kwargs):
if isArgsThisClass(self, args):
self.data = args[0].data
else:
if len(args) == 1 and len(kwargs) == 0:
kwargs = args[0]
super().__init__(
OrderedDict(
[
(
"pay_vesting_period_days",
Uint16(kwargs["pay_vesting_period_days"]),
)
]
)
)
id = o[0]
if id == 0:
data = Refund_worker_initializer(o[1])
elif id == 1:
data = Vesting_balance_worker_initializer(o[1])
elif id == 2:
data = Burn_worker_initializer(o[1])
else:
raise ValueError("Unknown {}".format(self.__class__.name))
super().__init__(data, id)
class SpecialAuthority(Static_variant):
def __init__(self, o):
class No_special_authority(GrapheneObject):
def __init__(self, kwargs):
super().__init__(OrderedDict([]))
class Top_holders_special_authority(GrapheneObject):
def __init__(self, kwargs):
super().__init__(
OrderedDict(
[
("asset", ObjectId(kwargs["asset"], "asset")),
("num_top_holders", Uint8(kwargs["num_top_holders"])),
]
)
)
id = o[0]
if id == 0:
data = No_special_authority(o[1])
elif id == 1:
data = Top_holders_special_authority(o[1])
else:
raise Exception("Unknown SpecialAuthority")
super().__init__(data, id)
class Extension(Array):
def __init__(self, *args, **kwargs):
self.json = {}
a = []
for key, value in kwargs.items():
self.json.update({key: value})
for arg in args:
if isinstance(arg, dict):
self.json.update(arg)
for index, extension in enumerate(self.sorted_options):
name = extension[0]
klass = extension[1]
for key, value in self.json.items():
if key.lower() == name.lower():
a.append(Static_variant(klass(value), index))
super().__init__(a)
def __str__(self):
"""We overload the __str__ function because the json representation is different
for extensions."""
return json.dumps(self.json)
class AccountCreateExtensions(Extension):
class Null_ext(GrapheneObject):
def __init__(self, *args, **kwargs):
super().__init__(OrderedDict([]))
class Buyback_options(GrapheneObject):
def __init__(self, *args, **kwargs):
kwargs.update(args[0])
super().__init__(
OrderedDict(
[
("asset_to_buy", ObjectId(kwargs["asset_to_buy"], "asset")),
(
"asset_to_buy_issuer",
ObjectId(kwargs["asset_to_buy_issuer"], "account"),
),
(
"markets",
Array([ObjectId(x, "asset") for x in kwargs["markets"]]),
),
]
)
)
sorted_options = [
("null_ext", Null_ext),
("owner_special_authority", SpecialAuthority),
("active_special_authority", SpecialAuthority),
("buyback_options", Buyback_options),
]
class CallOrderExtension(Extension):
def targetCollateralRatio(value):
if value:
return Uint16(value)
else:
return None
sorted_options = [("target_collateral_ratio", targetCollateralRatio)]
class AssertPredicate(Static_variant):
def __init__(self, o):
class Account_name_eq_lit_predicate(GrapheneObject):
def __init__(self, *args, **kwargs):
kwargs.update(args[0])
super().__init__(
OrderedDict(
[
("account_id", ObjectId(kwargs["account_id"], "account")),
("name", String(kwargs["name"])),
]
)
)
class Asset_symbol_eq_lit_predicate(GrapheneObject):
def __init__(self, *args, **kwargs):
kwargs.update(args[0])
super().__init__(
OrderedDict(
[
("asset_id", ObjectId(kwargs["asset_id"], "asset")),
("symbol", String(kwargs["symbol"])),
]
)
)
class Block_id_predicate(GrapheneObject):
def __init__(self, *args, **kwargs):
kwargs.update(args[0])
super().__init__(OrderedDict([("id", BlockId(kwargs["id"]))]))
id = o[0]
if id == 0:
data = Account_name_eq_lit_predicate(o[1])
elif id == 1:
data = Asset_symbol_eq_lit_predicate(o[1])
elif id == 2:
data = Block_id_predicate(o[1])
else:
raise ValueError("Unknown {}".format(self.__class__.__name__))
super().__init__(data, id)
class LimitOrderAutoAction(Static_variant):
def __init__(self, o):
class Create_take_profit_order_action(GrapheneObject):
def __init__(self, *args, **kwargs):
kwargs.update(args[0])
super().__init__(
OrderedDict(
[
("fee_asset_id", ObjectId(kwargs["fee_asset_id"], "asset")),
("spread_percent", Uint16(kwargs["spread_percent"])),
("size_percent", Uint16(kwargs["size_percent"])),
(
"expiration_seconds",
Uint32(kwargs["expiration_seconds"]),
),
("repeat", Bool(kwargs["repeat"])),
("extensions", Set([])),
]
)
)
id = o[0]
if id == 0:
data = Create_take_profit_order_action(o[1])
else:
raise ValueError("Unknown {}".format(self.__class__.__name__))
super().__init__(data, id)
class LimitOrderCreateExtensions(Extension):
def NestedLimitOrderAutoAction(value):
if value:
return Array([LimitOrderAutoAction(o) for o in value])
else:
return None
sorted_options = [
("on_fill", NestedLimitOrderAutoAction),
]