Giter Site home page Giter Site logo

pywaves's Introduction

PyWaves

PyWaves is an object-oriented Python interface to the Waves blockchain platform.

Getting Started

You can install PyWaves using:

pip install pywaves

Documentation

The library utilizes classes to represent various Waves data structures:

  • pywaves.Address
  • pywaves.Asset
  • pywaves.AssetPair
  • pywaves.Order

Code Example

import pywaves as pw

myAddress = pw.Address(privateKey='CtMQWJZqfc7PRzSWiMKaGmWFm4q2VN5fMcYyKDBPDx6S')
otherAddress = pw.Address('3PNTcNiUzppQXDL9RZrK3BcftbujiFqrAfM')
myAddress.sendWaves(otherAddress, 10000000)
myToken = myAddress.issueAsset('Token1', 'My Token', 1000, 0)
while not myToken.status():
	pass
myAddress.sendAsset(otherAddress, myToken, 50)

Address Class

pywaves.Address(address, publicKey, privateKey, seed) Creates a new Address object

attributes:

  • address
  • publicKey
  • privateKey
  • seed

methods:

balance(assetId='', confirmations=0) returns balance of Waves or other assets

assets() returns a list of assets owned by the address

issueAsset(name, description, quantity, decimals=0, reissuable=False, txFee=DEFAULT_ASSET_FEE, timestamp=0) issue a new asset

reissueAsset(Asset, quantity, reissuable=False, txFee=DEFAULT_ASSET_FEE, timestamp=0) reissue an asset

burnAsset(Asset, quantity, txFee=DEFAULT_ASSET_FEE, timestamp=0) burn the specified quantity of an asset

sendWaves(recipient, amount, attachment='', txFee=DEFAULT_TX_FEE, timestamp=0) send specified amount of Waves to recipient

massTransferWaves(transfers, attachment='', timestamp=0) sending Waves tokens via a mass transfer

sendAsset(recipient, asset, amount, attachment='', txFee=DEFAULT_TX_FEE, timestamp=0) send specified amount of an asset to recipient

massTransferWaves(self, transfers, attachment='', timestamp=0) sending an asset via mass transfer

cancelOrder(assetPair, order) cancel an order

buy(assetPair, amount price, maxLifetime=30*86400, matcherFee=DEFAULT_MATCHER_FEE, timestamp=0) post a buy order

tradableBalance(assetPair) get tradable balance for the specified asset pair

sell(assetPair, amount, price, maxLifetime=30*86400, matcherFee=DEFAULT_MATCHER_FEE, timestamp=0) post a sell order

lease(recipient, amount, txFee=DEFAULT_LEASE_FEE, timestamp=0) post a lease transaction

leaseCancel(leaseId, txFee=DEFAULT_LEASE_FEE, timestamp=0) cancel a lease

getOrderHistory(assetPair) get order history for the specified asset pair

cancelOpenOrders(assetPair) cancel all open orders for the specified asset pair

deleteOrderHistory(assetPair) delete order history for the specified asset pair

createAlias(alias, txFee=DEFAULT_ALIAS_FEE, timestamp=0) create alias

sponsorAsset(assetId, minimalFeeInAssets, txFee=pywaves.DEFAULT_SPONSOR_FEE, timestamp=0) sponsoring assets

setScript(script, txFee=pywaves.DEFAULT_SCRIPT_FEE, timestamp=0) sets a script for this address

dataTransaction(data, timestamp=0) sets data for the account. data should be a json array with entries including type (bool, binary, int, string), key and value

deleteDataEntry(key) deletes a given data entry, identified by key, from the data storage of the account

setScript(scriptSource, txFee=pywaves.DEFAULT_SCRIPT_FEE, timestamp=0) issue a smart asset

setAssetScript(asset, scriptSource, txFee=pywaves.DEFAULT_ASSET_SCRIPT_FEE, timestamp=0) set a new script for a smart asset

invokeScript(dappAddress, functionName, params, payments, feeAsset = None, txFee=pywaves.DEFAULT_INVOKE_SCRIPT_FEE) invoke a script on a given dapp address

Asset Class

pywaves.Asset(assetId) Creates a new Asset object

attributes:

  • status
  • assetId
  • issuer
  • name
  • description
  • quantity
  • decimals = 0
  • reissuable = False

methods:

status() returns 'Issued' if the asset exists

AssetPair Class

pywaves.AssetPair(asset1, asset2) Creates a new AssetPair object with 2 Asset objects

attributes:

  • asset1
  • asset2

methods:

orderbook() get order book

ticker() get ticker with 24h ohlcv data

last() get traded price

open() get 24h open price

high() get 24h high price

low() get 24h low price

close() get 24h close price (same as last())

vwap() get 24h vwap price

volume() get 24h volume

priceVolume() get 24h price volume

trades(n) get the last n trades

trades(from, to) get the trades in from/to interval

candles(timeframe, n) get the last n candles in the specified timeframe

candles(timeframe, from, to) get the candles in from/to interval in the specified timeframe

Order Class

pywaves.Order(orderId, assetPair, address='') Creates a new Order object

attributes:

  • status
  • orderId
  • assetPair
  • address
  • matcher
  • matcherPublicKey

methods:

status() returns current order status cancel() cancel the order

WXFeeCalculator Class

This class is meant to provide the necessary functionality to calculate fees according to the new WX fee structure

All values here for price and amounts of tokens are always in the smallest unit of the token ("satoshis").

Methods:

calculateDynamicFee() calculates the dynamic fee for a trade

calculateDynamicDiscountFee() calculates the dynamic discounted fee for a trade

calculatePercentSellingFee(priceAssetId, amountAssetId, amountToSell) calculates the percentage selling fee for a trade

calculatePercentDiscountedSellingFee(priceAssetId, amountAssetId, amountToSell) calculates the discounted percentage selling fee for a trade

calculatePercentBuyingFee(priceAssetId, price, amountToBuy) calculates the percentage buying fee for a trade

calculatePercentDiscountedBuyingFee(priceAssetId, price, amountToBuy) calculates the discounted percentage buying fee for a trade

Example:

import pywaves as pw

config = {
    'amountAsset': 'WAVES',
    'priceAsset': '25FEqEjRkqK6yCkiT7Lz6SAYz7gUFCtxfCChnrVFD5AT',
    'privateKey': 'xxx'
}

pw.setNode('https://nodes-testnet.wavesnodes.com/', chain='testnet')
pw.setMatcher('http://matcher-testnet.waves.exchange')

wxFeeCalculator = pw.WXFeeCalculator()
address = pw.Address(privateKey=config['privateKey'])
tradingPair = pw.AssetPair(pw.Asset(config['amountAsset']), pw.Asset(config['priceAsset']))
price = 5
amountToBuy = 1000000000
matcherFee = wxFeeCalculator.calculatePercentDiscountedBuyingFee(config['priceAsset'], price, amountToBuy)
tx = address.buy(tradingPair, amountToBuy, price, matcherFee = matcherFee, matcherFeeAssetId = 'EMAMLxDnv3xiz8RXg8Btj33jcEw3wLczL3JKYYmuubpc')
print (tx)

Other functions

pywaves.setNode(node, chain, chain_id) set node URL ('http://ip-address:port') and chain (either 'mainnet' or 'testnet', or any other chain, if you also define the chain id)

pywaves.setChain(chain, chain_id) set chain (either 'mainnet' or 'testnet', or any other chain if you also supply the chain id)

pywaves.setOffline() switch to offline mode; sign tx locally without broadcasting to network

pywaves.setOnline() switch to online mode; sign tx locally a broadcast to network

