Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit bc7ff4a

Browse files
committed
update exchange for btc markets
1 parent 14968c1 commit bc7ff4a

29 files changed

Lines changed: 751 additions & 432 deletions

api/offers.py

Lines changed: 86 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -17,52 +17,98 @@ def offers_response(response_dict):
1717
if len(response_dict[field]) != 1:
1818
return (None, 'Multiple values for field '+field)
1919

20+
filterActive = True
21+
if 'onlyActive' in response_dict:
22+
try:
23+
if response_dict['onlyActive'][0] in [0,False,'false']:
24+
filterActive = False
25+
except:
26+
return (None, 'Query field "onlyActive" accepts value true or false')
27+
28+
2029
if response_dict['type'][0].upper() == "TIME":
2130
time = int(response_dict['time'][0]) if 'time' in response_dict else 86400
22-
data = filterOffersByTime( response_dict['currencyType'][0] , time )
31+
data = filterOffersByTime( response_dict['currencyType'][0] , time , filterActive )
2332
else:
2433
address_arr = json.loads(response_dict['address'][0])
25-
data = filterOffers(address_arr) if type( address_arr ) == type( [] ) else { 'ERR': 'Address field must be a list or array type' }
34+
data = filterOffers(address_arr, filterActive) if type( address_arr ) == type( [] ) else { 'ERR': 'Address field must be a list or array type' }
2635

2736
response_status='OK'
2837
response='{"status":"'+response_status+'", "data":'+ str(json.dumps(data)) +'}'
2938

3039
return (response, None)
3140

32-
def filterOffersByTime( currency_type , time_seconds):
41+
def filterOffersByTime( currency_type , time_seconds , filter):
3342
#filter by currency
34-
currency = ('1' if (currency_type in ['OMNI','OMN','MSC'] ) else '2')
43+
44+
try:
45+
currency = int(currency_type)
46+
except:
47+
try:
48+
if (currency_type in ['OMNI','OMN','MSC']):
49+
currency = 1
50+
else:
51+
return []
52+
except:
53+
return []
54+
3555

3656
atleast_now = int( str( int(time.time() - time_seconds) ) + '000' )
3757

58+
eq = ""
59+
if filter:
60+
eq = " and ao.offerstate='active'"
61+
3862
ROWS=dbSelect("select ao.*,t.txhash,t.protocol,t.txdbserialnum,t.txtype,t.txversion,t.ecosystem,t.txrecvtime,t.txstate,t.txerrorcode,"
3963
"t.txblocknumber,t.txseqinblock,txj.txdbserialnum,txj.protocol,txj.txdata "
4064
"from activeoffers ao, transactions t, txjson txj where ao.propertyidselling=%s and ao.propertyiddesired='0' and "
41-
"ao.createtxdbserialnum=t.txdbserialnum and ao.createtxdbserialnum=txj.txdbserialnum", [currency])
65+
"ao.createtxdbserialnum=t.txdbserialnum and ao.createtxdbserialnum=txj.txdbserialnum"+str(eq), [currency])
4266

4367
response = [ mapSchema(row) for row in ROWS if int(mapSchema(row)['tx_time']) > atleast_now ]
4468

4569
return sorted(response, key=lambda x: int(x['tx_time']) )
46-
70+
71+
72+
def getName(propertyid):
73+
if int(propertyid) == 1:
74+
name = 'Omni Token #1'
75+
elif int(propertyid) == 2:
76+
name = 'Test Omni Token #2'
77+
else:
78+
try:
79+
ROWS=dbSelect("select propertyname from smartproperties where protocol='Omni' and propertyid=%s",[int(propertyid)])
80+
name = ROWS[0][0]+" #"+str(propertyid)
81+
except:
82+
name = "#"+str(propertyid)
83+
return name
84+
4785
def mapSchema(row):
4886
#print row, 'row'
4987
try:
5088
rawdata = json.loads(row[-1])
5189
except TypeError:
5290
rawdata = row[-1]
5391

