1.0.1 Token Swap Contract

This commit is contained in:
Vivek Teega 2021-11-19 15:26:51 +05:30
parent 339dac6a50
commit 1b27d0b31a
5 changed files with 646 additions and 955 deletions

3
app.py
View File

@ -4,7 +4,6 @@ from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@ -20,4 +19,4 @@ def marker_list():
return jsonify(dbdict)
app.run(debug=True)
app.run(debug=True)

View File

@ -5,6 +5,7 @@ Base = declarative_base()
ContractBase = declarative_base()
SystemBase = declarative_base()
LatestCacheBase = declarative_base()
ContinuosContractBase = declarative_base()
class ActiveTable(Base):
@ -222,3 +223,55 @@ class LatestBlocks(LatestCacheBase):
blockNumber = Column('blockNumber', String)
blockHash = Column('blockHash', String)
jsonData = Column('jsonData', String)
class ContractStructure1(ContinuosContractBase):
__tablename__ = "contractstructure"
id = Column('id', Integer, primary_key=True)
attribute = Column('attribute', String)
index = Column('index', Integer)
value = Column('value', String)
class ContractParticipants1(ContinuosContractBase):
__tablename__ = "contractparticipants"
id = Column('id', Integer, primary_key=True)
participantAddress = Column('participantAddress', String)
tokenAmount = Column('tokenAmount', Float)
userChoice = Column('userChoice', String)
transactionHash = Column('transactionHash', String)
blockNumber = Column('blockNumber', Integer)
blockHash = Column('blockHash', String)
winningAmount = Column('winningAmount', Float)
class ContractDeposits1(ContinuosContractBase):
__tablename__ = "contractdeposits"
id = Column('id', Integer, primary_key=True)
depositorAddress = Column('depositorAddress', String)
depositAmount = Column('depositAmount', Float)
expiryTime = Column('expiryTime', String)
transactionHash = Column('transactionHash', String)
blockNumber = Column('blockNumber', Integer)
blockHash = Column('blockHash', String)
class ContractTransactionHistory1(ContinuosContractBase):
__tablename__ = "contractTransactionHistory"
primary_key = Column('id', Integer, primary_key=True)
transactionType = Column('transactionType', String)
transactionSubType = Column('transactionSubType', String)
sourceFloAddress = Column('sourceFloAddress', String)
destFloAddress = Column('destFloAddress', String)
transferAmount = Column('transferAmount', Float)
blockNumber = Column('blockNumber', Integer)
blockHash = Column('blockHash', String)
time = Column('time', Integer)
transactionHash = Column('transactionHash', String)
blockchainReference = Column('blockchainReference', String)
jsonData = Column('jsonData', String)
parsedFloData = Column('parsedFloData', String)

View File