pywaves.validateAddress(address) checks if the provided address is a valid Waves address

pywaves.setMatcher(node) set matcher URL ('http://ip-address:port')

pywaves.setDatafeed(node) set datafeed URL ('http://ip-address:port')

pywaves.height() get blockchain height

pywaves.lastblock() get last block

pywaves.block(n) get block at specified height

pywaves.tx(id) get transaction details

pywaves.stateChangeForTx(id): get the state changes for the given tx by id

pywaves.stateChangesForAddress(address, limit = 1000): get the last (with a default of 1000) state changes for the given address

pywaves.symbols() get list of symbol-asset mapping

pywaves.markets() get all traded markets with tickers

pywaves.{SYMBOL_NAME} get predefined asset for the specified symbol (pywaves.WAVES, pywaves.BTC, pywaves.USD,...)

Default Fees

The fees for waves/asset transfers, asset issue/reissue/burn and matcher transactions are set by default as follows:

  • DEFAULT_TX_FEE = 100000
  • DEFAULT_ASSET_FEE = 100000000
  • DEFAULT_MATCHER_FEE = 1000000
  • DEFAULT_LEASE_FEE = 100000
  • DEFAULT_ALIAS_FEE = 100000
  • DEFAULT_SPONSOR_FEE = 100000000
  • DEFAULT_SCRIPT_FEE = 100000

More Examples

Playing with addresses:

import pywaves as pw

# generate a new address
myAddress = pw.Address("<some address>")
myAddress._generate()

# set an address with an address
myAddress = pw.Address('3P6WfA4qYtkgwVAsWiiB6yaea2X8zyXncJh')

# get an existing address from seed
myAddress = pw.Address(seed='seven wrist bargain hope pattern banner plastic maple student chaos grit next space visa answer')

# get an existing address from privateKey
myAddress = pw.Address(privateKey='CtMQWJZqfc7PRzSWiMKaGmWFm4q2VN5fMcYyKDBPDx6S')

# get an existing address from a publicKey
address = pw.Address(publicKey=EYNuSmW4Adtcc6AMCZyxkiHMPmF2BZ2XxvjpBip3UFZL”)

# get an address from a seed with a different nonce (This is especially useful for accessing addresses generated by nodes)
myAddress = pw.Address(seed='seven wrist bargain hope pattern banner plastic maple student chaos grit next space visa answer', nonce=1)

Balances:

import pywaves as pw

myAddress = pw.Address('3P6WfA4qYtkgwVAsWiiB6yaea2X8zyXncJh')

# get Waves balance
print("Your balance is %18d" % myAddress.balance())

# get Waves balance after 20 confirmations 
print("Your balance is %18d" % myAddress.balance(confirmations = 20))

# get an asset balance
print("Your asset balance is %18d" % myAddress.balance('DHgwrRvVyqJsepd32YbBqUeDH4GJ1N984X8QoekjgH8J'))

Waves and asset transfers:

import pywaves as pw

myAddress = pw.Address(privateKey='CtMQWJZqfc7PRzSWiMKaGmWFm4q2VN5fMcYyKDBPDx6S')

# send Waves to another address
myAddress.sendWaves(recipient = pw.Address('3PNTcNiUzppQXDL9RZrK3BcftbujiFqrAfM'),
                    amount = 100000000)

# send asset to another address
myToken = pw.Asset('4ZzED8WJXsvuo2MEm2BmZ87Azw8Sx7TVC6ufSUA5LyTV')
myAddress.sendAsset(recipient = pw.Address('3PNTcNiUzppQXDL9RZrK3BcftbujiFqrAfM'),
                    asset = myToken,
                    amount = 1000)

Issuing an asset:

import pywaves as pw

myToken = myAddress.issueAsset( name = "MyToken",
                                description = "This is my first token",
                                quantity = 1000000,
                                decimals = 2 )

Create an alias:

import pywaves as pw

pw.setNode(node = 'http://127.0.0.1:6869', chain = 'testnet')

myAddress = pw.Address(privateKey='CtMQWJZqfc7PRzSWiMKaGmWFm4q2VN5fMcYyKDBPDx6S')
myAddress.createAlias("MYALIAS1")

Mass payment:

import pywaves as pw

recipients =   ['3PBbp6bg2YEnHfdJtYM7jzzXYQeb7sx5oFg',
                '3P4A27aCd3skNja46pcgrLYEnK36TkSzgUp',
                '3P81U3ujotNUwZMWALdcJQLzBVbrAuUQMfs',
                '3PGcKEMwQcEbmeL8Jhe9nZQRBNCNdcHCoZP',
                '3PKjtzZ4FhKrJUikbQ1hRk5xbwVKDyTyvkn']

myAddress = pw.Address(privateKey = "CtMQWJZqfc7PRzSWiMKaGmWFm4q2VN5fMcYyKDBPDx6S")

for address in recipients:
	myAddress.sendWaves(pw.Address(address), 1000000)

Mass transfer of Waves (feature 11)

import pywaves as pw

transfers = [
	{ 'recipient': '3N1xca2DY8AEwqRDAJpzUgY99eq8J9h4rB3', 'amount': 1 },
	{ 'recipient': '3N3YWbQ27NnK7tek6ASFh38Bj93guLxxSi1', 'amount': 2 },
	{ 'recipient': '3MwiB5UkWxt4X1qJ8DQpP2LpM3m48V1z5rC', 'amount': 3 }
]

address = pw.Address(privateKey = "CtMQWJZqfc7PRzSWiMKaGmWFm4q2VN5fMcYyKDBPDx6S")
address.massTransferWaves(transfers)

Mass transfer of Assets (feature 11)

import pywaves as pw

transfers = [
	{ 'recipient': '3N1xca2DY8AEwqRDAJpzUgY99eq8J9h4rB3', 'amount': 1 },
	{ 'recipient': '3N3YWbQ27NnK7tek6ASFh38Bj93guLxxSi1', 'amount': 2 },
	{ 'recipient': '3MwiB5UkWxt4X1qJ8DQpP2LpM3m48V1z5rC', 'amount': 3 }
]

address = pw.Address(privateKey = "CtMQWJZqfc7PRzSWiMKaGmWFm4q2VN5fMcYyKDBPDx6S")
address.massTransferAssets(transfers, pw.Asset('9DtBNdyBCyViLZHptyF1HbQk73F6s7nQ5dXhNHubtBhd'))

Data Transaction:

import pywaves as py

myAddress = py.Address(privateKey='CtMQWJZqfc7PRzSWiMKaGmWFm4q2VN5fMcYyKDBPDx6S')

data = [{
        'type':'string', 
        'key': 'test', 
        'value':'testval'
        }]

myAddress.dataTransaction(data)

Token airdrop:

import pywaves as pw

myAddress = pw.Address(privateKey = '`')
myToken = pw.Asset('4ZzED8WJXsvuo2MEm2BmZ87Azw8Sx7TVC6ufSUA5LyTV')
amount = 1000

with open('recipients.txt') as f:
	lines = f.readlines()
for address in lines:
	myAddress.sendAsset(pw.Address(address.strip()), myToken, amount)

Add a script to an account:

import pywaves as pw
import base64

pw.setNode(node='<node>', chain='testnet')

script = 'match tx { \n' + \
'  case _ => true\n' + \
'}'
address = pw.Address(privateKey = "<private key>")
tx = address.setScript(script, txFee=1000000)

Issue a Smart Asset

imort pywaves as pw
import base64

pw.setNode(node='<node>', chain='testnet')

