Skip to content

Commit

Permalink
update beta [V3]
Browse files Browse the repository at this point in the history
  • Loading branch information
serderovsh committed Nov 18, 2018
1 parent eac91e1 commit ccb235b
Show file tree
Hide file tree
Showing 6 changed files with 126 additions and 24 deletions.
4 changes: 2 additions & 2 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[run]
source = .
omit = setup.py
branch = True
include = */tronapi/*
7 changes: 3 additions & 4 deletions tronapi/base/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,10 @@ def deprecated_for(replace_message):
"""
Decorate a deprecated function, with info about what to use instead, like:
@deprecated_for("toBytes()")
def toAscii(arg):
...
Examples:
>>> @deprecated_for("toBytes()")
>>> def toAscii(arg):
"""

def decorator(to_wrap):
@functools.wraps(to_wrap)
def wrapper(*args, **kwargs):
Expand Down
28 changes: 14 additions & 14 deletions tronapi/contract.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import copy
from typing import Dict, Any

from eth_utils import function_abi_to_4byte_selector, to_hex

Expand Down Expand Up @@ -189,23 +190,24 @@ def factory(cls, tron, class_name=None, **kwargs):
@classmethod
@deprecated_for("contract.constructor.transact")
def deploy(cls, **kwargs):
"""
Deploys the contract on a blockchain.
"""Deploy Contract
Deploys a contract.
Returns TransactionExtention, which contains an unsigned transaction.
Example:
.. code-block:: python
>>> MyContract.deploy(
fee_limit=10**9,
call_value=0,
consume_user_resource_percent=12
consume_user_resource_percent=10
)
Args:
**kwargs: Transaction parameters for the deployment
transaction as a dict
"""

if not cls.bytecode:
raise ValueError(
"Cannot deploy a contract that does not have 'bytecode' associated "
Expand All @@ -223,15 +225,15 @@ def deploy(cls, **kwargs):
# Contract owner address, converted to a hex string
owner_address = kwargs.setdefault('owner_address', cls.tron.default_address.hex)

# The compiled contract's identifier, used to interact with the Virtual Machine.
bytecode = to_hex(cls.bytecode)

# We write all the results in one object
deploy_transaction = dict(**kwargs)
deploy_transaction.setdefault('abi', cls.abi)
deploy_transaction.setdefault('bytecode', bytecode)
transaction = dict(**kwargs)
# Smart Contract's Application Binary Interface
transaction.setdefault('abi', cls.abi)
# The compiled contract's identifier, used to interact with the Virtual Machine.
transaction.setdefault('bytecode', to_hex(cls.bytecode))

if not is_integer(fee_limit) or fee_limit <= 0 or fee_limit > 10**9:
if not is_integer(fee_limit) or fee_limit <= 0 or \
fee_limit > 10 ** 9:
raise ValueError('Invalid fee limit provided')

if not is_integer(call_value) or call_value < 0:
Expand All @@ -244,9 +246,7 @@ def deploy(cls, **kwargs):
if not cls.tron.isAddress(owner_address):
raise InvalidAddress('Invalid issuer address provided')

deploy_data = cls.tron.manager.request('/wallet/deploycontract',
deploy_transaction)
return deploy_data
return cls.tron.manager.request('/wallet/deploycontract', transaction)

@classmethod
def constructor(cls):
Expand Down
5 changes: 5 additions & 0 deletions tronapi/providers/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ def _request(self, **kwargs):
kwargs.setdefault('timeout', 60)
response = self.session.request(**kwargs)
text = response.text

try:
json = response.json()
except ValueError:
Expand All @@ -122,4 +123,8 @@ def _request(self, **kwargs):
raise exc_cls(response.status_code, text, json, kwargs.get('url'))

data = json if json is not None else text

# Additional error interceptor that will occur in case of failed requests
if 'Error' in data:
raise ValueError(data['Error'])
return HttpResponse(response.status_code, response.headers, data)
101 changes: 99 additions & 2 deletions tronapi/transactionbuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
# --------------------------------------------------------------------------------------------

from datetime import datetime, timedelta
from typing import Dict

from tronapi.exceptions import InvalidTronError, TronError
from tronapi.exceptions import InvalidTronError, TronError, InvalidAddress
from tronapi.utils.help import is_valid_url
from tronapi.utils.types import is_string, is_integer, is_boolean

Expand Down Expand Up @@ -145,6 +146,57 @@ def unfreeze_balance(self, resource='BANDWIDTH', account=None):

return response

def purchase_token(self, to: str, token_id: str, amount: int, buyer=None):
"""Purchase a Token
Creates an unsigned ICO token purchase transaction.
Args:
to (str): is the address of the Token issuer
token_id (str): is the name of the token
amount (int): is the number of tokens created
buyer (str): is the address of the Token owner
"""
if buyer is None:
buyer = self.tron.default_address.hex

if not self.tron.isAddress(to):
raise InvalidAddress('Invalid to address provided')

if not len(token_id):
raise ValueError('Invalid token ID provided')

if amount <= 0:
raise ValueError('Invalid amount provided')

_to = self.tron.address.to_hex(to)
_from = self.tron.address.to_hex(buyer)

return self.tron.manager.request('/wallet/participateassetissue', {
'to_address': _to,
'owner_address': _from,
'asset_name': self.tron.toHex(text=token_id),
'amount': int(amount)
})

def withdraw_block_rewards(self, address: str = None):
"""Withdraw block rewards
Creates an unsigned Super Representative award balance withdraw transaction.
Args:
address (str): Optional address to withdraw from.
"""
if not address:
address = self.tron.default_address.hex

if not self.tron.isAddress(address):
raise InvalidAddress('Invalid address provided')

return self.tron.manager.request('/wallet/withdrawbalance', {
'owner_address': self.tron.address.to_hex(address)
})

def apply_for_sr(self, url, address):
"""Apply to become a super representative
Expand All @@ -164,6 +216,52 @@ def apply_for_sr(self, url, address):
'url': self.tron.toHex(text=url)
})

def vote(self, votes: Dict[str, int], voter_address: str = None):
"""Vote
Vote on the super representative
Args:
votes (dict): dictionary of SR address : vote count key-value pair
voter_address: voter address
Examples:
>>> from tronapi import Tron
>>>
>>> data = [
>>> ('TRJpw2uqohP7FUmAEJgt57wakRn6aGQU6Z', 1)
>>> ]
>>>
>>> tron = Tron()
>>> tron.transaction.vote(data)
"""
if voter_address is None:
voter_address = self.tron.default_address.hex

_view_vote = []

# We create a cycle to check all the received data for voting.
for sr_address, vote_count in votes:
if not self.tron.isAddress(sr_address):
raise InvalidAddress(
'Invalid SR address provided: ' + sr_address
)

if not is_integer(vote_count) or vote_count <= 0:
raise ValueError(
'Invalid vote count provided for SR: ' + sr_address
)

_view_vote.append({
'vote_address': self.tron.address.to_hex(sr_address),
'vote_count': int(vote_count)
})

return self.tron.manager.request('/wallet/votewitnessaccount', {
'owner_address': self.tron.address.to_hex(voter_address),
'votes': _view_vote
})

def vote_proposal(self, proposal_id, has_approval, voter_address):
"""Proposal approval
Expand Down Expand Up @@ -398,4 +496,3 @@ def create_token(self, **kwargs):
})

return response

5 changes: 3 additions & 2 deletions tronapi/trx.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def get_block_transaction_count(self, block: Any):

return len(transaction)

def get_transaction_from_block(self, block: Any, index=0):
def get_transaction_from_block(self, block: Any, index: int = 0):
"""Get transaction details from Block
Args:
Expand Down Expand Up @@ -528,7 +528,8 @@ def list_nodes(self):
"""List the nodes which the api fullnode is connecting on the network"""
response = self.tron.manager.request('/wallet/listnodes')
callback = map(lambda x: {
'address': '{}:{}'.format(self.tron.toText(x['address']['host']), str(x['address']['port']))
'address': '{}:{}'.format(self.tron.toText(x['address']['host']),
str(x['address']['port']))
}, response['nodes'])

return list(callback)
Expand Down

0 comments on commit ccb235b

Please sign in to comment.