54-
#We only map tx21 and tx22
5592
if row[-11] == 20:
5693
#print row
5794
ppc = Decimal( rawdata['bitcoindesired'] ) / Decimal( rawdata['amount'] )
5895
color = getcolor(row[10])
96+
97+
#print rawdata
98+
99+
if rawdata['divisible']:
100+
amount_available = '%.8f' % ( Decimal(row[1]) / Decimal(1e8) )
101+
else:
102+
amount_available = str(row[1])
103+
59104
response = {
60105
'action': -1, #don't have this data
61106
'block': str(row[-5]),
62107
'currencyId': str(rawdata['propertyid']),
63-
'currency_str': 'Omni Token' if str(rawdata['propertyid']) == '1' else 'Test Omni Token',
108+
'propertyid': rawdata['propertyid'],
109+
'currency_str': getName(rawdata['propertyid']),
64110
'formatted_amount': str(rawdata['amount']),
65-
'formatted_amount_available': '%.8f' % ( Decimal(row[1]) / Decimal(1e8) ),
111+
'formatted_amount_available': amount_available,
66112
'formatted_bitcoin_amount_desired': '%.8f' % ( Decimal(row[2]) / Decimal(1e8) ),
67113
'formatted_block_time_limit': str(rawdata['timelimit']),
68114
'formatted_fee_required': str(rawdata['feerequired']),
@@ -71,32 +117,40 @@ def mapSchema(row):
71117
'from_address': rawdata['sendingaddress'],
72118
'tx_type_str': "Sell offer",
73119
'color': color,
120+
'status':row[10],
74121
'invalid': False if rawdata['valid'] == True else True,
75122
'to_address': "sell offer",
76123
'tx_hash': rawdata['txid'],
77124
'tx_time': str(rawdata['blocktime']) + '000'
78125
}
79126
else:
127+
#We only map tx21 and tx22
80128
sellofferdata = getsell(str(row[3]))
81129
try:
82130
selljson=json.loads(sellofferdata[-1])
83131
except TypeError:
84132
selljson=sellofferdata[-1]
85133

86134
ppc = Decimal( selljson['bitcoindesired'] ) / Decimal( selljson['amount'] )
87-
remaining = Decimal(row[1]) / Decimal(1e8)
135+
136+
if selljson['divisible']:
137+
remaining = Decimal(row[1]) / Decimal(1e8)
138+
else:
139+
remaining = Decimal(row[1])
140+
88141
response = {
89142
'block': str(row[-5]),
90143
'status': 'valid' if row[5] == 'unpaid' or row[5] == 'paid-partial' else 'closed',
91144
'currencyId': str(rawdata['propertyid']),
92-
'currency_str': 'Omni Token' if str(rawdata['propertyid']) == '1' else 'Test Omni Token',
145+
'propertyid': rawdata['propertyid'],
146+
'currency_str': getName(rawdata['propertyid']),
93147
'formatted_amount': '%.8f' % remaining,
94148
'sell_offer_txid': selljson['txid'],
95149
#'formatted_amount_available': str( row[1] / Decimal(1e8) ),
96150
#'formatted_bitcoin_amount_desired': str( row[2] / Decimal(1e8) ),
97151
'formatted_price_per_coin': '%.8f' % ppc,
98152
'bitcoin_required': '%.8f' % ( Decimal( ppc ) * Decimal( remaining ) ),
99-
'payment_expired': False,
153+
'payment_expired': row[7],
100154
'from_address': rawdata['sendingaddress'],
101155
'tx_type_str': 'Sell accept',
102156
'color': "bgc-accept", #needed for compatibility
@@ -135,18 +189,22 @@ def genQs(prefix, tbl_abbr, field, array):
135189
qs += prefix + ' ' + tbl_abbr + '.' + field + '=\'' + entry +'\' ' # "and/or" table abbrev "." fieldname = next address
136190
return qs + ') '
137191

138-
def filterOffers(addresses):
192+
def filterOffers(addresses, filter):
139193
#Returns all *ACTIVE* accepts and offers for a given address
140194
offers = {}
141195

142196
#Query all active offers
143197
qs = genQs('or', 'ao', 'seller', addresses)
144198

199+
eq = ""
200+
if filter:
201+
eq = " and ao.offerstate='active'"
202+
145203
ROWS=dbSelect("select ao.*,t.txhash,t.protocol,t.txdbserialnum,t.txtype,t.txversion,t.ecosystem,t.txrecvtime,t.txstate,t.txerrorcode,"
146204
"t.txblocknumber,t.txseqinblock,txj.txdbserialnum,txj.protocol,txj.txdata "
147205
"from activeoffers ao, transactions t, txjson txj where " + qs + \
148-
" and offerstate='active' and ao.propertyiddesired='0' and ao.createtxdbserialnum=t.txdbserialnum "
149-
"and ao.createtxdbserialnum=txj.txdbserialnum")
206+
" and ao.propertyiddesired='0' and ao.createtxdbserialnum=t.txdbserialnum "
207+
"and ao.createtxdbserialnum=txj.txdbserialnum"+str(eq))
150208

151209
#print query
152210

@@ -157,22 +215,26 @@ def filterOffers(addresses):
157215
jsondata=row[-1]
158216

159217
address = jsondata['sendingaddress']
160-
currency = 'OMNI' if jsondata['propertyid'] == 1 else 'T-OMNI'
218+
#pid = jsondata['propertyid']
219+
#currency = 'PROD' if (pid != 2 and pid <2147483650) else 'TEST'
161220