script = 'match tx { \n' + \
'  case _ => true\n' + \
'}'
address = pw.Address(privateKey = '<private key>')
tx = address.issueSmartAsset('smartTestAsset', 'an asset for testingsmart assets', 1000, script, 2)

Set a new script for a Smart Asset

import pywaves as pw
import base64

pw.setNode(node='<node>', chain='testnet')

script = 'match tx { \n' + \
'  case _ => true\n' + \
'}'
address = pw.Address(privateKey = '<private key>')
tx = address.setAssetScript(pw.Asset('<asset id>'), script)

Invoking a script on a dapp address

import pywaves as pw

pw.setNode(node='<node>', chain='testnet')

address = pw.Address(privateKey = '<private key>')
tx = address.invokeScript('3N5Wq22bLSf3gt5VwHTCRbRnETeSwpuT8kK', 'fundRecipient', [{"type": "integer", "value": 100, }, { "type": "string", "value": "test" }, { "type": "boolean", "value": True }], [ { "amount": 100, "assetId": "BGNVLgPKLwiBiZ7vWLcy3r92MzpPCU2DuUb4tv9W6gMi" } ])

Working with contracts

import pywaves as pw

pw.setNode(node = '<node>', 'T')

contract = pw.Contract('3N7XfieeJ8dHyMJfs7amukzxKB1PfMXzHzi', '<seed>')
contract.faucet()

Working with oracles

Querrying oracles:

import pywaves as pw

oracle = pw.Oracle(oracleAddress = '3P4PCxsJqMzQBALo8zANHtBDZRRquobHQp7')
# getting all data entries for an oracle
print(oracle.getData())
# getting data for a specific key of an oracle
print(oracle.getData('order_total_EeH5DRjdMnoYDhNbtkLsRNZq95etJUqWtvMDBCXojBoy'))
# getting all data entries of an oracle filtered by a regular expression
print(oracle.getData(regex = '^order_total_.*$'))

Storing data in an oracle:

import pywaves as pw

pw.setNode('https://testnode1.wavesnodes.com', 'T')

oracle = pw.Oracle(seed='<your seed here>')
print(oracle.storeData('oracle_test', 'string', 'test entry from oracle class'))

Working with more than one network

import pywaves as pw

config = pw.ParallelPyWaves()
config.setNode('https://testnode1.wavesnodes.com', 'testnet')

tAddress = pw.Address(seed = "test test test", pywaves = config)

address = pw.Address(seed = "test test test")
print(tAddress.address)
print(address.address)
print(tAddress.address)

Playing with Waves Matcher node (DEX):

import pywaves as pw

# set Matcher node to use
pw.setMatcher(node = 'http://127.0.0.1:6886')

# post a buy order
BTC = pw.Asset('4ZzED8WJXsvuo2MEm2BmZ87Azw8Sx7TVC6ufSUA5LyTV')
USD = pw.Asset('6wuo2hTaDyPQVceETj1fc5p4WoMVCGMYNASN8ym4BGiL')
BTC_USD = pw.AssetPair(BTC, USD)
myOrder = myAddress.buy(assetPair = BTC_USD, amount = 15e8, price = 95075)

# post a sell order
WCT = pw.Asset('6wuo2hTaDyPQVceETj1fc5p4WoMVCGMYNASN8ym4BGiL')
Incent = pw.Asset('FLbGXzrpqkvucZqsHDcNxePTkh2ChmEi4GdBfDRRJVof')
WCT_Incent = pw.AssetPair(WCT, Incent)
myOrder = myAddress.sell(assetPair = WCT_Incent, amount = 100e8, price = 25e8)

# post a buy order using Waves as price asset
BTC = pw.Asset('4ZzED8WJXsvuo2MEm2BmZ87Azw8Sx7TVC6ufSUA5LyTV')
BTC_WAVES = pw.AssetPair(BTC, pw.WAVES)
myOrder = myAddress.buy(assetPair = BTC_WAVES, amount = 1e8, price = 50e8)

# cancel an order
myOrder.cancel()
# or
myAddress.cancelOrder(assetPair, myOrder)

Getting Market Data from Waves Data Feed (WDF):

import pywaves as pw

# set the asset pair
WAVES_BTC = pw.AssetPair(pw.WAVES, pw.BTC)

# get last price and volume
print("%s %s" % (WAVES_BTC.last(), WAVES_BTC.volume()))

# get ticker
ticker = WAVES_BTC.ticker()
print(ticker['24h_open'])
print(ticker['24h_vwap'])

# get last 10 trades
trades = WAVES_BTC.trades(10)
for t in trades:
	print("%s %s %s %s" % (t['buyer'], t['seller'], t['price'], t['amount']))
	
# get last 10 daily OHLCV candles
ohlcv = WAVES_BTC.candles(1440, 10)
for t in ohlcv:
	print("%s %s %s %s %s" % (t['open'], t['high'], t['low'], t['close'], t['volume']))

LPOS

import pywaves as pw

# connect to a local testnet node
pw.setNode(node = 'http://127.0.0.1:6869', chain = 'testnet')

myAddress = pw.Address(privateKey = 'CsBpQpNE3Z1THNMS9vJPaXqYwN9Hgmhd9AsAPrM3tiuJ')
minerAddress = pw.Address('3NBThmVJmcexzJ9itP9KiiC2K6qnGQwpqMq')

# lease 1000 Waves to minerAddress
leaseId = myAddress.lease(minerAddress, 100000000000)

# revoke the lease
myAddress.leaseCancel(leaseId)

Doing simple multisig

Thanks to the new functionality of the TxSigner and TxGenerator classes, new functionality like multisig is possible:

pw.setNode('https://nodes-testnet.wavesnodes.com', 'T')
firstAddress = address.Address(seed = 'this is just a simple test seed one')
secondAddress = address.Address(seed = 'this is just a simple test seed two')

generator = txGenerator.TxGenerator()
signer = txSigner.TxSigner()
tx = generator.generateSendWaves(secondAddress, 1, firstAddress.publicKey, txFee=500000)
signer.signTx(tx, firstAddress.privateKey)
signer.signTx(tx, secondAddress.privateKey)

res = firstAddress.broadcastTx(tx)

Using PyWaves in a Python shell

Check an address balance:

>>> import pywaves as pw
>>> pw.Address('3P31zvGdh6ai6JK6zZ18TjYzJsa1B83YPoj')
address = 3P31zvGdh6ai6JK6zZ18TjYzJsa1B83YPoj
publicKey = 
privateKey = 
seed = 
balances:
  Waves = 1186077288304570
  BDMRyZsmDZpgKhdM7fUTknKcUbVVkDpMcqEj31PUzjMy (Tokes) = 43570656915
  RRBqh2XxcwAdLYEdSickM589Vb4RCemBCPH5mJaWhU9 (Ripto Bux) = 4938300000000
  4rmhfoscYcjz1imNDvtz45doouvrQqDpbX7xdfLB4guF (incentCoffee) = 7
  Ftim86CXM6hANxArJXZs2Fq7XLs3nJvgBzzEwQWwQn6N (Waves) = 2117290600000000
  E4ip4jzTc4PCvebYn1818T4LNoYBVL3Y4Y4dMPatGwa9 (BitCoin) = 500000000000
  FLbGXzrpqkvucZqsHDcNxePTkh2ChmEi4GdBfDRRJVof (Incent) = 12302659925430
  GQr2fpkfmWjMaZCbqMxefbiwgvpcNgYdev7xpuX6xqcE (KISS) = 1000
  DxG3PLganyNzajHGzvWLjc4P3T2CpkBGxY4J9eJAAUPw (UltraCoin) = 200000000000000
  4eWBPyY4XNPsFLoQK3iuVUfamqKLDu5o6zQCYyp9d8Ae (LIKE) = 1000
