-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathcommit.py
More file actions
1433 lines (1223 loc) · 53.1 KB
/
commit.py
File metadata and controls
1433 lines (1223 loc) · 53.1 KB
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import logging
import random
import re
import voluptuous as vo
from datetime import datetime, timedelta
from funcy.colls import none
from funcy.flow import silent
from funcy.seqs import first
from steembase import memo
from steembase import operations
from steembase.account import PrivateKey, PublicKey
from steembase.exceptions import AccountExistsException, MissingKeyError
from steembase.storage import configStorage
from .account import Account
from .amount import Amount
from .converter import Converter
from .instance import shared_steemd_instance
from .transactionbuilder import TransactionBuilder
from .utils import (
derive_permlink,
fmt_time_string,
keep_in_dict,
resolve_identifier,
)
from .wallet import Wallet
log = logging.getLogger(__name__)
STEEMIT_100_PERCENT = 10000
STEEMIT_1_PERCENT = (STEEMIT_100_PERCENT / 100)
# TODO
# account_witness_proxy [active]
# account_update [owner, active]
# decline_voting_rights [owner]
# challenge_authority [posting]
# prove_authority [active, owner]
# request_account_recovery [active]
# change_recovery_account [owner]
# reset_account [active]
# set_reset_account [active, owner]
# escrow_transfer [active]
# escrow_dispute [active]
# escrow_release [active]
# escrow_approve [active]
# custom_binary [any]
# custom [active]
# delete_comment [posting]
# enable_content_editing_operation [active]
class Commit(object):
""" Commit things to the Steem network.
This class contains helper methods to construct, sign and broadcast
common transactions, such as posting, voting, sending funds, etc.
:param Steemd steemd: Steemd node to connect to*
:param bool offline: Do **not** broadcast transactions! *(optional)*
:param bool debug: Enable Debugging *(optional)*
:param list,dict,string keys: Predefine the wif keys to shortcut the
wallet database
Three wallet operation modes are possible:
* **Wallet Database**: Here, the steemlibs load the keys from the
locally stored wallet SQLite database (see ``storage.py``).
To use this mode, simply call ``Steem()`` without the
``keys`` parameter
* **Providing Keys**: Here, you can provide the keys for
your accounts manually. All you need to do is add the wif
keys for the accounts you want to use as a simple array
using the ``keys`` parameter to ``Steem()``.
* **Force keys**: This more is for advanced users and
requires that you know what you are doing. Here, the
``keys`` parameter is a dictionary that overwrite the
``active``, ``owner``, ``posting`` or ``memo`` keys for
any account. This mode is only used for *foreign*
signatures!
"""
def __init__(self, steemd_instance=None, no_broadcast=False, **kwargs):
self.steemd = steemd_instance or shared_steemd_instance()
self.no_broadcast = no_broadcast
self.unsigned = kwargs.get("unsigned", False)
self.expiration = int(kwargs.get("expiration", 60))
self.wallet = Wallet(self.steemd, **kwargs)
def finalizeOp(self, ops, account, permission):
""" This method obtains the required private keys if present in
the wallet, finalizes the transaction, signs it and
broadacasts it
:param operation ops: The operation (or list of operaions) to
broadcast
:param operation account: The account that authorizes the
operation
:param string permission: The required permission for
signing (active, owner, posting)
... note::
If ``ops`` is a list of operation, they all need to be
signable by the same key! Thus, you cannot combine ops
that require active permission with ops that require
posting permission. Neither can you use different
accounts for different operations!
"""
tx = TransactionBuilder(
None,
steemd_instance=self.steemd,
wallet_instance=self.wallet,
no_broadcast=self.no_broadcast,
expiration=self.expiration)
tx.appendOps(ops)
if self.unsigned:
tx.addSigningInformation(account, permission)
return tx
else:
tx.appendSigner(account, permission)
tx.sign()
return tx.broadcast()
def sign(self, unsigned_trx, wifs=[]):
""" Sign a provided transaction witht he provided key(s)
:param dict unsigned_trx: The transaction to be signed and returned
:param string wifs: One or many wif keys to use for signing
a transaction. If not present, the keys will be loaded
from the wallet as defined in "missing_signatures" key
of the transactizions.
"""
tx = TransactionBuilder(
unsigned_trx,
steemd_instance=self.steemd,
wallet_instance=self.wallet,
no_broadcast=self.no_broadcast,
expiration=self.expiration)
tx.appendMissingSignatures(wifs)
tx.sign()
return tx.json()
def broadcast(self, signed_trx):
""" Broadcast a transaction to the Steem network
:param tx signed_trx: Signed transaction to broadcast
"""
tx = TransactionBuilder(
signed_trx,
steemd_instance=self.steemd,
wallet_instance=self.wallet,
no_broadcast=self.no_broadcast,
expiration=self.expiration)
return tx.broadcast()
def post(self,
title,
body,
author,
permlink=None,
reply_identifier=None,
json_metadata=None,
comment_options=None,
community=None,
tags=None,
beneficiaries=None,
self_vote=False):
""" Create a new post.
If this post is intended as a reply/comment, `reply_identifier` needs
to be set with the identifier of the parent post/comment (eg.
`@author/permlink`).
Optionally you can also set json_metadata, comment_options and upvote
the newly created post as an author.
Setting category, tags or community will override the values provided
in json_metadata and/or comment_options where appropriate.
Args:
title (str): Title of the post
body (str): Body of the post/comment
author (str): Account are you posting from
permlink (str): Manually set the permlink (defaults to None).
If left empty, it will be derived from title automatically.
reply_identifier (str): Identifier of the parent post/comment (only
if this post is a reply/comment).
json_metadata (str, dict): JSON meta object that can be attached to
the post.
comment_options (str, dict): JSON options object that can be
attached to the post.
Example::
comment_options = {
'max_accepted_payout': '1000000.000 SBD',
'percent_steem_dollars': 10000,
'allow_votes': True,
'allow_curation_rewards': True,
'extensions': [[0, {
'beneficiaries': [
{'account': 'account1', 'weight': 5000},
{'account': 'account2', 'weight': 5000},
]}
]]
}
community (str): (Optional) Name of the community we are posting
into. This will also override the community specified in
`json_metadata`.
tags (str, list): (Optional) A list of tags (5 max) to go with the
post. This will also override the tags specified in
`json_metadata`. The first tag will be used as a 'category'. If
provided as a string, it should be space separated.
beneficiaries (list of dicts): (Optional) A list of beneficiaries
for posting reward distribution. This argument overrides
beneficiaries as specified in `comment_options`.
For example, if we would like to split rewards between account1 and
account2::
beneficiaries = [
{'account': 'account1', 'weight': 5000},
{'account': 'account2', 'weight': 5000}
]
self_vote (bool): (Optional) Upvote the post as author, right after
posting.
"""
# prepare json_metadata
json_metadata = json_metadata or {}
if isinstance(json_metadata, str):
json_metadata = silent(json.loads)(json_metadata) or {}
# override the community
if community:
json_metadata.update({'community': community})
# deal with the category and tags
if isinstance(tags, str):
tags = list(set(filter(None, (re.split("[\W_]", tags)))))
category = None
tags = tags or json_metadata.get('tags', [])
if tags:
if len(tags) > 5:
raise ValueError('Can only specify up to 5 tags per post.')
# first tag should be a category
category = tags[0]
json_metadata.update({"tags": tags})
# can't provide a category while replying to a post
if reply_identifier and category:
category = None
# deal with replies/categories
if reply_identifier:
parent_author, parent_permlink = resolve_identifier(
reply_identifier)
if not permlink:
permlink = derive_permlink(title, parent_permlink)
elif category:
parent_permlink = derive_permlink(category)
parent_author = ""
if not permlink:
permlink = derive_permlink(title)
else:
parent_author = ""
parent_permlink = ""
if not permlink:
permlink = derive_permlink(title)
post_op = operations.Comment(
**{
"parent_author": parent_author,
"parent_permlink": parent_permlink,
"author": author,
"permlink": permlink,
"title": title,
"body": body,
"json_metadata": json_metadata
})
ops = [post_op]
# if comment_options are used, add a new op to the transaction
if comment_options or beneficiaries:
options = keep_in_dict(comment_options or {}, [
'max_accepted_payout', 'percent_steem_dollars', 'allow_votes',
'allow_curation_rewards', 'extensions'
])
# override beneficiaries extension
if beneficiaries:
# validate schema
# or just simply vo.Schema([{'account': str, 'weight': int}])
schema = vo.Schema([{
vo.Required('account'):
vo.All(str, vo.Length(max=16)),
vo.Required('weight', default=10000):
vo.All(int, vo.Range(min=1, max=10000))
}])
schema(beneficiaries)
options['beneficiaries'] = beneficiaries
default_max_payout = "1000000.000 SBD"
comment_op = operations.CommentOptions(
**{
"author":
author,
"permlink":
permlink,
"max_accepted_payout":
options.get("max_accepted_payout", default_max_payout),
"percent_steem_dollars":
int(options.get("percent_steem_dollars", 10000)),
"allow_votes":
options.get("allow_votes", True),
"allow_curation_rewards":
options.get("allow_curation_rewards", True),
"extensions":
options.get("extensions", []),
"beneficiaries":
options.get("beneficiaries"),
})
ops.append(comment_op)
if self_vote:
vote_op = operations.Vote(
**{
'voter': author,
'author': author,
'permlink': permlink,
'weight': 10000,
})
ops.append(vote_op)
return self.finalizeOp(ops, author, "posting")
def vote(self, identifier, weight, account=None):
""" Vote for a post
:param str identifier: Identifier for the post to upvote Takes
the form ``@author/permlink``
:param float weight: Voting weight. Range: -100.0 - +100.0. May
not be 0.0
:param str account: Voter to use for voting. (Optional)
If ``voter`` is not defines, the ``default_account`` will be taken
or a ValueError will be raised
.. code-block:: python
steempy set default_account <account>
"""
if not account:
account = configStorage.get("default_account")
if not account:
raise ValueError("You need to provide a voter account")
post_author, post_permlink = resolve_identifier(identifier)
op = operations.Vote(
**{
"voter": account,
"author": post_author,
"permlink": post_permlink,
"weight": int(weight * STEEMIT_1_PERCENT)
})
return self.finalizeOp(op, account, "posting")
def create_account(
self,
account_name,
json_meta=None,
password=None,
owner_key=None,
active_key=None,
posting_key=None,
memo_key=None,
additional_owner_keys=[],
additional_active_keys=[],
additional_posting_keys=[],
additional_owner_accounts=[],
additional_active_accounts=[],
additional_posting_accounts=[],
store_keys=True,
store_owner_key=False,
delegation_fee_steem='0 STEEM',
creator=None,
):
""" Create new account in Steem
The brainkey/password can be used to recover all generated keys
(see `steembase.account` for more details.
By default, this call will use ``default_account`` to
register a new name ``account_name`` with all keys being
derived from a new brain key that will be returned. The
corresponding keys will automatically be installed in the
wallet.
.. note:: Account creations cost a fee that is defined by
the network. If you create an account, you will
need to pay for that fee!
**You can partially pay that fee by delegating VESTS.**
To pay the fee in full in STEEM, leave
``delegation_fee_steem`` set to ``0 STEEM`` (Default).
To pay the fee partially in STEEM, partially with delegated
VESTS, set ``delegation_fee_steem`` to a value greater than ``1
STEEM``. `Required VESTS will be calculated automatically.`
To pay the fee with maximum amount of delegation, set
``delegation_fee_steem`` to ``1 STEEM``. `Required VESTS will be
calculated automatically.`
.. warning:: Don't call this method unless you know what
you are doing! Be sure to understand what this
method does and where to find the private keys
for your account.
.. note:: Please note that this imports private keys (if password is
present) into the wallet by default. However, it **does not import
the owner key** unless `store_owner_key` is set to True (default
False). Do NOT expect to be able to recover it from the wallet if
you lose your password!
:param str account_name: (**required**) new account name
:param str json_meta: Optional meta data for the account
:param str owner_key: Main owner key
:param str active_key: Main active key
:param str posting_key: Main posting key
:param str memo_key: Main memo_key
:param str password: Alternatively to providing keys, one
can provide a password from which the
keys will be derived
:param list additional_owner_keys: Additional owner public keys
:param list additional_active_keys: Additional active public keys
:param list additional_posting_keys: Additional posting public keys
:param list additional_owner_accounts: Additional owner account
names
:param list additional_active_accounts: Additional active account
names
:param list additional_posting_accounts: Additional posting account
names
:param bool store_keys: Store new keys in the wallet (default:
``True``)
:param bool store_owner_key: Store owner key in the wallet
(default: ``False``)
:param str delegation_fee_steem: (Optional) If set, `creator` pay a
fee of this amount, and delegate the rest with VESTS (calculated
automatically). Minimum: 1 STEEM. If left to 0 (Default), full fee
is paid without VESTS delegation.
:param str creator: which account should pay the registration fee
(defaults to ``default_account``)
:raises AccountExistsException: if the account already exists on the
blockchain
"""
assert len(
account_name) <= 16, "Account name must be at most 16 chars long"
if not creator:
creator = configStorage.get("default_account")
if not creator:
raise ValueError(
"Not creator account given. Define it with " +
"creator=x, or set the default_account using steempy")
if password and (owner_key or posting_key or active_key or memo_key):
raise ValueError("You cannot use 'password' AND provide keys!")
# check if account already exists
try:
Account(account_name, steemd_instance=self.steemd)
except: # noqa FIXME(sneak)
pass
else:
raise AccountExistsException
" Generate new keys from password"
from steembase.account import PasswordKey, PublicKey
if password:
posting_key = PasswordKey(account_name, password, role="posting")
active_key = PasswordKey(account_name, password, role="active")
owner_key = PasswordKey(account_name, password, role="owner")
memo_key = PasswordKey(account_name, password, role="memo")
posting_pubkey = posting_key.get_public_key()
active_pubkey = active_key.get_public_key()
owner_pubkey = owner_key.get_public_key()
memo_pubkey = memo_key.get_public_key()
posting_privkey = posting_key.get_private_key()
active_privkey = active_key.get_private_key()
owner_privkey = owner_key.get_private_key()
memo_privkey = memo_key.get_private_key()
# store private keys
if store_keys:
if store_owner_key:
self.wallet.addPrivateKey(owner_privkey)
self.wallet.addPrivateKey(active_privkey)
self.wallet.addPrivateKey(posting_privkey)
self.wallet.addPrivateKey(memo_privkey)
elif owner_key and posting_key and active_key and memo_key:
posting_pubkey = PublicKey(
posting_key, prefix=self.steemd.chain_params["prefix"])
active_pubkey = PublicKey(
active_key, prefix=self.steemd.chain_params["prefix"])
owner_pubkey = PublicKey(
owner_key, prefix=self.steemd.chain_params["prefix"])
memo_pubkey = PublicKey(
memo_key, prefix=self.steemd.chain_params["prefix"])
else:
raise ValueError(
"Call incomplete! Provide either a password or public keys!")
owner = format(owner_pubkey, self.steemd.chain_params["prefix"])
active = format(active_pubkey, self.steemd.chain_params["prefix"])
posting = format(posting_pubkey, self.steemd.chain_params["prefix"])
memo = format(memo_pubkey, self.steemd.chain_params["prefix"])
owner_key_authority = [[owner, 1]]
active_key_authority = [[active, 1]]
posting_key_authority = [[posting, 1]]
owner_accounts_authority = []
active_accounts_authority = []
posting_accounts_authority = []
# additional authorities
for k in additional_owner_keys:
owner_key_authority.append([k, 1])
for k in additional_active_keys:
active_key_authority.append([k, 1])
for k in additional_posting_keys:
posting_key_authority.append([k, 1])
for k in additional_owner_accounts:
owner_accounts_authority.append([k, 1])
for k in additional_active_accounts:
active_accounts_authority.append([k, 1])
for k in additional_posting_accounts:
posting_accounts_authority.append([k, 1])
props = self.steemd.get_chain_properties()
required_fee_steem = Amount(props["account_creation_fee"]).amount * 30
required_fee_vests = 0
delegation_fee_steem = Amount(delegation_fee_steem).amount
if delegation_fee_steem:
# creating accounts without delegation requires 30x
# account_creation_fee creating account with delegation allows one
# to use VESTS to pay the fee where the ratio must satisfy 1 STEEM
# in fee == 5 STEEM in delegated VESTS
delegated_sp_fee_mult = 5
if delegation_fee_steem < 1:
raise ValueError(
"When creating account with delegation, at least " +
"1 STEEM in fee must be paid.")
# calculate required remaining fee in vests
remaining_fee = required_fee_steem - delegation_fee_steem
if remaining_fee > 0:
required_sp = remaining_fee * delegated_sp_fee_mult
required_fee_vests = Converter(self.steemd).sp_to_vests(required_sp) + 1
s = {
'creator': creator,
'fee': '%s STEEM' % (delegation_fee_steem or required_fee_steem),
'delegation': '%s VESTS' % required_fee_vests,
'json_metadata': json_meta or {},
'memo_key': memo,
'new_account_name': account_name,
'owner': {
'account_auths': owner_accounts_authority,
'key_auths': owner_key_authority,
'weight_threshold': 1
},
'active': {
'account_auths': active_accounts_authority,
'key_auths': active_key_authority,
'weight_threshold': 1
},
'posting': {
'account_auths': posting_accounts_authority,
'key_auths': posting_key_authority,
'weight_threshold': 1
},
'prefix': self.steemd.chain_params["prefix"]
}
op = operations.AccountCreateWithDelegation(**s)
return self.finalizeOp(op, creator, "active")
def transfer(self, to, amount, asset, memo="", account=None):
""" Transfer SBD or STEEM to another account.
:param str to: Recipient
:param float amount: Amount to transfer
:param str asset: Asset to transfer (``SBD`` or ``STEEM``)
:param str memo: (optional) Memo, may begin with `#` for encrypted
messaging
:param str account: (optional) the source account for the transfer
if not ``default_account``
"""
if not account:
account = configStorage.get("default_account")
if not account:
raise ValueError("You need to provide an account")
assert asset in ['STEEM', 'SBD']
if memo and memo[0] == "#":
from steembase import memo as Memo
memo_wif = self.wallet.getMemoKeyForAccount(account)
if not memo_wif:
raise MissingKeyError("Memo key for %s missing!" % account)
to_account = Account(to, steemd_instance=self.steemd)
nonce = random.getrandbits(64)
memo = Memo.encode_memo(
PrivateKey(memo_wif),
PublicKey(
to_account["memo_key"],
prefix=self.steemd.chain_params["prefix"]),
nonce,
memo,
prefix=self.steemd.chain_params["prefix"])
op = operations.Transfer(
**{
"from":
account,
"to":
to,
"amount":
'{:.{prec}f} {asset}'.format(
float(amount), prec=3, asset=asset),
"memo":
memo
})
return self.finalizeOp(op, account, "active")
def withdraw_vesting(self, amount, account=None):
""" Withdraw VESTS from the vesting account.
:param float amount: number of VESTS to withdraw over a period of
104 weeks
:param str account: (optional) the source account for the transfer
if not ``default_account``
"""
if not account:
account = configStorage.get("default_account")
if not account:
raise ValueError("You need to provide an account")
op = operations.WithdrawVesting(
**{
"account":
account,
"vesting_shares":
'{:.{prec}f} {asset}'.format(
float(amount), prec=6, asset="VESTS"),
})
return self.finalizeOp(op, account, "active")
def transfer_to_vesting(self, amount, to=None, account=None):
""" Vest STEEM
:param float amount: number of STEEM to vest
:param str to: (optional) the source account for the transfer if not
``default_account``
:param str account: (optional) the source account for the transfer
if not ``default_account``
"""
if not account:
account = configStorage.get("default_account")
if not account:
raise ValueError("You need to provide an account")
if not to:
to = account # powerup on the same account
op = operations.TransferToVesting(
**{
"from":
account,
"to":
to,
"amount":
'{:.{prec}f} {asset}'.format(
float(amount), prec=3, asset='STEEM')
})
return self.finalizeOp(op, account, "active")
def convert(self, amount, account=None, request_id=None):
""" Convert SteemDollars to Steem (takes one week to settle)
:param float amount: number of VESTS to withdraw
:param str account: (optional) the source account for the transfer
if not ``default_account``
:param str request_id: (optional) identifier for tracking the
conversion`
"""
if not account:
account = configStorage.get("default_account")
if not account:
raise ValueError("You need to provide an account")
if request_id:
request_id = int(request_id)
else:
request_id = random.getrandbits(32)
op = operations.Convert(
**{
"owner":
account,
"requestid":
request_id,
"amount":
'{:.{prec}f} {asset}'.format(
float(amount), prec=3, asset='SBD')
})
return self.finalizeOp(op, account, "active")
def transfer_to_savings(self, amount, asset, memo, to=None, account=None):
""" Transfer SBD or STEEM into a 'savings' account.
:param float amount: STEEM or SBD amount
:param float asset: 'STEEM' or 'SBD'
:param str memo: (optional) Memo
:param str to: (optional) the source account for the transfer if
not ``default_account``
:param str account: (optional) the source account for the transfer
if not ``default_account``
"""
assert asset in ['STEEM', 'SBD']
if not account:
account = configStorage.get("default_account")
if not account:
raise ValueError("You need to provide an account")
if not to:
to = account # move to savings on same account
op = operations.TransferToSavings(
**{
"from":
account,
"to":
to,
"amount":
'{:.{prec}f} {asset}'.format(
float(amount), prec=3, asset=asset),
"memo":
memo,
})
return self.finalizeOp(op, account, "active")
def transfer_from_savings(self,
amount,
asset,
memo,
request_id=None,
to=None,
account=None):
""" Withdraw SBD or STEEM from 'savings' account.
:param float amount: STEEM or SBD amount
:param float asset: 'STEEM' or 'SBD'
:param str memo: (optional) Memo
:param str request_id: (optional) identifier for tracking or
cancelling the withdrawal
:param str to: (optional) the source account for the transfer if
not ``default_account``
:param str account: (optional) the source account for the transfer
if not ``default_account``
"""
assert asset in ['STEEM', 'SBD']
if not account:
account = configStorage.get("default_account")
if not account:
raise ValueError("You need to provide an account")
if not to:
to = account # move to savings on same account
if request_id:
request_id = int(request_id)
else:
request_id = random.getrandbits(32)
op = operations.TransferFromSavings(
**{
"from":
account,
"request_id":
request_id,
"to":
to,
"amount":
'{:.{prec}f} {asset}'.format(
float(amount), prec=3, asset=asset),
"memo":
memo,
})
return self.finalizeOp(op, account, "active")
def transfer_from_savings_cancel(self, request_id, account=None):
""" Cancel a withdrawal from 'savings' account.
:param str request_id: Identifier for tracking or cancelling
the withdrawal
:param str account: (optional) the source account for the transfer
if not ``default_account``
"""
if not account:
account = configStorage.get("default_account")
if not account:
raise ValueError("You need to provide an account")
op = operations.CancelTransferFromSavings(**{
"from": account,
"request_id": request_id,
})
return self.finalizeOp(op, account, "active")
def claim_reward_balance(self,
reward_steem='0 STEEM',
reward_sbd='0 SBD',
reward_vests='0 VESTS',
account=None):
""" Claim reward balances.
By default, this will claim ``all`` outstanding balances. To bypass
this behaviour, set desired claim amount by setting any of
`reward_steem`, `reward_sbd` or `reward_vests`.
Args:
reward_steem (string): Amount of STEEM you would like to claim.
reward_sbd (string): Amount of SBD you would like to claim.
reward_vests (string): Amount of VESTS you would like to claim.
account (string): The source account for the claim if not
``default_account`` is used.
"""
if not account:
account = configStorage.get("default_account")
if not account:
raise ValueError("You need to provide an account")
# if no values were set by user, claim all outstanding balances on
# account
if none(
int(first(x.split(' ')))
for x in [reward_sbd, reward_steem, reward_vests]):
a = Account(account, steemd_instance=self.steemd)
reward_steem = a['reward_steem_balance']
reward_sbd = a['reward_sbd_balance']
reward_vests = a['reward_vesting_balance']
op = operations.ClaimRewardBalance(
**{
"account": account,
"reward_steem": reward_steem,
"reward_sbd": reward_sbd,
"reward_vests": reward_vests,
})
return self.finalizeOp(op, account, "posting")
def delegate_vesting_shares(self, to_account, vesting_shares,
account=None):
""" Delegate SP to another account.
Args:
to_account (string): Account we are delegating shares to
(delegatee).
vesting_shares (string): Amount of VESTS to delegate eg. `10000
VESTS`.
account (string): The source account (delegator). If not specified,
``default_account`` is used.
"""
if not account:
account = configStorage.get("default_account")
if not account:
raise ValueError("You need to provide an account")
op = operations.DelegateVestingShares(
**{
"delegator": account,
"delegatee": to_account,
"vesting_shares": str(Amount(vesting_shares)),
})
return self.finalizeOp(op, account, "active")
def witness_feed_publish(self,
steem_usd_price,
quote="1.000",
account=None):
""" Publish a feed price as a witness.
:param float steem_usd_price: Price of STEEM in USD (implied price)
:param float quote: (optional) Quote Price. Should be 1.000, unless
we are adjusting the feed to support the peg.
:param str account: (optional) the source account for the transfer
if not ``default_account``
"""
if not account:
account = configStorage.get("default_account")
if not account:
raise ValueError("You need to provide an account")
op = operations.FeedPublish(
**{
"publisher": account,
"exchange_rate": {
"base": "%s SBD" % steem_usd_price,
"quote": "%s STEEM" % quote,
}
})
return self.finalizeOp(op, account, "active")
def witness_update(self, signing_key, url, props, account=None):
""" Update witness
:param pubkey signing_key: Signing key
:param str url: URL
:param dict props: Properties
:param str account: (optional) witness account name
Properties:::
{
"account_creation_fee": x,
"maximum_block_size": x,
"sbd_interest_rate": x,
}
"""
if not account:
account = configStorage.get("default_account")
if not account:
raise ValueError("You need to provide an account")
try:
PublicKey(signing_key)
except Exception as e:
raise e
op = operations.WitnessUpdate(
**{
"owner": account,
"url": url,
"block_signing_key": signing_key,
"props": props,
"fee": "0.000 STEEM",