162221
if address not in offers: offers[ address ] = {}
163-
if 'offer_tx' not in offers[ address ]: offers[ address ]['offer_tx'] = {}
222+
if 'offer_tx' not in offers[ address ]: offers[ address ]['offer_tx'] = []
164223

165-
offers[ address ]['offer_tx'][ currency ] = mapSchema(row)
224+
offers[ address ]['offer_tx'].append( mapSchema(row))
166225
#only one active offer per address
167226

168227
#Query all active accepts
169228
qs = genQs('or', 'oa', 'buyer', addresses)
170229

230+
eq = ""
231+
if filter:
232+
eq = " and expiredstate='f'"
233+
171234
ROWS=dbSelect("select oa.*,t.txhash,t.protocol,t.txdbserialnum,t.txtype,t.txversion,t.ecosystem,t.txrecvtime,t.txstate,t.txerrorcode,"
172235
"t.txblocknumber,t.txseqinblock,txj.txdbserialnum,txj.protocol,txj.txdata "
173236
"from offeraccepts oa, transactions t, txjson txj where " + qs + \
174-
" and expiredstate='f' and oa.linkedtxdbserialnum=t.txdbserialnum "
175-
"and oa.linkedtxdbserialnum=txj.txdbserialnum")
237+
" and oa.linkedtxdbserialnum=t.txdbserialnum and oa.linkedtxdbserialnum=txj.txdbserialnum"+str(eq))
176238

177239
#print query
178240

@@ -182,12 +244,13 @@ def filterOffers(addresses):
182244
except TypeError:
183245
jsondata=row[-1]
184246
address = jsondata['referenceaddress']
185-
currency = 'OMNI' if jsondata['propertyid'] == 1 else 'T-OMNI'
247+
#pid = jsondata['propertyid']
248+
#currency = 'PROD' if (pid != 2 and pid <2147483650) else 'TEST'
186249

187250
if address not in offers: offers[ address ] = {}
188-
if 'accept_tx' not in offers[ address ]: offers[ address ]['accept_tx'] = {}
251+
if 'accept_tx' not in offers[ address ]: offers[ address ]['accept_tx'] = []
189252

190-
offers[ address ]['accept_tx'][ currency ] = mapSchema(row)
253+
offers[ address ]['accept_tx'].append( mapSchema(row))
191254
#only one active offer per address
192255

193256
return offers

api/omnidex.py

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def getDesignatingCurrencies():
6363
if value not in valid_values:
6464
abort(make_response('Field \'ecosystem\' invalid value, request failed', 400))
6565

66-
ecosystem = "Production" if value == 1 else "Test"
66+
ecosystem = "Production" if value == 1 else "Test"
6767
except KeyError:
6868
abort(make_response('No field \'ecosystem\' in request, request failed', 400))
6969
except ValueError:
@@ -74,6 +74,44 @@ def getDesignatingCurrencies():
7474
except:
7575
filter = True
7676

77+
try:
78+
if 'version' in request.form and request.form['version'] in ['1',1]:
79+
ret=getDesignatingCurrenciesOmniExchange(ecosystem,filter)
80+
else:
81+
ret=getDesignatingCurrenciesOmniDex(ecosystem,filter)
82+
except Exception as e:
83+
print e
84+
ret=getDesignatingCurrenciesOmniDex(ecosystem,filter)
85+
86+
return jsonify(ret)
87+
88+
def getDesignatingCurrenciesOmniExchange(ecosystem,filter):
89+
print "getDesignatingCurrenciesOmniExchange",ecosystem,filter
90+
91+
designating_currencies = dbSelect("select sp.propertyid, sp.propertyname, sp.propertytype from smartproperties sp where sp.protocol='Omni' and "
92+
"sp.propertyid in (select distinct(propertyidselling) from activeoffers where offerstate='active' and propertyiddesired=0 and "
93+
"CASE WHEN %s='Production' THEN "
94+
"propertyidselling > 0 and propertyidselling < 2147483648 and propertyidselling !=2 "
95+
"ELSE propertyidselling > 2147483650 or propertyidselling=2 END)",[ecosystem])
96+
97+
designating_currencies.sort(key = lambda x: x[0])
98+
99+
if filter:
100+
listfilter=dbSelect("select propertyid from smartproperties where (flags->>'scam')::boolean or (flags->>'duplicate')::boolean order by propertyid")
101+
dc=(x for x in designating_currencies if [x[0]] not in listfilter )
102+
else:
103+
listfilter=[]
104+
dc=designating_currencies
105+
106+
return {"status" : 200, "currencies": [
107+
{
108+
"propertyid":currency[0], "propertyname" : currency[1], "propertytype" : currency[2], "displayname" : str(currency[1])+" #"+str(currency[0])
109+
} for currency in dc],
110+
"filter": [id for pid in listfilter for id in pid] }
111+
112+
def getDesignatingCurrenciesOmniDex(ecosystem,filter):
113+
print "getDesignatingCurrenciesOmniDex",ecosystem,filter
114+
77115
#designating_currencies = dbSelect("select distinct ao.propertyiddesired as propertyid, sp.propertyname from activeoffers ao "
78116
# "inner join SmartProperties sp on ao.propertyiddesired = sp.propertyid and sp.ecosystem = %s "
79117
#"where (ao.propertyidselling not in (1, 2, 31)) or (ao.propertyidselling = 1 and ao.propertyiddesired = 31) "
@@ -98,11 +136,11 @@ def getDesignatingCurrencies():
98136
listfilter=[]
99137
dc=designating_currencies
100138