>>> 

Generate a new address:

>>> import pywaves as pw
>>> newAddress = pw.Address('<some address>')
>>> newAddress._generate()
address = 3P6WfA4qYtkgwVAsWiiB6yaea2X8zyXncJh
publicKey = EYNuSmW4Adtcc6AMCZyxkiHMPmF2BZ2XxvjpBip3UFZL
privateKey = CtMQWJZqfc7PRzSWiMKaGmWFm4q2VN5fMcYyKDBPDx6S
seed = seven wrist bargain hope pattern banner plastic maple student chaos grit next space visa answer
balances:
  Waves = 0
>>> 

Check an asset:

>>> import pywaves as pw
>>> pw.Asset('DHgwrRvVyqJsepd32YbBqUeDH4GJ1N984X8QoekjgH8J')
status = Issued
assetId = DHgwrRvVyqJsepd32YbBqUeDH4GJ1N984X8QoekjgH8J
issuer = 3PPKF2pH4KMYgsDixjrhnWrPycVHr1Ye37V
name = WavesCommunity
description = Waves community token.
quantity = 1000000000
decimals = 2
reissuable = False

Post an order and check its status:

>>> myOrder = myAddress.buy(pw.AssetPair(token1, token2), 1, 25)
>>> myOrder
status = Accepted
id = ARZdYgfXz3ksRMvhnGeLLJnn3CQnz7RCa7U6dVw3zert
asset1 = AFzL992FQbhcgSZGKDKAiRWcjtthM55yVCE99hwbHf88
asset2 = 49Aha2RR2eunR3KZFwedfdi7K9v5MLQbLYcmVdp2QkZT
sender.address = 3P6WfA4qYtkgwVAsWiiB6yaea2X8zyXncJh
sender.publicKey = EYNuSmW4Adtcc6AMCZyxkiHMPmF2BZ2XxvjpBip3UFZL
matcher = http://127.0.0.1:6886

Cancel the order

>>> myOrder.cancel()
>>> myOrder
status = Cancelled
id = ARZdYgfXz3ksRMvhnGeLLJnn3CQnz7RCa7U6dVw3zert
asset1 = AFzL992FQbhcgSZGKDKAiRWcjtthM55yVCE99hwbHf88
asset2 = 49Aha2RR2eunR3KZFwedfdi7K9v5MLQbLYcmVdp2QkZT
sender.address = 3P6WfA4qYtkgwVAsWiiB6yaea2X8zyXncJh
sender.publicKey = EYNuSmW4Adtcc6AMCZyxkiHMPmF2BZ2XxvjpBip3UFZL
matcher = http://127.0.0.1:6886

Offline signing and custom timestamps

Offline signing a future transaction:

>>> import pywaves as pw
>>> pw.setOffline()
>>> myAddress=pw.Address(privateKey="F2jVbjrKzjUsZ1AQRdnd8MmxFc85NQz5jwvZX4BXswXv")
>>> recipient=pw.Address("3P8Ya6Ary5gzwnzbBXDp3xjeNG97JEiPcdA")
# sign a future tx to transfer 100 WAVES to recipient
# the tx is valid on Jan 1st, 2020 12:00pm
>>> myAddress.sendWaves(recipient, amount=100e8, timestamp=1577880000000)
{'api-endpoint': '/assets/broadcast/transfer',
 'api-type': 'POST',
 'api-data': '{"fee": 100000,
			   "timestamp": 1577880000000,
			   "senderPublicKey": "27zdzBa1q46RCMamZ8gw2xrTGypZnbzXs5J1Y2HbUmEv",
			   "amount": 10000000000,
			   "attachment": "",
			   "recipient": "3P8Ya6Ary5gzwnzbBXDp3xjeNG97JEiPcdA"
			   "signature": "YetPopTJWC4WBPXbneWv9g6YEp6J9g9rquZWjewjdQnFbmaxtXjrRsUu69NZzHebVzUGLrhQiFFoguXJwdUn8BH"}'}

Offline signing time lock/unlock transactions:

>>> import pywaves as pw
>>> pw.setOffline()
>>> myAddress=pw.Address(privateKey="F2jVbjrKzjUsZ1AQRdnd8MmxFc85NQz5jwvZX4BXswXv")
# generate a lockbox address
>>> lockAddress=pw.Address('<some address>')
>>> lockAddress._generate()
# sign the 'lock' tx to send 100e8 to the lockbox (valid on Nov 1st, 2017)
>>> myAddress.sendWaves(lockAddress, 100e8, timestamp=1509537600000)
{'api-endpoint': '/assets/broadcast/transfer',
 'api-type': 'POST',
 'api-data': '{"fee": 100000,
               "timestamp": 1509537600000,
               "senderPublicKey": "27zdzBa1q46RCMamZ8gw2xrTGypZnbzXs5J1Y2HbUmEv",
               "amount": 10000000000,
               "attachment": "",
               "recipient": "3P3UbyQM9W7WzTgjYkLuBrPZZeWsiUtCcpv",
               "signature": "5VgT6qWxJwxEyrxFNfsi67QqbyUiGq9Ka7HVzgovRTTDT8nLRyuQv2wBAJQhRiXDkTTV6zsQmHnBkh8keCaFPoNT"}'}
# sign the 'unlock' tx to send funds back to myAddress (valid on Jan 1st, 2020)
>>> lockAddress.sendWaves(myAddress, 100e8-200000, txFee=200000, timestamp=1577880000000)
{'api-endpoint': '/assets/broadcast/transfer',
 'api-type': 'POST',
 'api-data': '{"fee": 200000,
               "timestamp": 1577880000000,
			   "senderPublicKey": "52XnBGnAVZmw1CHo9aJPiMsVMiTWeNGSNN9aYJ7cDtx4",
			   "amount": 9999800000,
			   "attachment": "",
			   "recipient": "3P7tfdCaTyYCfg5ojxNahEJDSS4MZ7ybXBY",
			   "signature": "3beyz1sqKefP96LaXWT3CxdPRW86DAxcj6wgWPyyKq3SgdotVqnKyWXDyeHnBzCq1nC7JA9CChTmo1c1iVAv6C4T"}'}
# delete lockbox address and private key
>>> del lockAddress

Connecting to a different node or chain

PyWaves supports both mainnet and testnet chains. By default, PyWaves connects to the mainnet RPC server at https://nodes.wavesnodes.com. It's possible to specify a different server and chain with the setNode() function

import pywaves as pw

# connects to a local testnet node
pw.setNode(node = 'http://127.0.0.1:6869', chain = 'testnet')

# connects to a local mainnet node
pw.setNode(node = 'http://127.0.0.1:6869', chain = 'mainnet')

License

Code released under the MIT License.

pywaves's People

Contributors

aquitipeando avatar arsenlosenko avatar aspadeto avatar blackturtle123 avatar deemru avatar ewsterrenburg avatar isgeny avatar ismagin avatar ivister avatar jansenmarc avatar kardanovir avatar m4ikz avatar pivoo81 avatar pywaves avatar sabotagebeats avatar shoreward avatar silassarius avatar vlzhr avatar yurial avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pywaves's Issues

Wrong response from AssetPair.orderbook()