@ -1,7 +1,7 @@
import configparser
import re
import arrow
import pdb
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
@ -11,18 +11,20 @@ operation = None
address = None
amount = None
months = {'jan': 1,
'feb': 2,
'mar': 3,
'apr': 4,
'may': 5,
'jun': 6,
'jul': 7,
'aug': 8,
'sep': 9,
'oct': 10,
'nov': 11,
'dec': 12}
months = {
'jan': 1,
'feb': 2,
'mar': 3,
'apr': 4,
'may': 5,
'jun': 6,
'jul': 7,
'aug': 8,
'sep': 9,
'oct': 10,
'nov': 11,
'dec': 12
}
def isTransfer(text):
@ -34,6 +36,15 @@ def isTransfer(text):
return False
def isDeposit(text):
wordlist = ['submit', 'deposit'] # keep everything lowercase
textList = text.split(' ')
for word in wordlist:
if word in textList:
return True
return False
def isIncorp(text):
wordlist = ['incorporate', 'create', 'start'] # keep everything lowercase
textList = text.split(' ')
@ -63,7 +74,8 @@ def isSmartContractPay(text):
smartContractName = smartContractName[:-1]
if smartContractTrigger and smartContractName:
contractconditions = {'smartContractTrigger': smartContractTrigger, 'smartContractName': smartContractName}
contractconditions = {
'smartContractTrigger': smartContractTrigger, 'smartContractName': smartContractName}
return contractconditions
else:
return False
@ -88,6 +100,26 @@ def extractAmount(text, marker):
return returnval
def extractSubmitAmount(text, marker):
count = 0
returnval = None
text = text.split('deposit-conditions')[0]
splitText = text.split(' ')
for word in splitText:
word = word.replace(marker, '')
try:
float(word)
count = count + 1
returnval = float(word)
except ValueError:
continue
if count > 1:
return 'Too many'
return returnval
def extractMarker(text):
textList = text.split(' ')
for word in textList:
@ -139,7 +171,8 @@ def extractAddress(text):
def extractContractType(text):
operationList = ['one-time-event*'] # keep everything lowercase
# keep everything lowercase
operationList = ['one-time-event*', 'continuous-event*']
count = 0
returnval = None
for operation in operationList:
@ -163,7 +196,7 @@ def brackets_toNumber(item):
return float(item[1:-1])
def extractContractConditions(text, contracttype, marker, blocktime):
def extractContractConditions(text, contracttype, blocktime, marker=None):
rulestext = re.split('contract-conditions:\s*', text)[-1]
# rulelist = re.split('\d\.\s*', rulestext)
rulelist = []
@ -181,12 +214,12 @@ def extractContractConditions(text, contracttype, marker, blocktime):
break
for i in range(len(numberList)):
rule = rulestext.split('({})'.format(i + 1))[1].split('({})'.format(i + 2))[0]
rule = rulestext.split('({})'.format(
i + 1))[1].split('({})'.format(i + 2))[0]
rulelist.append(rule.strip())
if contracttype == 'one-time-event*':
extractedRules = {}
for rule in rulelist:
if rule == '':
continue
@ -195,9 +228,10 @@ def extractContractConditions(text, contracttype, marker, blocktime):
try:
expirytime_split = expirytime.split(' ')
parse_string = '{}/{}/{} {}'.format(expirytime_split[3], months[expirytime_split[1]],
expirytime_split[2], expirytime_split[4])
expirytime_object = arrow.get(parse_string, 'YYYY/M/D HH:mm:ss').replace(tzinfo=expirytime_split[5])
parse_string = '{}/{}/{} {}'.format(
expirytime_split[3], months[expirytime_split[1]], expirytime_split[2], expirytime_split[4])
expirytime_object = arrow.get(
parse_string, 'YYYY/M/D HH:mm:ss').replace(tzinfo=expirytime_split[5])
blocktime_object = arrow.get(blocktime)
if expirytime_object < blocktime_object:
print(
@ -231,7 +265,8 @@ def extractContractConditions(text, contracttype, marker, blocktime):
searchResult = pattern.search(rule).group(0)
minimumsubscriptionamount = searchResult.split(marker)[0]
try:
extractedRules['minimumsubscriptionamount'] = float(minimumsubscriptionamount)
extractedRules['minimumsubscriptionamount'] = float(
minimumsubscriptionamount)
except:
print("Minimum subscription amount entered is not a decimal")
elif rule[:25] == 'maximumsubscriptionamount':
@ -239,7 +274,8 @@ def extractContractConditions(text, contracttype, marker, blocktime):
searchResult = pattern.search(rule).group(0)
maximumsubscriptionamount = searchResult.split(marker)[0]
try:
extractedRules['maximumsubscriptionamount'] = float(maximumsubscriptionamount)
extractedRules['maximumsubscriptionamount'] = float(
maximumsubscriptionamount)
except:
print("Maximum subscription amount entered is not a decimal")
elif rule[:12] == 'payeeaddress':
@ -252,9 +288,114 @@ def extractContractConditions(text, contracttype, marker, blocktime):
return extractedRules
else:
return None
elif contracttype == 'continuous-event*':
extractedRules = {}
for rule in rulelist:
print(rule)
if rule == '':
continue
elif rule[:7] == 'subtype':
# todo : recheck the regular expression for subtype, find an elegant version which covers all permutations and combinations
'''pattern = re.compile('[^subtype\s*=].*')
searchResult = pattern.search(rule).group(0)
subtype = searchResult.split(marker)[0]'''
extractedRules['subtype'] = rule.split('=')[1].strip()
elif rule[:15] == 'accepting_token':
pattern = re.compile('[^accepting_token\s*=\s*].*')
searchResult = pattern.search(rule).group(0)
accepting_token = searchResult.split(marker)[0]
extractedRules['accepting_token'] = accepting_token
elif rule[:13] == 'selling_token':
pattern = re.compile('[^selling_token\s*=\s*].*')
searchResult = pattern.search(rule).group(0)
selling_token = searchResult.split(marker)[0]
extractedRules['selling_token'] = selling_token
elif rule[:9].lower() == 'pricetype':
pattern = re.compile('[^pricetype\s*=\s*].*')
searchResult = pattern.search(rule).group(0)
priceType = searchResult.split(marker)[0]
extractedRules['priceType'] = priceType
elif rule[:5] == 'price':
pattern = re.compile('[^price\s*=\s*].*')
searchResult = pattern.search(rule).group(0)
price = searchResult.split(marker)[0]
if price[0]=="'" or price[0]=='"':
price = price[1:]
if price[-1]=="'" or price[-1]=='"':
price = price[:-1]
extractedRules['price'] = float(price)
# else:
# pdb.set_trace()
if len(extractedRules) > 1:
return extractedRules
else:
return None
return None
def extractDepositConditions(text, blocktime):
rulestext = re.split('deposit-conditions:\s*', text)[-1]
# rulelist = re.split('\d\.\s*', rulestext)
rulelist = []
numberList = re.findall(r'\(\d\d*\)', rulestext)
for idx, item in enumerate(numberList):
numberList[idx] = int(item[1:-1])
numberList = sorted(numberList)
for idx, item in enumerate(numberList):
if len(numberList) > 1 and numberList[idx] + 1 != numberList[idx + 1]:
print('Deposit condition numbers are not in order')
return None
if idx == len(numberList) - 2:
break
for i in range(len(numberList)):
rule = rulestext.split('({})'.format(
i + 1))[1].split('({})'.format(i + 2))[0]
rulelist.append(rule.strip())
# elif contracttype == 'continuous-event*':
extractedRules = {}
for rule in rulelist:
if rule == '':
continue
elif rule[:10] == 'expirytime':
expirytime = re.split('expirytime[\s]*=[\s]*', rule)[1].strip()
try:
expirytime_split = expirytime.split(' ')
parse_string = '{}/{}/{} {}'.format(
expirytime_split[3], months[expirytime_split[1]], expirytime_split[2], expirytime_split[4])
expirytime_object = arrow.get(
parse_string, 'YYYY/M/D HH:mm:ss').replace(tzinfo=expirytime_split[5])
blocktime_object = arrow.get(blocktime)
if expirytime_object < blocktime_object:
print(
'Expirytime of the contract is earlier than the block it is incorporated in. This incorporation will be rejected ')
return None
extractedRules['expiryTime'] = expirytime
except:
print('Error parsing expiry time')
return None
"""for rule in rulelist:
if rule == '':
continue
elif rule[:7] == 'subtype':
subtype=rule[8:]
#pattern = re.compile('[^subtype\s*=\s*].*')
#searchResult = pattern.search(rule).group(0)
#contractamount = searchResult.split(marker)[0]
extractedRules['subtype'] = subtype """
if len(extractedRules) > 0:
return extractedRules
else:
return None
def extractTriggerCondition(text):
searchResult = re.search('\".*\"', text)
if searchResult is None:
@ -265,40 +406,69 @@ def extractTriggerCondition(text):
# Combine test
def parse_flodata(string, blockinfo, netvariable):
print("Break point at the first line of parsing function")
# todo Rule 20 - remove 'text:' from the start of flodata if it exists
if string[0:5] == 'text:':
string = string.split('text:')[1]
# todo Rule 21 - Collapse multiple spaces into a single space in the whole of flodata
# todo Rule 22 - convert flodata to lowercase to make the system case insensitive
nospacestring = re.sub(' +', ' ', string)
nospacestring = re.sub('\t', ' ', string)
nospacestring = re.sub('\n', ' ', nospacestring)
nospacestring = re.sub(' +', ' ', nospacestring)
cleanstring = nospacestring.lower()
#cleanstring_noconditions = cleanstring.split('contract-conditions:')[0]
cleanstring_split = re.compile("contract-conditions*[' ']:").split(cleanstring)
# todo Rule 23 - Count number of words ending with @ and #
atList = []
hashList = []
starList = []
for word in cleanstring.split(' '):
for word in cleanstring_split[0].split(' '):
if word.endswith('*') and len(word) != 1:
starList.append(word)
if word.endswith('@') and len(word) != 1:
atList.append(word)
if len(starList) != 1 or starList[0] not in ['one-time-event*', 'continuous-event*']:
parsed_data = {'type': 'noise'}
else:
if starList == 'one-time-event*':
for word in cleanstring_split[0].split(' '):
if word.endswith('#') and len(word) != 1:
hashList.append(word)
elif starList == 'continuous-event*':
for word in cleanstring_split[1].split(' '):
if word.endswith('#') and len(word) != 1:
hashList.append(word)
'''for word in cleanstring_noconditions.split(' '):
if word.endswith('@') and len(word) != 1:
atList.append(word)
if word.endswith('#') and len(word) != 1:
hashList.append(word)
if word.endswith('*') and len(word) != 1:
starList.append(word)
'''
print('')
# todo Rule 24 - Reject the following conditions - a. number of # & number of @ is equal to 0 then reject
# todo Rule 25 - If number of # or number of @ is greater than 1, reject
# todo Rule 25.a - If a transaction is rejected, it means parsed_data type is noise
# Filter noise first - check if the words end with either @ or #
if (len(atList) == 0 and len(hashList) == 0) or len(atList) > 1 or len(hashList) > 1:
if (len(atList) == 0 and len(hashList) == 0) or len(atList) > 1 or len(hashList) > 2 or len(starList) > 1:
parsed_data = {'type': 'noise'}
# todo Rule 26 - if number of # is 1 and number of @ is 0, then check if its token creation or token transfer transaction
elif len(hashList) == 1 and len(atList) == 0:
# todo Rule 26 - if number of # is 1 and numbner of @ is 0 and number of * is 0, then check if its token creation or token transfer transaction
elif len(hashList) == 1 and len(atList) == 0 and len(starList) == 0:
# Passing the above check means token creation or transfer
incorporation = isIncorp(cleanstring)
transfer = isTransfer(cleanstring)
# todo Rule 27 - if (neither token incorporation and token transfer) OR both token incorporation and token transfer, reject
# todo Rule 27 - if (neither token incorporation a
if (not incorporation and not transfer) or (incorporation and transfer):
parsed_data = {'type': 'noise'}
@ -316,29 +486,35 @@ def parse_flodata(string, blockinfo, netvariable):
# todo Rule 31 - Extract number of tokens to be sent and the address to which to be sent, both data is mandatory
elif not incorporation and transfer:
amount = extractAmount(cleanstring, hashList[0][:-1])
if None not in [amount] and amount!='Too many':
if None not in [amount]:
parsed_data = {'type': 'transfer', 'transferType': 'token', 'flodata': string,
'tokenIdentification': hashList[0][:-1],
'tokenAmount': amount}
else:
parsed_data = {'type': 'noise'}
# todo Rule 32 - if number of # is 1 and number of @ is 1, then process for smart contract transfer or creation
elif len(hashList) == 1 and len(atList) == 1:
# todo Rule 32 - if number of @ is 1, then process for smart contract transfer or creation or trigger
elif len(atList) == 1:
# Passing the above check means Smart Contract creation or transfer
incorporation = isIncorp(cleanstring)
transfer = isTransfer(cleanstring)
deposit = isDeposit(cleanstring)
# todo Rule 33 - if a confusing smart contract command is given, like creating and sending at the same time, or no
if (not incorporation and not transfer) or (incorporation and transfer):
if incorporation and transfer:
parsed_data = {'type': 'noise'}
# todo Rule 34 - if incorporation and not transfer, then extract type of contract, address of the contract and conditions of the contract. Reject if any of those is not present
elif incorporation and not transfer:
contracttype = extractContractType(cleanstring)
contractaddress = extractAddress(nospacestring)
contractconditions = extractContractConditions(cleanstring, contracttype, marker=hashList[0][:-1],
blocktime=blockinfo['time'])
if contracttype == 'one-time-event*' and len(hashList) == 1:
contractconditions = extractContractConditions(cleanstring, contracttype, blocktime=blockinfo['time'], marker=hashList[0][:-1])
elif contracttype == 'continuous-event*':
contractconditions = extractContractConditions(cleanstring, contracttype, blocktime=blockinfo['time'])
else:
parsed_data = {'type': 'noise'}
return parsed_data
if config['DEFAULT']['NET'] == 'mainnet' and blockinfo['height'] < 3454510:
if None not in [contracttype, contractconditions]:
@ -349,16 +525,29 @@ def parse_flodata(string, blockinfo, netvariable):
else:
parsed_data = {'type': 'noise'}
else:
if None not in [contracttype, contractaddress, contractconditions]:
if None not in [contracttype, contractaddress, contractconditions] and contracttype[:-1] == 'one-time-event':
parsed_data = {'type': 'smartContractIncorporation', 'contractType': contracttype[:-1],
'tokenIdentification': hashList[0][:-1], 'contractName': atList[0][:-1],
'contractAddress': contractaddress[:-1], 'flodata': string,
'contractConditions': contractconditions}
elif None not in [contracttype, contractaddress, contractconditions] and contracttype[:-1] == 'continuous-event':
if contractconditions['subtype'] == 'tokenswap' and ('priceType' not in contractconditions):
parsed_data = {'type': 'noise'}
return parsed_data
else:
parsed_data = {'type': 'smartContractIncorporation', 'contractType': contracttype[:-1], 'contractName': atList[0][:-1],
'contractAddress': contractaddress[:-1], 'flodata': string,
'contractConditions': contractconditions}
else:
parsed_data = {'type': 'noise'}
# todo Rule 35 - if it is not incorporation and it is transfer, then extract smart contract amount to be locked and userPreference. If any of them is missing, then reject
elif not incorporation and transfer:
# todo - Temporary check for transaction 22196cc761043b96a06fcfe5e58af2dafb90c7d222dcb909b537f7ee6715f0bd on testnet , figure out an elegant way of doing this
if len(hashList) == 0:
parsed_data = {'type': 'noise'}
return parsed_data
# We are at the send/transfer of smart contract
amount = extractAmount(cleanstring, hashList[0][:-1])
userChoice = extractUserchoice(cleanstring)
@ -373,18 +562,34 @@ def parse_flodata(string, blockinfo, netvariable):
else:
parsed_data = {'type': 'noise'}
elif deposit:
# Figure out amount of token to be submitted
for word in cleanstring_split[0].split(' '):
if word.endswith('#') and len(word) != 1:
hashList.append(word)
depositAmount = extractSubmitAmount(cleanstring_split[0], hashList[0][:-1])
# '' name of token = hashList[0]
# '' name of Smart Contract = atList[0]
# '' FLO address of the Smart Contract
# '' Submit conditions
deposit_conditions = extractDepositConditions(cleanstring, blocktime=blockinfo['time'])
if None not in [deposit_conditions]:
parsed_data = {'type': 'smartContractDeposit',
'tokenIdentification': hashList[0][:-1], 'depositAmount': depositAmount, 'contractName': atList[0][:-1], 'flodata': string,
'depositConditions': deposit_conditions}
else:
parsed_data = {'type': 'noise'}
# todo Rule 36 - Check for only a single @ and the substring "smart contract system says" in flodata, else reject
elif (len(hashList) == 0 and len(atList) == 1):
# Passing the above check means Smart Contract pays | exitcondition triggered from the committee
# todo Rule 37 - Extract the trigger condition given by the committee. If its missing, reject
triggerCondition = extractTriggerCondition(cleanstring)
if triggerCondition is not None:
parsed_data = {'type': 'smartContractPays', 'contractName': atList[0][:-1],
'triggerCondition': triggerCondition.group().strip()[1:-1]}
# If flodata doesn't indicate incorporation nor transfer, check if its a committee trigger
elif (not incorporation and not transfer):
# Passing the above check means Smart Contract pays | exitcondition triggered from the committee
# todo Rule 37 - Extract the trigger condition given by the committee. If its missing, reject
triggerCondition = extractTriggerCondition(cleanstring)
if triggerCondition is not None:
parsed_data = {'type': 'smartContractPays', 'contractName': atList[0][:-1], 'triggerCondition': triggerCondition.group().strip()[1:-1]}
else:
parsed_data = {'type': 'noise'}
else:
parsed_data = {'type': 'noise'}
else:
parsed_data = {'type': 'noise'}
return parsed_data
return parsed_data

View File

@ -2,14 +2,15 @@ arrow==1.1.0
bidict==0.21.2
certifi==2021.5.30
cffi==1.14.5
requests==2.25.0
chardet
chardet==4.0.0
greenlet==1.1.0
idna==2.10
pybtc==2.0.9
pycparser==2.20
python-dateutil==2.8.1
python-engineio==3.14.2
python-socketio==4.6.1
requests==2.25.0
secp256k1==0.13.2
six==1.16.0
SQLAlchemy==1.4.18

File diff suppressed because it is too large Load Diff