def get_user(ecosys_key, key): cleos = Cleos(url='https://chain.wax.io') ecosystems = cleos.get_table(code=CONTRACT_ACCOUNT, scope=CONTRACT_SCOPE, table=ECOSYSTEMS_TABLE, lower_bound=ecosys_key, upper_bound=ecosys_key, limit=1, timeout=30) ecosystem = ecosystems.get('rows', [])[0] user = ecosystem.get('users')[int(key)] # Get all of this User's granted Achievements achievements = [] grants_categories = user.bycategory for (category_id, achievements_list) in grants_categories.iteritems(): userachievements = achievements_list.userachievements for userachievement in userachievements: achievements.append((ecosystem.get('categories')[category_id].get( 'achievements')[userachievement.get('achievement_id')], userachievement.get('timestamp'))) return render_template('user.html', ecosystem=ecosystem, achievements=achievements)
def index(): cleos = Cleos(url='https://chain.wax.io') ecosystems = cleos.get_table(code=CONTRACT_ACCOUNT, scope=CONTRACT_SCOPE, table=ECOSYSTEMS_TABLE, limit=100, timeout=30) return render_template('index.html', ecosystems=ecosystems.get('rows', []))
def get_ecosystem(): cleos = Cleos(url=settings.WAX_URL) ecosystems = cleos.get_table(code=settings.WAX_CONTRACT, scope=settings.WAX_CONTRACT, table='ecosystems', lower_bound=settings.WAXBADGES_ECOSYSTEM_ID, upper_bound=settings.WAXBADGES_ECOSYSTEM_ID, limit=1, timeout=30) return ecosystems.get('rows', [])[0]
def get_ecosystem(key): cleos = Cleos(url='https://chain.wax.io') ecosystems = cleos.get_table(code=CONTRACT_ACCOUNT, scope=CONTRACT_SCOPE, table=ECOSYSTEMS_TABLE, lower_bound=key, upper_bound=key, limit=1, timeout=30) ecosystem = ecosystems.get('rows', [])[0] print(ecosystem) return render_template('ecosys.html', ecosystem=ecosystem)
def find_user(ecosys_key, userid): cleos = Cleos(url='https://chain.wax.io') ecosystems = cleos.get_table(code=CONTRACT_ACCOUNT, scope=CONTRACT_SCOPE, table=ECOSYSTEMS_TABLE, lower_bound=ecosys_key, upper_bound=ecosys_key, limit=1, timeout=30) ecosystem = ecosystems.get('rows', [])[0] for (key, user) in enumerate(ecosystem.users): if user.userid == userid: return key return None
def get_achievement(ecosys_key, cat_key, key): cleos = Cleos(url='https://chain.wax.io') ecosystems = cleos.get_table(code=CONTRACT_ACCOUNT, scope=CONTRACT_SCOPE, table=ECOSYSTEMS_TABLE, lower_bound=ecosys_key, upper_bound=ecosys_key, limit=1, timeout=30) ecosystem = ecosystems.get('rows', [])[0] achievement = ecosystem.get('categories')[int(cat_key)].get( 'achievements')[int(key)] achievement['key'] = int(key) if achievement['maxquantity'] == 0: achievement['num_available'] = 'unlimited' achievement['maxquantity'] = 'unlimited' else: achievement['num_available'] = achievement['maxquantity'] - len( achievement.get('usergrants', [])) users = [] for usergrant in achievement.get('usergrants'): user = ecosystem.get('users')[usergrant.get('user_id')] if not user.get('avatarurl').startswith('http'): user['avatarurl'] = ecosystem.get('baseasseturl') + "/" + user.get( 'avatarurl') user['user_id'] = usergrant.get('user_id') print(user) users.append({ "user": user, "timestamp": datetime.utcfromtimestamp(usergrant.get('timestamp')), }) return render_template('ach.html', ecosystem=ecosystem, category_id=cat_key, achievement=achievement, usergrants=users)
def get_proofofachievement(ecosys_key, cat_key, ach_key, user_key): cleos = Cleos(url='https://chain.wax.io') ecosystems = cleos.get_table(code=CONTRACT_ACCOUNT, scope=CONTRACT_SCOPE, table=ECOSYSTEMS_TABLE, lower_bound=ecosys_key, upper_bound=ecosys_key, limit=1, timeout=30) ecosystem = ecosystems.get('rows', [])[0] achievement = ecosystem.get('categories')[int(cat_key)].get( 'achievements')[int(ach_key)] achievement['key'] = int(ach_key) if achievement['maxquantity'] == 0: achievement['maxquantity'] = 'unlimited' user = ecosystem.get('users')[int(user_key)] user['key'] = int(user_key) if not user.get('avatarurl').startswith('http'): user['avatarurl'] = ecosystem.get('baseasseturl') + "/" + user.get( 'avatarurl') for userachievement in user.get('userachievements'): if userachievement.get('category_id') == int( cat_key) and userachievement.get('achievement_id') == int( ach_key): timestamp = datetime.utcfromtimestamp( userachievement.get('timestamp')) break return render_template('poa.html', ecosystem=ecosystem, category_id=cat_key, achievement=achievement, user=user, timestamp=timestamp)
labels = nx.draw_networkx_labels(G, pos, node_labels) plt.show(figure) def tonodes(table): nodes = {} for entry in table['rows']: next_node = Node(entry) nodes[entry['identity']] = next_node if len(nodes) == 0: logger.info('table is empty, check your eosurl is correct.') return return nodes if __name__ == "__main__": args = parser.parse_args() cleos = Cleos(url=args.eosurl) if args.command == "info": logger.info(cleos.get_info()) elif args.command == "print": cleos.get_info() table = cleos.get_table('bittensoracc', 'bittensoracc', 'metagraph') logger.info(tonodes(table)) elif args.command == "table": cleos.get_info() table = cleos.get_table('bittensoracc', 'bittensoracc', 'metagraph') nodes = tonodes(table) _make_plot_table(nodes) else: logger.info('Command not found.')
class EosNetwork: def __init__(self, endpoint): self.endpoint = endpoint self.cleos = Cleos(url=endpoint) def deploy_contract(self, contract_info, account_info): setcode_action = self.create_setcode_action(contract_info['code_file'], account_info['name']) setabi_action = self.create_setabi_action(contract_info['abi_file'], account_info['name']) transaction = {'actions': [setcode_action, setabi_action]} key = EOSKey(account_info['private_key']) tx_result = self.cleos.push_transaction(transaction, key) return tx_result def create_setcode_action(self, code_file, account_name): file_handle = open(code_file, 'rb') file_data = file_handle.read() hex_data = hexlify(file_data) arguments = { 'account': account_name, 'code': hex_data.decode('utf-8'), 'vmtype': 0, 'vmversion': 0 } payload = { 'account': 'eosio', 'name': 'setcode', 'authorization': [{ 'actor': account_name, 'permission': 'active' }] } # Converting payload to binary data. data = self.cleos.abi_json_to_bin(payload['account'], payload['name'], arguments) # Inserting payload binary form as 'data' field in original payload. payload['data'] = data['binargs'] return payload def create_setabi_action(self, abi_file, account_name): file_handle = open(abi_file) file_data = json.load(file_handle) abi_data = Abi(file_data) arguments = {'account': account_name, 'abi': abi_data.get_raw()} payload = { 'account': 'eosio', 'name': 'setabi', 'authorization': [{ 'actor': account_name, 'permission': 'active' }] } # Converting payload to binary data. data = self.cleos.abi_json_to_bin(payload['account'], payload['name'], arguments) # Inserting payload binary form as 'data' field in original payload. payload['data'] = data['binargs'] return payload def read_data(self, code, scope, table_name): return self.cleos.get_table(code, scope, table_name) def write_data(self, contract_name, action_name, account_name, private_key, params): payload = { 'account': contract_name, 'name': action_name, 'authorization': [{ 'actor': account_name, 'permission': 'active' }] } print(params) data = self.cleos.abi_json_to_bin(payload['account'], payload['name'], params) payload['data'] = data['binargs'] print(payload) transaction = {'actions': [payload]} key = EOSKey(private_key) tx_result = self.cleos.push_transaction(transaction, key) return tx_result
class Metagraph(): def __init__(self, config): self.config = config self.cleos = Cleos(url=config.eosurl) self.nodes = {} self.pull_metagraph() self.attributions = [(config.identity, 1.0)] # TODO(shibshib) this should be our own key. NOT EOSMAIN. self.eoskey = "5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3" def get_my_stake(self): return int(self.nodes[self.config.identity].stake) # TODO(shibshib): pull this from the eos chain under the var 'total stake' # instead of doing a sum. def get_total_stake(self): return int(sum([node.stake for node in self.nodes.values()])) def pull_metagraph(self): table = self.cleos.get_table('bittensoracc', 'bittensoracc', 'metagraph') for entry in table['rows']: next_node = Node(entry) self.nodes[entry['identity']] = next_node logger.debug(self.__str__()) # Push attribution scores. def publish_attributions(self): logger.debug('Publish attributions: ' + str(self.attributions)) transaction = self.publish_attributions_trx() try: #import pdb #pdb.set_trace() # TODO (shibshib) Rewrite the cleos library for our selves. resp = self.cleos.push_transaction(transaction, self.eoskey, broadcast=True) except: try: eoskey = eospy.keys.EOSKey(self.eoskey) resp = self.cleos.push_transaction(transaction, eoskey, broadcast=True) except Exception as e: logger.error('Failed to publish transaction "{}"'.format(e)) def publish_attributions_trx(self): arguments = { "this_user": self.config.identity, "this_edges": [(attr[0], float(attr[1])) for attr in self.attributions], } payload = { "account": "bittensoracc", "name": "emit", "authorization": [{ "actor": self.config.identity, "permission": "active", }], } #Converting payload to binary data = self.cleos.abi_json_to_bin(payload['account'], payload['name'], arguments) #Inserting payload binary form as "data" field in original payload payload['data'] = data['binargs'] #final transaction formed trx = {"actions": [payload]} return trx def __repr__(self): return self.__str__() def __str__(self): str_rep = "\nmetagraph = {\n" for node in self.nodes.values(): str_rep += ("\t" + str(node) + "\n") str_rep += "}." return str_rep
def jsoninfo(): logger = reactive_log('json') url_index = test_net_is_working(BOS_URLS) logger.info('BOS Node [' + str(url_index) + '] is working:' + BOS_URLS[url_index]) ce = Cleos(url=BOS_URLS[url_index]) BP_TOTAL_VOTES = float( int( ce.get_table('eosio', 'eosio', 'global')['rows'][0]['total_activated_stake']) / 10000) print(BP_TOTAL_VOTES) # try: # get tally json file proposals = {} try: rawtext = urlopen(TALLY_API, timeout=15).read() proposals = json.loads(rawtext.decode('utf8')) except Exception as err: logger.error(err) # get Voted Total # page = requests.get(BOS_TEST_NET_EX) # try: # page = requests.get(BOS_NET_EX) # tree = etree.HTML(page.content.lower().decode('utf-8')) # vote_total_from_web = tree.xpath(EOSX_VOTE_TOTAL_XPATH) # logger.info(str(vote_total_from_web)) # except Exception as err: # logger.error(err) #iterater the current proposals for proposal in proposals: proposal_item = proposals[proposal] vote_key = proposal_item['stats']['votes'] vote_total = proposal_item['stats']['votes'][ 'total'] if 'total' in vote_key else 0 vote_yes = proposal_item['stats']['votes'][ '1'] if '1' in vote_key else 0 vote_no = proposal_item['stats']['votes']['0'] if '0' in vote_key else 0 _meet_conditions_days = 0 _approved_by_vote = 0 _approved_by_vote_date = None _approved_by_BET = 0 _reviewed_by_BET_date = None _approved_by_BPs = 0 _approved_by_BPs_date = None # check if the proposal exists try: propos = Proposal.select().where(Proposal.name == proposal).count() logger.info("result" + str(propos)) # the proposal exists if propos > 0: # check if the proposal is passed if proposal_base_condition_ckeck(BP_TOTAL_VOTES, vote_total, vote_yes, vote_no): propos = Proposal.get(Proposal.name == proposal) meet = propos.meet_conditions_days # abv = propos.approved_by_vote abvd = propos.approved_by_vote_date _approved_by_vote = 1 if int(meet) >= 20 else 0 _approved_by_vote_date = datetime.now( ) if abvd == None else abvd # if meet >= 0 and abv != False and abvd != None: nrow = ( Proposal.update( json_info=proposal_item, vote_total=vote_total, vote_yes=vote_yes, vote_no=vote_no, meet_conditions_days=int(meet) + 1, approved_by_vote=_approved_by_vote, approved_by_vote_date=_approved_by_vote_date # , approved_by_BET = _approved_by_BET # , reviewed_by_BET_date = _reviewed_by_BET_date # , approved_by_BPs = _approved_by_BPs # , approved_by_BPs_date = _approved_by_BPs_date ).where(Proposal.name == proposal).execute()) else: nrow = ( Proposal.update( json_info=proposal_item, vote_total=vote_total, vote_yes=vote_yes, vote_no=vote_no, meet_conditions_days=0, approved_by_vote=0, approved_by_vote_date=None # , approved_by_BET = _approved_by_BET # , reviewed_by_BET_date = _reviewed_by_BET_date # , approved_by_BPs = _approved_by_BPs # , approved_by_BPs_date = _approved_by_BPs_date ).where(Proposal.name == proposal).execute()) else: if proposal_base_condition_ckeck(BP_TOTAL_VOTES, vote_total, vote_yes, vote_no): _approved_by_vote = 1 _approved_by_vote_date = datetime.now() else: pass new_proposal = Proposal( name=proposal, json_info=proposal_item, vote_total=vote_total, vote_yes=vote_yes, vote_no=vote_no, meet_conditions_days=_meet_conditions_days, approved_by_vote=_approved_by_vote, approved_by_vote_date=_approved_by_vote_date, approved_by_BET=_approved_by_BET, reviewed_by_BET_date=_reviewed_by_BET_date, approved_by_BPs=_approved_by_BPs, approved_by_BPs_date=_approved_by_BPs_date) new_proposal.save() except Exception as err: logger.error(err) logger.info("proposal name: " + proposal) logger.info("vote total: " + str(vote_total)) logger.info("vote yes: " + str(vote_yes)) logger.info("vote no: " + str(vote_no)) logger.info("___________________") resp = flask.Response(proposals) resp.headers['Access-Control-Allow-Origin'] = '*' return resp