I want to save orderbook's data from wavesplatform. I try to send request one time per 10 sec. Almost always all is OK, but sometimes I'm getting error while parsing orderbook JSON about one hundred times in a row:
Expecting value: line 1 column 1 (char 0)
When I tried to look at response at these moments, I saw next message:
An error occurred: Ask timed out on [Actor[akka://wavesplatform/user/matcher#-1822518904]] after [5000 ms]. Sender[null] sent message of type "com.wavesplatform.matcher.market.OrderBookActor$GetOrderBookRequest".
Is it my local problem or something wrong with WAVES node? Can you help please?

Error in example Getting Market Data from Waves Data Feed (WDF):

Running example:

trades = WAVES_BTC.trades(10)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/xxxxxxxx/.local/lib/python2.7/site-packages/pywaves/asset.py", line 116, in trades
    return self._getMarketData('/api/trades/%s/%s/%d' % (a1, a2, limit))
NameError: global name 'a1' is not defined

All other code from this section work fine.

pw.Address(privateKey='63cvmsKSNlas8234FAKEPRIVATEKEYtjxhasWV254Sd') outputting byte character for some reason

PYTHON

print(pw.Address(privateKey='63cvmsKSNlas8234FAKEPRIVATEKEYtjxhasWV254Sd')

OUTPUT:

address = b'3PDW8Bxf18fjiTf6YVyBVBHi6czCkvSky8v'
publicKey = b'7BLUAUs3LTrspThIsiSFakeToo7fMskdN023z6E4xK'
privateKey = b'63cvmsKSNlas8234FAKEPRIVATEKEYtjxhasWV254Sd'
seed =
nonce = 0
balances:
Waves = 0

Why am I getting this "byte" designation character on my output? Also, when I try to send assets, I get insufficient balance, I'm guessing the b character in front of my address and keys is hindering the script from retrieving my balances because it's looking for the balance of b'address' instead of just 'address'. Have read this is a Python3.6 issue. Tried running in Python2, but couldn't even get PyWAVES to install via PIP that way...

HELP!?

Sendasset not working in testnet

Hi I tried using sendasset in mainnet and testnet, mainnet its working fine, but testnet, I am getting Asset not issued exception.

readme.md is incorrect regarding new address generation

We had some trouble in connection with gateways while generating new addresses with empty private keys. The usual workaround is to generate a new seed and generate an address from this seed. By this, the client is explicitely in full controll of the necessary credentials.

https://github.com/PyWaves/PyWaves/#generate-a-new-address

it says in the readme.md that this should work - how do you generate new seed?

Originally posted by @sabotagebeats in #68 (comment)

Example code does not work anymore

Hi guys,

I'm trying to use this code (approximately one month ago it does worked for me with appropriate result):

import pywaves as pw
# post a buy order
addr = pw.Address(privateKey='MyPrivateKey')
BTC = pw.Asset('4ZzED8WJXsvuo2MEm2BmZ87Azw8Sx7TVC6ufSUA5LyTV')
USD = pw.Asset('6wuo2hTaDyPQVceETj1fc5p4WoMVCGMYNASN8ym4BGiL')
BTC_USD = pw.AssetPair(BTC, USD)
myOrder = addr.buy(assetPair = BTC_USD, amount = 15, price = 95)

But now instead of POST to:

http://nodes.wavesnodes.com/matcher/orderbook

there have been redirect to:

http://matcher.wavesnodes.com/matcher/orderbook

and I got following result:

{
  "matcherPublicKey" : "7kPFrHDiGw1rCm7LPszuECwWYL3dMf6iMifLRDJQZMzy",
  "markets" : [ {
    "amountAsset" : "9L3E6fELS4ZYih5St4hwmyvJYTLRzXGK5ei8eFJCcnFg",
    "amountAssetName" : "INRDC",
    "amountAssetInfo" : {
      "decimals" : 8
    },
    "priceAsset" : "WAVES",
    "priceAssetName" : "WAVES",
    "priceAssetInfo" : {
      "decimals" : 8
    },
    "created" : 1533950240808
  }, ...
}

It looks like that DEX changed API or smth like that. Maybe you know what happened.
Thanks in advance.

Getting from publicKey

Decoding empty private key while getting an existing address from a publicKey.

pw.Address(publicKey='EYNuSmW4Adtcc6AMCZyxkiHMPmF2BZ2XxvjpBip3UFZL')
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    pw.Address(publicKey='EYNuSmW4Adtcc6AMCZyxkiHMPmF2BZ2XxvjpBip3UFZL')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pywaves/address.py", line 207, in __init__
    self._generate(publicKey=publicKey)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pywaves/address.py", line 293, in _generate
    self.privateKey = base58.b58encode(privKey)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/base58.py", line 45, in b58encode
    type(v).__name__)
TypeError: a bytes-like object is required, not 'str'

Wrong default tx fee for sponsored transaction

def sendAsset(self, recipient, asset, amount, attachment='', feeAsset='', txFee=pywaves.DEFAULT_TX_FEE, timestamp=0):
if user sets sponsoredAsset to feeAsset and not sets txFee, you should send request for asset details and get minSposoredFee instead of using DEFAULT_TX_FEE.
minSposoredFee could be less or more then default one.

For example, if minSposoredFee = 10_000 and user not sets txFee, then tx will cost 0.01 waves
if minSposoredFee = 1_000_000 then default txFee will be less then minimal

error.incorrect.publicKeyAccount

Hello, I have a problem, and I can't find the solution :(

. This is when I start a purchase I have this displayed.
[ERROR] {' error': 1,' message':' failed to parse json message',' cause': None,' validationErrors': {' obj. matcherPublicKey':[{' msg':[' error. incorrect. publicKeyAccount'],' args':[]}}}}

However, I have well inserted the public key given to me in the waveswallet lite. Thank you in advance:)

State check failed on sending sponsored transaction

Hi,
I'm trying to send sponsored transaction in testnet but receive an error.

root = pw.Address(seed=ROOT_SEED)
recipient = pw.Address(address=RECIPIENT_ADDRESS)
attachment = ATTACHMENT
asset = pw.Asset(config['waves']['asset_id'])

tx = root.sendAsset(
    recipient = recipient,
    asset = asset,
    feeAsset = asset,
    amount = 1000000,
    attachment = ATTACHMENT) 

Output:

{  
   'error':112,
   'message':'State check failed. Reason: Script doesn\'t exist and proof doesn\'t validate as signature for {"type":4,"id":"29p9orSEPsKVVBW9dfhpXR1q6P1P5B71STDPe4uByfXp","sender":"3MzoaDZwcWffax62N9haEvF6dvGvu455KXw","senderPublicKey":"DuSZ8n8wrHnBKAqEEV688z6nvFUnWkNeC8U1ibe3eA66","fee":100000,"timestamp":1551765392268,"proofs":["4NuqWqqKmAyyD5W3FYtXRkuhRWMbpUsHhJJ6rVKZxzYZS7hcCCfCEe42xCUg6raB6w62uYtZutX4aE5GASTcRTNq"],"version":2,"recipient":"3Mxo3eTNkuDoJXdiAmbxCTxbxFaekcadBap","assetId":"6TwYqtBCr6zCqjLUTUne3gGAJX1nUY3WeZpTqsn1DYAB","feeAssetId":"6TwYqtBCr6zCqjLUTUne3gGAJX1nUY3WeZpTqsn1DYAB","feeAsset":"6TwYqtBCr6zCqjLUTUne3gGAJX1nUY3WeZpTqsn1DYAB","amount":1000000,"attachment":"9tmzPf5YiwHaT9n4hXqsu47qciKiNFxxJrCdTisUrjN9EEvvak5CdDkAYv22XH6"}',
   'tx':{  
      'type':4,
      'id':'29p9orSEPsKVVBW9dfhpXR1q6P1P5B71STDPe4uByfXp',
      'sender':'3MzoaDZwcWffax62N9haEvF6dvGvu455KXw',
      'senderPublicKey':'DuSZ8n8wrHnBKAqEEV688z6nvFUnWkNeC8U1ibe3eA66',
      'fee':100000,
      'timestamp':1551765392268,
      'proofs':[  
         '4NuqWqqKmAyyD5W3FYtXRkuhRWMbpUsHhJJ6rVKZxzYZS7hcCCfCEe42xCUg6raB6w62uYtZutX4aE5GASTcRTNq'
      ],
      'version':2,
      'recipient':'3Mxo3eTNkuDoJXdiAmbxCTxbxFaekcadBap',
      'assetId':'6TwYqtBCr6zCqjLUTUne3gGAJX1nUY3WeZpTqsn1DYAB',
      'feeAssetId':'6TwYqtBCr6zCqjLUTUne3gGAJX1nUY3WeZpTqsn1DYAB',
      'feeAsset':'6TwYqtBCr6zCqjLUTUne3gGAJX1nUY3WeZpTqsn1DYAB',
      'amount':1000000,
      'attachment':'9tmzPf5YiwHaT9n4hXqsu47qciKiNFxxJrCdTisUrjN9EEvvak5CdDkAYv22XH6'
   }
}

Upgraded pywaves to the latest version

Installing collected packages: base58, pyblake2, python-axolotl-curve25519, certifi, chardet, idna, urllib3, requests, pywaves
Successfully installed base58-0.2.5 certifi-2018.11.29 chardet-3.0.4 idna-2.8 pyblake2-1.1.2 python-axolotl-curve25519-0.4.1.post2 pywaves-0.8.22 requests-2.21.0 urllib3-1.24.1

What can be possibly wrong? Thanks

Getting sum amount of orderbook

I am trying to get all order from 'amount' waves_usd pair. I did it. now I want to use that value to calculate orders amount but I got an error: 'float' object is not iterable
İn the below codes without sum(x) 'print(x) working fine and type(x) = floats
how can I get sum() function works.

`import pywaves as pw

usd = 'Ft8X1v1LTa1ABafufpaCWyVj8KkaxUWE6xBhW6sNFJck'

WavesUsd = pw.AssetPair(pw.WAVES, pw.Asset(usd))

a = WavesUsd.orderbook()['bids']

for i in a:
x = (i['amount'] / 100000000)
print(sum(x))
`

Loop to see balances

I am now able to iterate in the token list and show something similar to every token balance.
It seems that the balance is not the expected one.
Last row is not able to get me the decimal adjusted balance, or it shows 99999999 for the number 1.

In waves explorer I get

DtHrdJwXovcVDzhuAwpWM9... Ktoken 1.00
while pywaves:
Token name: b'Ktoken', Address: DtHrdJwXovcVDzhuAwpWM9..., Decimals:2, or :100
balance: 999999.0

In waves explorer i get
53VHGAEfVNJnByeMbu9… Auct token 2000.00000000
while in pywaves:
Token name: b’Auct token’, Address: 53VHGAEfVNJnByeMbu9…, Decimals:8, or :100000000
balance: 350000000.0

What is going on? And what is the b’’ surrounding the token name?

`import pywaves as pw

myAddress = pw.Address(privateKey='prikey')
print("Public key:" + myAddress.publicKey)
print("Your balance without decimals is %18d" % myAddress.balance())
print("Your balance is %18f" % (myAddress.balance() / pw.WAVES.decimals))

print("Assets no: %d" % len(myAddress.assets()))
for assetAddress in myAddress.assets():
aToken=pw.Asset(assetAddress)
print("Token name: %s" % aToken.name, end=", ")
print("Address: %s" % assetAddress, end=", ")
#print("descr: " + str(aToken.description))
print("Decimals:" + str(aToken.decimals) + ", or :" + str(10**aToken.decimals))
print("balance: " + str(float(aToken.quantity) / pow(10, aToken.decimals)))
`

How to Execute the Script

I have tried the script it got executed but nothing shows as a result in python.

How to do that please explain?
Does I need to make any edit in script to run it.

pw.WAVES assetID = ''

Hi there,

I'm using a django backend to print out a report of how a current token is doing, when I attempt to use pw.WAVES as part of the assetPair in pw.AssetPair(pw.WAVES, pw.Asset('XYZ')), it returns the error:
{u'status': u'error', u'message': u'Asset pair not available'}

When I simply print out the AssetPair it returns:
asset1 = asset2 = XYZ

pw.WAVES returns nothing? Any ideas?

Transaction Error

I am using local node waves testnet. transaction is not working. I posted the error. Please check it.

import pywaves as pw
pw.setNode(node = 'http://127.0.0.1:6869',chain = 'testnet')
address = '3Mq6YmrnfoSt5T36i3S2XPXpXh8kP87DUw4'
publicKey = '9u6mN4kN8U7iQVsyNaru7ko6VV3E3pQ6sqcmmDwM6k7a'
privateKey = 'GczfiQJoqkp4E4pXGj7wicx53nckPyG46EWChEd9brzM'
myAddress = pw.Address(privateKey=privateKey) 
t_id = myAddress.sendWaves(recipient=pw.Address('3MwMwdzo6k1wwDE8JgiZmbM7nXEL6xmftPc'),amount = 10000000)

Error:
{'error': 112, 'message': 'State check failed. Reason: invalid signature', 'tx': {'type': 4, 'id': 'BPP2CSFUBey5UybNDZpeeKJ7aEptMc2mXVmdYnUrAf3F', 'sender': '3Mq6YmrnfoSt5T36i3S2XPXpXh8kP87DUw4', 'senderPublicKey': '9u6mN4kN8U7iQVsyNaru7ko6VV3E3pQ6sqcmmDwM6k7a', 'fee': 100000, 'timestamp': 1521476122683, 'signature': '4PYFgEYtKJWG1zXQtmw3KMgR54opCnNBkfNQKieP4A6ywGNHainhfpNqnqhMwsoNeSW42C5kNyNs6K76tsSg1o3E', 'recipient': '3MwMwdzo6k1wwDE8JgiZmbM7nXEL6xmftPc', 'assetId': None, 'amount': 10000000, 'feeAsset': None, 'attachment': '1'}}

New connections are now refused?

I have been using the python shell to interact with the blockchain, I went to create an AssetPair to view recent transactions between then and I get this error back:

raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=80): Max retries exceeded with url: /api/trades//WAVES/8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS/10 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x110037110>: Failed to establish a new connection: [Errno 61] Connection refused',))

This may be to do with the fact I attempted to change my 'datafeed' node to my localhost, I then tried to change it to 0.0.0.0 but its still not working.

Thanks

Script doesn't exist and proof doesn't validate as signature for

I have a problem with send a Asset transaction:

{  
   'error':112,
   'message':'State check failed. Reason: Script doesn\'t exist and proof doesn\'t validate as signature for {"type":4,"id":"4Jyia9ZcU4BiE3md4fovgdiPoRciRLQeMrDoxEG1UunM","sender":"3NCUUgk262yj7p4SSaMYconszYumDCZNK1E","senderPublicKey":"G5gcKJDA2LoD2cGDNupzenCiyx99m1shRZPuGhApbWcH","fee":100,"timestamp":1552800226007,"proofs":["teZUfy6g3B95Xja4fqwACmwGbQuZaxXp9aJ4ypi1qe9uPq5vz9KvMBNUKXsrRFRpZW3cbf2X9bsjbpC4qdyeXoM"],"version":2,"recipient":"3N4yVvp6xSpAK6JkjBgs2Jx8vnzFZrC4vhH","assetId":"8LVvxzo4b2bTwud5wjLkC7cRHYD8Y3J5q6tEkpWN38nm","feeAssetId":"8LVvxzo4b2bTwud5wjLkC7cRHYD8Y3J5q6tEkpWN38nm","feeAsset":"8LVvxzo4b2bTwud5wjLkC7cRHYD8Y3J5q6tEkpWN38nm","amount":1250,"attachment":"AXG4Fgp"}',
   'tx':{  
      'type':4,
      'id':'4Jyia9ZcU4BiE3md4fovgdiPoRciRLQeMrDoxEG1UunM',
      'sender':'3NCUUgk262yj7p4SSaMYconszYumDCZNK1E',
      'senderPublicKey':'G5gcKJDA2LoD2cGDNupzenCiyx99m1shRZPuGhApbWcH',
      'fee':100,
      'timestamp':1552800226007,
      'proofs':[           'teZUfy6g3B95Xja4fqwACmwGbQuZaxXp9aJ4ypi1qe9uPq5vz9KvMBNUKXsrRFRpZW3cbf2X9bsjbpC4qdyeXoM'
      ],
      'version':2,
      'recipient':'3N4yVvp6xSpAK6JkjBgs2Jx8vnzFZrC4vhH',
      'assetId':'8LVvxzo4b2bTwud5wjLkC7cRHYD8Y3J5q6tEkpWN38nm',
      'feeAssetId':'8LVvxzo4b2bTwud5wjLkC7cRHYD8Y3J5q6tEkpWN38nm',
      'feeAsset':'8LVvxzo4b2bTwud5wjLkC7cRHYD8Y3J5q6tEkpWN38nm',
      'amount':1250,
      'attachment':'AXG4Fgp'
   }
}

myAddress.issueAsset doesn't work

I use code as in example in README.md.

import pywaves as pw
node = "https://testnode1.wavesnodes.com"
chain = "testnet"

pw.setNode(node = node, chain = chain)
myAddress = pw.Address(privateKey='...')

myAddress.sendWaves(otherAddress, 10000000)
myToken = myAddress.issueAsset('Token1', 'My Token', 1000, 0)
s = myToken.status()
print(s)

raised:

----> 9 myToken = myAddress.issueAsset('Token1', 'My Token', 1000, 0)
     10 s = myToken.status()
     11 print(s)

e:\ProgramData\Anaconda3\lib\site-packages\pywaves\address.py in issueAsset(self, name, description, quantity, decimals, reissuable, txFee)
    337                 return req
    338             else:
--> 339                 return pywaves.Asset(req['assetId'])
    340 
    341     def reissueAsset(self, Asset, quantity, reissuable=False, txFee=pywaves.DEFAULT_TX_FEE):

KeyError: 'assetId'

Incompatible with base58-1.0.3

What about adding support of base58-1.0.3 ? PyWaves uses base58-0.2.5 which is very old.
In my case I need use PyWaves and PyEOS and my project and they need different versions of base58

Btw: requierments doesnt say what version of base58 needed but with base58-1.0.3 sendWaves doesnt work

Generate a new address error

generate a new address

import pywaves as pw
myAddress = pw.Address()

Error Message:
myAddress = pw.Address()
File ".../address.py", line 225, in init
raise ValueError('Empty private key not allowed')
ValueError: Empty private key not allowed

myAddress.assets() not working on testnet

Hi Team when I tried to list all the assets in testnet, I got the below issue, but mainnet works good.

Code:
pw.setChain("testnet")
myAddress = pw.Address('3MpCH9ChCKbN5UYu6V8PrwrPJXVTsaGF1kn')
print(myAddress.assets());

Logs:
Traceback (most recent call last):
File "wavesBalance.py", line 18, in
print(myAddress.assets());
File "C:\Users\renick.j\PycharmProjects\wavesrest\venv\lib\site-packages\pywaves\address.py", line 253, in assets
req = pywaves.wrapper('/assets/balance/%s' % self.address)['balances']
KeyError: 'balances'

Sponsorship asset. Script doesn't exist and proof doesn't validate

Testnet example. Same for mannet

{
  "error": 112,
  "message": "State check failed. Reason: Script doesn't exist and proof doesn't validate as signature for {\"type\":14,\"id\":\"CMA7x65kVifW5zJYqvxhBDUsjfD1ELZyaCfWke7nXfub\",\"sender\":\"3N9atHZUYJ14qvoGeLyucmhMnNRSiRL7Sno\",\"senderPublicKey\":\"2ard3BP4uEC5WqXA4hZaHfTcVcS3BCupv1LNsTwYxFZc\",\"fee\":100000000,\"timestamp\":1532944766140,\"proofs\":[\"4bDGnLjbysVHweMis9MRNxG6pHfqzPKUfSYdC8ScY7xD2pvrXX97449N4Wi23mEUk4ZghN7Rzd1RtjqqaQmLa7Ea\"],\"version\":1,\"assetId\":\"8BF1ZmmMXRnURxPDoz1QqMpWBWQxrqQHKBQvgt5j5eVT\",\"minSponsoredAssetFee\":100000}",
  "tx": {
    "type": 14,
    "id": "CMA7x65kVifW5zJYqvxhBDUsjfD1ELZyaCfWke7nXfub",
    "sender": "3N9atHZUYJ14qvoGeLyucmhMnNRSiRL7Sno",
    "senderPublicKey": "2ard3BP4uEC5WqXA4hZaHfTcVcS3BCupv1LNsTwYxFZc",
    "fee": 100000000,
    "timestamp": 1532944766140,
    "proofs": [
      "4bDGnLjbysVHweMis9MRNxG6pHfqzPKUfSYdC8ScY7xD2pvrXX97449N4Wi23mEUk4ZghN7Rzd1RtjqqaQmLa7Ea"
    ],
    "version": 1,
    "assetId": "8BF1ZmmMXRnURxPDoz1QqMpWBWQxrqQHKBQvgt5j5eVT",
    "minSponsoredAssetFee": 100000
  }
}

Sending Ethereum to Other Ethereum Address (Invalid Address)

I did the following

myAddress = pw.Address(privateKey=wPrivate)
ethToken = pw.Asset('474jTeYx2r2Va35794tCScAXWJG9hU2HcgxzMowaZUnu')
myAddress.sendAsset(recipient=pw.Address('0xe85e4a16258a870d95e7f6908c38a40dd8637041'), token=ethToken, amount=float(amount))

I think the problem is if I insert a "Wave address" as my recipient it work, but if I insert a real "Ethereum" address, it will say invalid address.

Is there a way I can transfer my Ethereum to other ethereum wallet or my Bitcoin to other bitcoin wallet.

I hope to find a solution.

Thanks

Transaction?

You can make it so that we receive the latest transaction in 24 hours

Example code don't work

myAddress.buy(...) get error " TypeError: b'H9sXEScHzMhhmpcCpkS7FQwZfxa69vYV56TGNwGmyD8G' is not JSON serializable "
I think because you put at json.dumps({ }) byte code from crypto.sign function which return bytecode

Masspayment only works max 4 recipient?

In my machine, mass payment script only work for max 4 recipient,
when i try more than 100, python said "too much address"
but when i try to sent to 99, python have no feedback and comand line no hang, just back to

and i try 90 recipient, 80,70,60,50,40,30,20,10,9,8,7,6,5,4.
just 4 recipient its work and recorded to blockchain
http://wavesexplorer.com/tx/DHKZUijrcindKSZfKQJ4h8uoJ2eBrrCdxLy1cJpaWN9D

the attachment is working,

and when i try airdrop script work smoothly too.

But problem is i want to sent proportional based on hodling x token and masspayment didn't work,
What script you suggest for me?

Thank you

error with MassTransferTransaction when using 139 byte attachment

Hello! I Have got an error when try to send mass transfer asset transaction with attachment 139 byte.
'error': 112, 'message': 'State check failed. Reason: Fee in WAVES for com.wavesplatform.transaction.transfer.MassTransferTransaction does not exceed minimal value of 5500000 WAVES: 5100000'

Private key from seed

I generated address using waves full node. Can I generate private key from encoded seed that I get using node API

GET /addresses/seed/<address>

Maybe I am moron! lol

New to PY ( just fyi )

Created a index.py file with

#!/usr/bin/python 
import pywaves as pw
myAddress = pw.Address('XXX')
# get Waves balance
print("Your balance is %18d" % myAddress.balance())
# get Waves balance after 20 confirmations 
print("Your balance is %18d" % myAddress.balance(confirmations = 20))
# get an asset balance
print("Your asset balance is %18d" % myAddress.balance('XXX'))

added my address and I am getting 500 Internal error - added a htaccess
Options +ExecCGI
AddHandler cgi-script .py

Checked that the VPS as python ...

then tested ..

#!/usr/bin/python

print "Content-type: text/html\n\n"
print "How to run Python scripts in cPanel"

^^^ worked fine.

So, did I miss a line or something to import the py configs ?

massTransferAssets

Hi,

I'm trying to implement the "massTransferAssets" function in a python script but there is a problem that doesn't allow me to get it.

I use: myAddress.massTransferAssets(transfers, pywaves.Asset('Token_ID'))

"myAddress" and "transfers" are OK because when I use them with "massTransferWaves" it runs.

So, anyone has the same problem?

Installation Issue - python-axolotl-curve25519 dependency

I am having issues installing PyWaves. The dependency for python-axolotl-curve25519 is where the installation is failing.

I have installed the latest version of VS Community and have the Data Tools and Visual C++ for Python packages.

Notable Error Messages:

curve/curve25519-donna.c(49) : fatal error C1083: Cannot open include file: 'stdint.h': No such file or directory
  error: command 'C:\\Users\\Command Center\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2

Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\comman~1\\appdata\\local\\temp\\pip-install-dnebcs\\python-axolotl-curve25519\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users\comman~1\appdata\local\temp\pip-record-y36sug\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\comman~1\appdata\local\temp\pip-install-dnebcs\python-axolotl-curve25519\

image

buy and sell return None

Hello!

I try to post orders with buy and sell methods.

My code is very simple:

import pywaves as pw
privkey = 'privkey_here'
my_token = 'my_token_id_here'
myAddress = pw.Address(privateKey=privkey)
TOKEN = pw.Asset(my_token)
WAVES = pw.WAVES
TOKEN_WAVES = pw.AssetPair(TOKEN, WAVES)
myOrder = myAddress.buy(assetPair=TOKEN_WAVES, amount=1, price=1)
print(myOrder)

When it's executed I see None as order ID.

I tried to use different values of price and amount, the same result.

When I try to use amount like "1e8" I see an error:

Traceback (most recent call last):
  File "main.py", line 19, in <module>
    myOrder = myAddress.buy(assetPair=TOKEN_WAVES,
  File "/usr/local/lib/python3.8/site-packages/pywaves/address.py", line 766, in buy
    id = self._postOrder(assetPair.asset1, assetPair.asset2, b'\0', amount, normPrice, maxLifetime, matcherFee, timestamp)
  File "/usr/local/lib/python3.8/site-packages/pywaves/address.py", line 677, in _postOrder
    struct.pack(">Q", amount) + \
struct.error: required argument is not an integer

Also tried with Python 2 - the same (order post return None, but no errors about 1e8 numbers).

How I can post orders with the current version? Thanks.

Get address info

Hello,

I've an issue when I try to get the balance from my account: if I use the public address I get correctly the balance from that address, but when I use de private key I get no balance:

import pywaves as pw
pw.Address(<public_address>)
address =
publicKey =
privateKey =
seed =
nonce = 0
balances:
Waves = <my_balance>
(....)

But when I use private key I get:

pw.Address(privateKey="xxx")
address = b'<my_public_address>
publicKey = b'<my_public_key>
privateKey = b'<my_private_key>
seed =
nonce = 0
balances:
Waves = 0

Am I doing something wrong?

Thanks,

checking signature owner

Account X signed a message using its private key.
How can I validate that the signature is create by X having its address and the message?

issueAsset supports only latin characters

Hello. When I'm trying to use non-latin characters in field description of issueAsset, it raises unicode error. But blockchain itself supports this characters when asset is created with Waves client or through signing and broadcasting raw transaction.

myAsset = testAddr.issueAsset(name='TEST', description='тест', quantity=100000000, decimals=8)                                       
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/euphemia/work/python/mywill_backend/venv/lib/python3.6/site-packages/pywaves/address.py", line 321, in issueAsset
    struct.pack(">Q", txFee) + \
  File "/home/euphemia/work/python/mywill_backend/venv/lib/python3.6/site-packages/pywaves/crypto.py", line 17, in <lambda>
    str2bytes = lambda s: s.encode('latin-1')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256)

'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256)

It would be good if this library also supported any characters in asset description

rounding issues on normPrice calculation

Randomly starting receiving errors along the lines of:
[ERROR] Order Rejected - Invalid price, last 6 digits must be 0

seems that pow (which is used for the calculation of normPrice) sometimes returns 9.99999999 when 10.0 is meant. A simple test:
prices={0.00056328, 0.00056356, 0.00056384, 0.00056554, 0.00056639}
for price in prices:
print("input: " + str(price))
price1 = pow(10, 8 + 8 - 2) * price
print("pow: " + str(price1))
price1 = round(pow(10, 8 + 8 - 2) * price)
print("pow round: " + str(price1))
normPrice = int(pow(10, 8 + 8 - 2) * price)
print("normprice: " + str(normPrice))
normPrice = int(round(pow(10, 8 + 8 - 2) * price))
print("normprice round: " + str(normPrice))

Results from the test:

input: 0.00056328
pow: 56328000000.0
pow round: 56328000000
normprice: 56328000000
normprice round: 56328000000
input: 0.00056356
pow: 56355999999.99999
pow round: 56356000000
normprice: 56355999999
normprice round: 56356000000
input: 0.00056384
pow: 56384000000.0
pow round: 56384000000
normprice: 56384000000
normprice round: 56384000000
input: 0.00056554
pow: 56554000000.0
pow round: 56554000000
normprice: 56554000000
normprice round: 56554000000
input: 0.00056639
pow: 56638999999.99999
pow round: 56639000000
normprice: 56638999999
normprice round: 56639000000

Problem can be quite easily fixed by changing the normprice calculation from:
normPrice = int(pow(10, 8 + assetPair.asset2.decimals - assetPair.asset1.decimals) * price)
to:
normPrice = int(round(pow(10, 8 + assetPair.asset2.decimals - assetPair.asset1.decimals) * price))
in address.py

Not able to post order

I am getting error "TypeError: can't concat int to bytes" while trying to _postOrder().

I might be passing incorrect parameters for _postOrder(). Can you add an example code for _postOrder() in README.md as you have done for sendWaves().

base58 version

The requirements only state base58 as a requirement, not which version. By default this will install the latest version 2.0.0 which is incompatible with PyWaves (results in an invalid Address when opening an existing wallet from seed). Version needs to be specified (0.2.5)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.