101-
return jsonify({"status" : 200, "currencies": [
139+
return {"status" : 200, "currencies": [
102140
{
103141
"propertyid":currency[0], "propertyname" : currency[1], "displayname" : str(currency[1])+" #"+str(currency[0])
104142
} for currency in dc],
105-
"filter": [id for pid in listfilter for id in pid] })
143+
"filter": [id for pid in listfilter for id in pid] }
106144

107145

108146
@app.route('/<int:denominator>')

api/omnitransaction.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def get_unsigned(self):
8686
return { "status": "NOT OK", "error": "Couldn't get list of unspent tx's. Response Code: " + str(dirty_txes['code']) }
8787

8888
if (dirty_txes['error'][:3]=='Low'):
89-
return { "status": "NOT OK", "error": "Not enough funds, try again. Needed: " + str(fee_total) + " but Have: " + str(dirty_txes['avail'] / Decimal(1e8)) }
89+
return { "status": "NOT OK", "error": "Not enough funds, try again. Needed: " + str(fee_total_satoshi / Decimal(1e8)) + " but Have: " + str(dirty_txes['avail'] / Decimal(1e8)) }
9090

9191
total_amount = dirty_txes['avail']
9292
unspent_tx = dirty_txes['utxos']

api/send.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def prepare_send_tx_for_signing(from_address, to_address, marker_address, curren
156156
raise Exception({ "status": "NOT OK", "error": "Could not get list of unspent txs. Response Code: " + str(dirty_txes['code']) })
157157

158158
if (dirty_txes['error'][:3]=='Low'):
159-
raise Exception({ "status": "NOT OK", "error": "Not enough funds, for " + str(from_address) + ". Needed: " + str(fee_total_satoshi) + " but Have: " + str(dirty_txes['avail']) })
159+
raise Exception({ "status": "NOT OK", "error": "Not enough funds, for " + str(from_address) + ". Needed: " + str(fee_total_satoshi/Decimal(1e8)) + " but Have: " + str(dirty_txes['avail']/Decimal(1e8)) })
160160

161161
inputs_total_value = dirty_txes['avail']
162162
inputs = dirty_txes['utxos']

api/transaction_service.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ def dehexify(hex_str):
218218

219219
if txType not in [-22,21,25,26,27,28]: #Dex purchases don't have these fields
220220
ret['currencyId'] = txJson['propertyid']
221-
ret['currency_str'] = 'OMN' if txJson['propertyid'] == 1 else 'TOMN' if txJson['propertyid'] == 2 else "Smart Property"
221+
ret['currency_str'] = getName(txJson['propertyid'])
222222
ret['invalid'] = not txValid
223223
ret['amount'] = str(txJson['amount'])
224224
ret['formatted_amount'] = txJson['amount']
@@ -342,6 +342,19 @@ def dehexify(hex_str):
342342

343343
return json.dumps([ ret ] , sort_keys=True, indent=4) #only send back mapped schema
344344

345+
def getName(propertyid):
346+
if int(propertyid) == 1:
347+
name = 'Omni Token #1'
348+
elif int(propertyid) == 2:
349+
name = 'Test Omni Token #2'
350+
else:
351+
try:
352+
ROWS=dbSelect("select propertyname from smartproperties where protocol='Omni' and propertyid=%s",[int(propertyid)])
353+
name = ROWS[0][0]+" #"+str(propertyid)
354+
except:
355+
name = "#"+str(propertyid)
356+
return name
357+
345358
@app.route('/general/<page_id>')
346359
def getmostrecent(page_id):
347360
return 0

www/js/app.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ app.config(function($idleProvider, $keepaliveProvider, idleDuration, idleWarning
234234
})
235235
.run(function(Account, $location, TESTNET, BalanceSocket) {
236236
//Whitelist pages
237-
whitelisted = ['login', 'about', 'status', 'explorer', 'details', 'dex'];
237+
whitelisted = ['login', 'about', 'status', 'explorer', 'details', 'dex', 'exchange/trade'];
238238

239239
if (!Account.loggedIn) {
240240
for (var i = 0; i < whitelisted.length; i++) {

0 commit comments

Comments
 (0)