def call(name: str) -> SmartContract: # Create keypair for the contract owner provider1 = Entity() address1 = Address(provider1) # Setting API up api = LedgerApi('185.91.52.11', 10002) # Need funds to deploy contract api.sync(api.tokens.wealth(provider1, 59000000)) with open(name, "r") as fb: source = fb.read() # Create contract contract = SmartContract(source) # Deploy contract api.sync(api.contracts.create(provider1, contract, 2456766)) print("Wait for txs to be mined ...") time.sleep(5) # Printing balance of the creating address1 print(contract.query(api, 'getAccountRides', acc_id="1"))
def main(): print('Loading private key...') # load up the previously created private key with open('private.key', 'r') as private_key_file: entity1 = Entity.load(private_key_file) print('Loading private key...complete') # build the ledger API api = LedgerApi('127.0.0.1', 8000) # create the smart contract contract = SmartContract(CONTRACT_TEXT) print('Deploying contract...') # deploy the contract to the network api.sync(api.contracts.create(entity1, contract, 2000)) print('Deploying contract...complete') # save the contract to the disk with open('sample.contract', 'w') as contract_file: contract.dump(contract_file)
def main(): # create our first private key pair entity1 = Entity() address1 = Address(entity1) # create a second private key pair entity2 = Entity() address2 = Address(entity2) # build the ledger API api = LedgerApi('127.0.0.1', 8100) # create wealth so that we have the funds to be able to create contracts on the network api.sync(api.tokens.wealth(entity1, 10000)) # create the smart contract contract = SmartContract(CONTRACT_TEXT) # deploy the contract to the network api.sync(api.contracts.create(entity1, contract, 2000)) # print the current status of all the tokens print('-- BEFORE --') print_address_balances(api, contract, [address1, address2]) # transfer from one to the other using our newly deployed contract tok_transfer_amount = 200 fet_tx_fee = 40 api.sync( contract.action(api, 'transfer', fet_tx_fee, [entity1], address1, address2, tok_transfer_amount)) print('-- BEFORE --') print_address_balances(api, contract, [address1, address2])
def prepare_contract(self, price): # Setting API up self._api = LedgerApi('127.0.0.1', 8100) self.scheduler = {} self.price = price self.rate = 22 self.max_count = 10 # Need funds to deploy contract self._api.sync(self._api.tokens.wealth(self._entity, 5000000)) # Create contract self._contract = SmartContract(self._source) # Deploy contract self._api.sync( self._api.contracts.create(self._entity, self._contract, 2456766)) self.chargers = [ Entity(), ] self._contract.action(self._api, 'addCharger', 2456766, [self._entity], Address(self.chargers[0]), int(self.latitude * 1000), int(self.longitude * 1000), self.price, self.rate, self.max_count)
def prepare_contract(self, price): # Setting API up self._api = LedgerApi('127.0.0.1', 8100) self.longitude = 10 self.latitude = 10 self.scheduler = {} self.price = price self.rate = 22 self.max_count = 10 # Need funds to deploy contract self._api.sync(self._api.tokens.wealth(self._entity, 5000000)) # Create contract self._contract = SmartContract(self._source) # Deploy contract self._api.sync( self._api.contracts.create(self._entity, self._contract, 2456766)) self.chargers = [ Entity(), ] #self._contract.action(self._api, 'test', 2456755, [self._entity], Address(self.chargers[0]), Address(self.chargers[0])) self._contract.action(self._api, 'addCharger', 2456766, [self._entity], Address(self.chargers[0]), self.longitude, self.latitude, self.price, self.rate, self.max_count) scooter = Entity() scooter_start_time = 150000 scooter_end_time = 151000 tx_digest = self._contract.action(self._api, 'book', 2456766, [self._entity], Address(self.chargers[0]), Address(scooter), scooter_start_time, scooter_end_time) time.sleep(3) tx_status = self._api.tx.status(tx_digest) if tx_status == "Executed": self.scheduler[str( Address(scooter))] = [scooter_start_time, scooter_end_time] query = self._contract.query(api=self._api, name='getSlotInfo', charger=Address(self.chargers[0])) print(query)
def test_dumps_and_loads_without_owner(self): # create the contract orig = SmartContract(CONTRACT_TEXT) # encode the contract encoded = orig.dumps() # re-create the contract new = SmartContract.loads(encoded) # checks self.assertIsInstance(new, SmartContract) self.assertEqual(orig.owner, new.owner) self.assertEqual(orig.digest, new.digest) self.assertEqual(orig.source, new.source)
def print_address_balances(api: LedgerApi, contract: SmartContract, addresses: List[Address]): for idx, address in enumerate(addresses): print('Address{}: {:<6d} bFET {:<10d} TOK'.format( idx, api.tokens.balance(address), contract.query(api, 'balance', address=address))) print()
def main(): # load up the previously created private key with open('private.key', 'r') as private_key_file: entity1 = Entity.load(private_key_file) # load up the deployed contract with open('sample.contract', 'r') as contract_file: contract = SmartContract.load(contract_file) # for the purposes of this example create a second private key pair to transfer funds to entity2 = Entity() # build the ledger API api = LedgerApi('127.0.0.1', 8000) # print the current status of all the tokens print('-- BEFORE --') print_address_balances(api, contract, [entity1, entity2]) # transfer from one to the other using our newly deployed contract tok_transfer_amount = 200 fet_tx_fee = 40 api.sync( contract.action(api, 'transfer', fet_tx_fee, [entity1], Address(entity1), Address(entity2), tok_transfer_amount)) print('-- AFTER --') print_address_balances(api, contract, [entity1, entity2])
def main(source, name): # Create keypair for the contract owner provider1 = Entity() address1 = Address(provider1) provider2 = Entity() address2 = Address(provider2) scooter1 = Entity() scooter_address1 = Address(scooter1) # Setting API up api = LedgerApi('127.0.0.1', 8100) # Need funds to deploy contract api.sync(api.tokens.wealth(provider1, 59000000)) # Create contract contract = SmartContract(source) # Deploy contract api.sync(api.contracts.create(provider1, contract, 2456766)) if name.endswith("contract.etch"): contract.action(api, 'addProvider', 2456766, [provider2, provider1], address2, address1) contract.action(api, 'addScooter', 2456766, [provider2, provider1], address2, address1, 22, 1) print("Wait for txs to be mined ...") time.sleep(5) # Printing balance of the creating address1 print(contract.query(api, 'getFleetSize'), " scooter in fleet")
def main(source): # Create keypair for the contract owner entity = Entity() address = Address(entity) # Setting API up api = LedgerApi('127.0.0.1', 8100) # Need funds to deploy contract api.sync(api.tokens.wealth(entity, 5000000)) # Create contract contract = SmartContract(source) # Deploy contract api.sync(api.contracts.create(entity, contract, 2456766)) # Printing balance of the creating address print(contract.query(api, 'balanceOf', owner=address)) # Getting the 9'th token id. token_id = contract.query(api, 'getTokenId', number=9) # Testing contract.query(api, 'isEqual', number=9, expected=token_id) # Locating the owner of a token print("Finding the owner of ", token_id) print(contract.query(api, 'ownerOf', token_id=token_id))
def run(options): entity1 = Entity() # build the ledger API api = LedgerApi(options['host'], options['port']) # create wealth so that we have the funds to be able to create contracts on the network api.sync(api.tokens.wealth(entity1, 100000)) # create the smart contract contract = SmartContract(CONTRACT_TEXT) # deploy the contract to the network api.sync(api.contracts.create(entity1, contract, 2000)) api.sync(contract.action(api, 'set_block_number_state', 400, [entity1])) assert contract.query(api, 'query_block_number_state') > 0
def main(source): # Create keypair for the contract owner entity = Entity() address = Address(entity) # Setting API up api = LedgerApi('127.0.0.1', 8100) # Need funds to deploy contract api.sync(api.tokens.wealth(entity, 1000000)) # Create contract contract = SmartContract(source) # Deploy contract api.sync(api.contracts.create(entity, contract, 20000)) # Printing message print(contract.query(api, 'totalSupply'))
def prepare_contract(self): # Setting API up self._api = LedgerApi('185.91.52.11', 10002) # Need funds to deploy contract self._api.sync(self._api.tokens.wealth(self._entity, 5000000)) # Create contract self._contract = SmartContract(self._source) # Deploy contract self._api.sync(self._api.contracts.create(self._entity, self._contract, 2456766))
def __init__(self, *args, start=(30.28, 59.91), finish=(30.34, 59.97), n_points=3, charge=0.6, **kwargs): super(ScooterAgent, self).__init__(*args, **kwargs) self._api = LedgerApi('127.0.0.1', 8100) self._entity = Entity() self.speed = 0.0005 self._api.sync(self._api.tokens.wealth(self._entity, 5000000)) self._address = Address(self._entity) with open("../02_full_contract.etch", "r") as fb: self._source = fb.read() # Create contract self._contract = SmartContract(self._source) # Deploy contract self._api.sync(self._api.contracts.create(self._entity, self._contract, 2456766)) with open('contract.txt','r') as ff: self.digest = ff.readline().split('\n')[0] self.owner = ff.readline() self._loop = asyncio.get_event_loop() self.provider = Entity() self.scooter = Entity() self.path = make_path(start, finish, n_points, 0.01) self.charge = charge self._contract.action(self._api, 'addProvider', 2456, [self._entity, self.provider], Address(self.provider), self._address) self._contract.action(self._api, 'addScooter', 2456, [self.provider], Address(self.scooter), Address(self.provider), int(start[1]*1000), int(start[0]*1000), 100, 1, 15)
def submit_contract(): if request.method != 'POST': return json.dumps({"status": "only POST requests are accepted"}) source = request.form['source'] name = request.form['name'] gas = request.form['gas'] contract = SmartContract(source) contracts[name] = contract api.sync(api.contracts.create(entity, contract, gas)) return json.dumps({"status": "done"})
def __init__(self, *args, n_providers=3, scooter_per_provider=5, **kwargs): super(ScooterAgent, self).__init__(*args, **kwargs) self._api = LedgerApi('127.0.0.1', 8100) self._entity = Entity() self._api.sync(self._api.tokens.wealth(self._entity, 5000000)) self._address = Address(self._entity) with open("../02_full_contract.etch", "r") as fb: self._source = fb.read() # Create contract self._contract = SmartContract(self._source) # Deploy contract self._api.sync( self._api.contracts.create(self._entity, self._contract, 2456766)) self._loop = asyncio.get_event_loop() self.providers = [] self.scooters = [] for i in range(n_providers): self.providers.append(Entity()) scooters = [Entity() for j in range(scooter_per_provider)] self.scooters.extend(scooters) self._contract.action(self._api, 'addProvider', 2456766, [self._entity, self.providers[0]], Address(self.providers[0]), self._address) self._contract.action(self._api, 'addScooter', 2456766, [self.providers[0]], Address(self.scooters[0]), Address(self.providers[0]), 22, 23, 100, 1, 15) print(Address(self.scooters[0]))
def main(source): # Create keypair for the contract owner entity = Entity() address = Address(entity) # Setting API up api = LedgerApi('localhost', 8000) # Need funds to deploy contract api.sync(api.tokens.wealth(entity, 100000)) # Create contract contract = SmartContract(source) # Deploy contract api.sync(api.contracts.create(entity, contract, 100000)) # Printing message contract.action(api, 'add', 100, [entity], "first") time.sleep(5) print(contract.query(api, 'getSize'))
def main(source): # Create keypair for the contract owner entity = Entity() address = Address(entity) # Setting API up api = LedgerApi('10.168.172.59', 8000) # Need funds to deploy contract api.sync(api.tokens.wealth(entity, 100000)) # Create contract contract = SmartContract(source) # Deploy contract api.sync(api.contracts.create(entity, contract, 10000)) # Printing message print( contract.query(api, 'register', owner='artyom', scooter='bike1', price='100'))
def prepare_contract(self): # Setting API up self._api = LedgerApi('127.0.0.1', 8100) # Need funds to deploy contract self._api.sync(self._api.tokens.wealth(self._entity, 5000000)) # Create contract self._contract = SmartContract(self._source) # Deploy contract self._api.sync( self._api.contracts.create(self._entity, self._contract, 2456766)) ff = open('contract.txt', 'w') ff.write(str(self._contract._digest) + "\n") ff.write(str(Address(self._entity))) ff.close()
def main(): # create our first private key pair entity1 = Entity() # build the ledger API api = LedgerApi('127.0.0.1', 8100) # create wealth so that we have the funds to be able to create contracts on the network api.sync(api.tokens.wealth(entity1, 1000000000000000)) # create the smart contract contract = SmartContract(CONTRACT_TEXT) # deploy the contract to the network api.sync(api.contracts.create(entity1, contract, 1000000000)) # update the graph with a new model fet_tx_fee = 100000000 with open(GRAPH_FILE_NAME, mode='rb') as file: print("reading in graph file...") rfile = file.read() print("encoding to base64 string...") b64obj = base64.b64encode(rfile) obj = b64obj.decode() print("updating smart contract graph...") api.sync( contract.action(api, 'updateGraph', fet_tx_fee, [entity1], obj)) print("finished updating smart contract graph") # set one real example input data set fet_tx_fee = 100000000 api.sync( contract.action(api, 'setHistorics', fet_tx_fee, [entity1], EXAMPLE_INPUT_HISTORICS)) current_historics = contract.query(api, 'getHistorics') print("current historics: " + current_historics) # make a prediction current_prediction = contract.query(api, 'makePrediction') print("current prediction: " + current_prediction)
class ScooterAgent(OEFAgent): """Class that implements the behaviour of the scooter agent.""" def __init__(self, *args, start=(30.28, 59.91), finish=(30.34, 59.97), n_points=3, charge=0.6, **kwargs): super(ScooterAgent, self).__init__(*args, **kwargs) self._api = LedgerApi('127.0.0.1', 8100) self._entity = Entity() self.speed = 0.0005 self._api.sync(self._api.tokens.wealth(self._entity, 5000000)) self._address = Address(self._entity) with open("../02_full_contract.etch", "r") as fb: self._source = fb.read() # Create contract self._contract = SmartContract(self._source) # Deploy contract self._api.sync(self._api.contracts.create(self._entity, self._contract, 2456766)) with open('contract.txt','r') as ff: self.digest = ff.readline().split('\n')[0] self.owner = ff.readline() self._loop = asyncio.get_event_loop() self.provider = Entity() self.scooter = Entity() self.path = make_path(start, finish, n_points, 0.01) self.charge = charge self._contract.action(self._api, 'addProvider', 2456, [self._entity, self.provider], Address(self.provider), self._address) self._contract.action(self._api, 'addScooter', 2456, [self.provider], Address(self.scooter), Address(self.provider), int(start[1]*1000), int(start[0]*1000), 100, 1, 15) def on_search_result(self, search_id: int, agents: List[str]): if len(agents) == 0: print("[{}]: No agent found. Stopping...".format(self.public_key)) self.stop() return print("[{0}]: Agent found: {1}".format(self.public_key, agents)) for agent in agents: print("[{0}]: Sending to agent {1}".format(self.public_key, agent)) # we send a 'None' query, meaning "give me all the resources you can propose." query = None self.send_cfp(1, 0, agent, 0, query) self.saved_proposals = [] self._loop.call_later(3, self.decide_on_proposals) def on_propose(self, msg_id: int, dialogue_id: int, origin: str, target: int, proposals: PROPOSE_TYPES): print("[{0}]: Received propose from agent {1}".format(self.public_key, origin)) for i, p in enumerate(proposals): print("[{0}]: Proposal {1}: {2}".format(self.public_key, i, p.values)) self.saved_proposals.append(((msg_id, dialogue_id, origin, msg_id + 1), p)) # self.send_accept(msg_id, dialogue_id, origin, msg_id + 1) def decide_on_proposals(self): print('Got proposals:', self.saved_proposals) proposals = [{ 'address': p[1].values['charger_address'], 'longitude': p[1].values['longitude'], 'latitude': p[1].values['latitude'], 'max_count': p[1].values['max_count'], 'rate': p[1].values['rate'], 'scheduler': json.loads(p[1].values['scheduler']), 'args': p[0] } for p in self.saved_proposals] best_proposal, best_slot, new_path = find_best(self.path, proposals, self.charge, 0.00001, self.speed) dict = { 'address': str(Address(self.scooter)), 'startTime': best_slot[0], 'endTime': best_slot[1] } encoded_data = json.dumps(dict).encode("utf-8") print("[{0}]: Sending contract to {1}".format(self.public_key, best_proposal['args'][2])) self.send_message(0, best_proposal['args'][1], best_proposal['args'][2], encoded_data) time.sleep(5) self.send_accept(best_proposal['args'][0], best_proposal['args'][1], best_proposal['args'][2], best_proposal['args'][3]) self.path = new_path self._loop.create_task(self.go()) async def go(self): start_time = time.time() while True: await asyncio.sleep(1) delte_time = time.time() - start_time walked_distance = self.speed*delte_time current_pos = 0 new_position = None for i in range(len(self.path) - 1): d = dist(self.path[i], self.path[i+1]) if current_pos + d >= walked_distance: alpha = (walked_distance - current_pos) / d new_position = in_between(self.path[i], self.path[i+1], alpha) print(self._address, 'Path', self.path) print(self._address, 'Next point', self.path[i+1]) break else: current_pos += d if new_position is None: raise Exception("That's all, folks!") self._contract.action(self._api, 'scooterUpdate', 2456, [self.provider], Address(self.scooter), int(new_position[1]*1000), int(new_position[0]*1000), int(self.charge*100))
class ChargerAgent(OEFAgent): """Class that implements the behaviour of the charger agent.""" charger_description = Description({ "price_per_energy_percent": True, }, JOURNEY_MODEL) def __init__(self, *args, **kwargs): super(ChargerAgent, self).__init__(*args, **kwargs) self._entity = Entity() self._address = Address(self._entity) with open("../03_full_contract.etch", "r") as fb: self._source = fb.read() self.prepare_contract(22) def prepare_contract(self, price): # Setting API up self._api = LedgerApi('127.0.0.1', 8100) self.longitude = 10 self.latitude = 10 self.scheduler = {} self.price = price self.rate = 22 self.max_count = 10 # Need funds to deploy contract self._api.sync(self._api.tokens.wealth(self._entity, 5000000)) # Create contract self._contract = SmartContract(self._source) # Deploy contract self._api.sync( self._api.contracts.create(self._entity, self._contract, 2456766)) self.chargers = [ Entity(), ] #self._contract.action(self._api, 'test', 2456755, [self._entity], Address(self.chargers[0]), Address(self.chargers[0])) self._contract.action(self._api, 'addCharger', 2456766, [self._entity], Address(self.chargers[0]), self.longitude, self.latitude, self.price, self.rate, self.max_count) scooter = Entity() scooter_start_time = 150000 scooter_end_time = 151000 tx_digest = self._contract.action(self._api, 'book', 2456766, [self._entity], Address(self.chargers[0]), Address(scooter), scooter_start_time, scooter_end_time) time.sleep(3) tx_status = self._api.tx.status(tx_digest) if tx_status == "Executed": self.scheduler[str( Address(scooter))] = [scooter_start_time, scooter_end_time] query = self._contract.query(api=self._api, name='getSlotInfo', charger=Address(self.chargers[0])) print(query) def on_cfp(self, msg_id: int, dialogue_id: int, origin: str, target: int, query: CFP_TYPES): """Send a simple Propose to the sender of the CFP.""" print("[{0}]: Received CFP from {1}".format(self.public_key, origin)) price = self.price # prepare the proposal with a given price. proposal = Description({ "price_per_energy_percent": price, "digest": str(self._contract.digest), "longitude": self.longitude, "latitude": self.latitude, "scheduler": json.dumps(self.scheduler), "rate": self.rate, "max_count": self.max_count }) print("[{}]: Sending propose at price: {}".format( self.public_key, price)) self.send_propose(msg_id + 1, dialogue_id, origin, target + 1, [proposal]) def on_accept(self, msg_id: int, dialogue_id: int, origin: str, target: int): """Once we received an Accept, send the requested data.""" print("[{0}]: Received accept from {1}.".format( self.public_key, origin)) # Preparing contract # PLACE HOLDER TO PREPARE AND SIGN TRANSACTION print(self._contract) contract = { "digest": str(self._contract.digest), "owner": str(self._contract.owner), "chargers": [str(Address(s)) for s in self.chargers] } # Sending contract encoded_data = json.dumps(contract).encode("utf-8") print("[{0}]: Sending contract to {1}".format(self.public_key, origin)) self.send_message(0, dialogue_id, origin, encoded_data)
from fetchai.ledger.api import LedgerApi from fetchai.ledger.contract import SmartContract from fetchai.ledger.crypto import Entity, Address import time contract_owner = Entity.from_hex( 'c25ace8a7a485b396f30e4a0332d0d18fd2e462b3f1404f85a1b7bcac4b4b19d') contract_owner_address = Address( contract_owner) # atsREugsanXS828FnTvmLM9vCkBsWnDgushDH9YjEgsdBuRGv with open("./cbns_token.etch", "r") as fb: contract_source = fb.read() api = LedgerApi('127.0.0.1', 8000) api.sync(api.tokens.wealth(contract_owner, 5000000)) contract = SmartContract(contract_source) api.sync(api.contracts.create(contract_owner, contract, 2456766)) time.sleep(10) print('Deployed contract address:', Address(contract.digest)) print('my balance:', contract.query(api, 'balanceOf', owner=contract_owner_address))
def main(source, name): # Create keypair for the contract owner charge_provider1 = Entity() charge_address1 = Address(charge_provider1) charge_provider2 = Entity() charge_address2 = Address(charge_provider2) parking_provider1 = Entity() parking_address1 = Address(parking_provider1) parking_provider2 = Entity() parking_address2 = Address(parking_provider2) charge1 = Entity() charge_station_address1 = Address(charge1) parking1 = Entity() parking_place_address1 = Address(parking1) # Setting API up api = LedgerApi('127.0.0.1', 8100) # Need funds to deploy contract api.sync(api.tokens.wealth(charge_provider1, 59000000)) # Create contract contract = SmartContract(source) # Deploy contract api.sync(api.contracts.create(charge_provider1, contract, 2456766)) if name.endswith("contract.etch"): contract.action(api, 'addChargeProvider', 2456766, [charge_provider2, charge_provider1], charge_address2, charge_address1) contract.action(api, 'addCharge', 2456766, [charge_provider2, charge_provider1], charge_address2, charge_address1, 22, 1) print("Wait for charge txs to be mined ...") time.sleep(5) # Printing balance of the creating address1 print(contract.query(api, 'getChargeFleetSize'), " charge in fleet") contract.action(api, 'addParkingProvider', 2456766, [parking_provider2, parking_provider1], parking_address2, parking_address1) contract.action(api, 'addParking', 2456766, [parking_provider2, parking_provider1], parking_address2, parking_address1, 22, 1) print("Wait for parking txs to be mined ...") time.sleep(5) # Printing balance of the creating address1 print(contract.query(api, 'getParkingFleetSize'), " parking in fleet")
endfunction @query function balance(address: Address) : UInt64 var supply_state = State<UInt64>(address); return supply_state.get(0u64); endfunction """ # build the ledger API api = LedgerApi(HOST, PORT) # create wealth so that we have the funds to be able to create contracts on the network api.sync(api.tokens.wealth(entity1, 10000)) # create the smart contract contract = SmartContract(CONTRACT_TEXT) # deploy the contract to the network api.sync(api.contracts.create(entity1, contract, 2000)) @app.route('/rentStop') def rentStop(): global address1 global address2 global api global contract api.sync(contract.action(api, 'transfer', 40, [entity1], address1, address2, 200)) return jsonify(True) @app.route('/getUsers') def getUsers():
class ChargerAgent(OEFAgent): """Class that implements the behaviour of the charger agent.""" charger_description = Description({ "price_per_energy_percent": True, }, JOURNEY_MODEL) def __init__(self, *args, latitude=59.54, longitude=30.31, **kwargs): super(ChargerAgent, self).__init__(*args, **kwargs) self._entity = Entity() self._address = Address(self._entity) self.latitude = latitude self.longitude = longitude with open("../02_full_contract.etch", "r") as fb: self._source = fb.read() self.prepare_contract(22) def prepare_contract(self, price): # Setting API up self._api = LedgerApi('127.0.0.1', 8100) self.scheduler = {} self.price = price self.rate = 22 self.max_count = 10 # Need funds to deploy contract self._api.sync(self._api.tokens.wealth(self._entity, 5000000)) # Create contract self._contract = SmartContract(self._source) # Deploy contract self._api.sync( self._api.contracts.create(self._entity, self._contract, 2456766)) self.chargers = [ Entity(), ] self._contract.action(self._api, 'addCharger', 2456766, [self._entity], Address(self.chargers[0]), int(self.latitude * 1000), int(self.longitude * 1000), self.price, self.rate, self.max_count) #query = self._contract.query(api=self._api, name='getSlotInfo', charger=Address(self.chargers[0])) #print(query) def on_cfp(self, msg_id: int, dialogue_id: int, origin: str, target: int, query: CFP_TYPES): """Send a simple Propose to the sender of the CFP.""" print("[{0}]: Received CFP from {1}".format(self.public_key, origin)) price = self.price timeArr = [] for key in self.scheduler.keys(): timeArr.append(self.scheduler[key]) # prepare the proposal with a given price. proposal = Description({ "price_per_energy_percent": price, "digest": str(self._contract), "longitude": self.longitude, "latitude": self.latitude, "scheduler": json.dumps(timeArr), "rate": self.rate, "max_count": self.max_count, "charger_address": str(Address(self.chargers[0])) }) print("[{}]: Sending propose at price: {}".format( self.public_key, price)) self.send_propose(msg_id + 1, dialogue_id, origin, target + 1, [proposal]) def on_message(self, msg_id: int, dialogue_id: int, origin: str, content: bytes): """Extract and print data from incoming (simple) messages.""" # PLACE HOLDER TO SIGN AND SUBMIT TRANSACTION json_bla = json.loads(content.decode("utf-8")) print("[{0}]: Received contract from {1}".format( self.public_key, origin)) print("READY TO SUBMIT: ", json_bla['address']) self.scooterToBook = Address(json_bla['address']) self.scooter_start_time = json_bla['startTime'] self.scooter_end_time = json_bla['endTime'] def on_accept(self, msg_id: int, dialogue_id: int, origin: str, target: int): """Once we received an Accept, send the requested data.""" print("[{0}]: Received accept from {1}.".format( self.public_key, origin)) # Preparing contract # PLACE HOLDER TO PREPARE AND SIGN TRANSACTION print(self.scooterToBook) print(Address(self.scooterToBook)) print("trying to BOOK /////") #tx_digest = self._contract.action(self._api, 'book', 2456766, [self.chargers[0]], Address(self.chargers[0]), # self.scooterToBook, self.scooter_start_time, self.scooter_end_time) time.sleep(3) #print("Failed tx:", tx_digest) #tx_status = self._api.tx.status(tx_digest) #if tx_status == "Executed": # self.scheduler[self.scooterToBook] = [self.scooter_start_time, self.scooter_end_time] # encoded_data = json.dumps(tx_digest).encode("utf-8") # print("[{0}]: Sending contract to {1}".format(self.public_key, origin)) # self.send_message(0, dialogue_id, origin, encoded_data) self.scheduler[self.scooterToBook] = [ self.scooter_start_time, self.scooter_end_time ]
from fetchai.ledger.api import LedgerApi from fetchai.ledger.contract import SmartContract from fetchai.ledger.crypto import Entity, Address import time contract_owner = Entity.from_hex('c25ace8a7a485b396f30e4a0332d0d18fd2e462b3f1404f85a1b7bcac4b4b19d') contract_owner_address = Address(contract_owner) # atsREugsanXS828FnTvmLM9vCkBsWnDgushDH9YjEgsdBuRGv with open("./chrg_token.etch", "r") as fb: contract_source = fb.read() api = LedgerApi('127.0.0.1', 8000) api.sync(api.tokens.wealth(contract_owner, 5000000)) contract = SmartContract(contract_source) api.sync(api.contracts.create(contract_owner, contract, 2456766)) time.sleep(10) print('Deployed contract address:', Address(contract.digest)) riders = ['WfQDBasLx396CCxWvUoa4BmEsStPNRUi9iA45zu6k3eeaUMGs', 'pUkSDemAkhTob8UiqmRoRbjBW2rwTdnDR68thfToZwYrYHdGr', '2GNnBTmnkUwDeJfuig3hxN77gteXixw45mhita58MzZyMoqQ9u', 'fzoGmzeHN3EkvtbgTNYxuP1Zokpn7AZy5eiSSdP9Rw7KwitPW', '2R6SJK7hoiVTQbMVQDMpB86NaHX9CAXBb5hmH5kyTHCndsNSfe'] for rider in riders: api.sync(contract.action(api, 'transfer', 100, [contract_owner], contract_owner_address, Address(rider), 100000)) print('my balance:', contract.query(api, 'balanceOf', owner=contract_owner_address))
import requests app = Flask(__name__) wallet_owner = Entity() wallet_address = Address(wallet_owner) api = LedgerApi('127.0.0.1', 8100) contracts = {} contract_user = Entity() user_address = Address(contract_user) with open(sys.argv[1], "r") as fb: source = fb.read() # Create contract contract = SmartContract(source) @app.route('/balance') def balance(): balance = api.tokens.balance(wallet_address) return json.dumps({"address": str(wallet_address), "balance": balance}) @app.route('/address') def address(): return json.dumps({"address", str(wallet_address)}) @app.route('/create-tokens') def create_tokens():
class ScooterAgent(OEFAgent): """Class that implements the behaviour of the scooter agent.""" def __init__(self, *args, n_providers=3, scooter_per_provider=5, **kwargs): super(ScooterAgent, self).__init__(*args, **kwargs) self._api = LedgerApi('127.0.0.1', 8100) self._entity = Entity() self._api.sync(self._api.tokens.wealth(self._entity, 5000000)) self._address = Address(self._entity) with open("../02_full_contract.etch", "r") as fb: self._source = fb.read() # Create contract self._contract = SmartContract(self._source) # Deploy contract self._api.sync( self._api.contracts.create(self._entity, self._contract, 2456766)) self._loop = asyncio.get_event_loop() self.providers = [] self.scooters = [] for i in range(n_providers): self.providers.append(Entity()) scooters = [Entity() for j in range(scooter_per_provider)] self.scooters.extend(scooters) self._contract.action(self._api, 'addProvider', 2456766, [self._entity, self.providers[0]], Address(self.providers[0]), self._address) self._contract.action(self._api, 'addScooter', 2456766, [self.providers[0]], Address(self.scooters[0]), Address(self.providers[0]), 22, 23, 100, 1, 15) print(Address(self.scooters[0])) def on_search_result(self, search_id: int, agents: List[str]): if len(agents) == 0: print("[{}]: No agent found. Stopping...".format(self.public_key)) self.stop() return print("[{0}]: Agent found: {1}".format(self.public_key, agents)) for agent in agents: print("[{0}]: Sending to agent {1}".format(self.public_key, agent)) # we send a 'None' query, meaning "give me all the resources you can propose." query = None self.send_cfp(1, 0, agent, 0, query) self.saved_proposals = [] self._loop.call_later(3, self.decide_on_proposals) def on_propose(self, msg_id: int, dialogue_id: int, origin: str, target: int, proposals: PROPOSE_TYPES): print("[{0}]: Received propose from agent {1}".format( self.public_key, origin)) for i, p in enumerate(proposals): print("[{0}]: Proposal {1}: {2}".format(self.public_key, i, p.values)) self.saved_proposals.append( ((msg_id, dialogue_id, origin, msg_id + 1), p)) # self.send_accept(msg_id, dialogue_id, origin, msg_id + 1) def decide_on_proposals(self): print('Got proposals:', self.saved_proposals) proposals = [{ 'address': p[1].values['charger_address'], 'longitude': p[1].values['longitude'], 'latitude': p[1].values['latitude'], 'max_count': p[1].values['max_count'], 'scheduler': json.loads(p[1].values['scheduler']), 'args': p[0] } for p in self.saved_proposals] trajectory = [(1, 1), (3, 4), (6, 4), (7, 6), (8, 8)] best_proposal, best_slot = find_best(trajectory, proposals, 100, 0.00001, 1, 0.1) dict = { 'address': str(Address(self.scooters[0])), 'startTime': best_slot[0], 'endTime': best_slot[1] } encoded_data = json.dumps(dict).encode("utf-8") print("[{0}]: Sending contract to {1}".format( self.public_key, best_proposal['args'][2])) self.send_message(0, best_proposal['args'][1], best_proposal['args'][2], encoded_data) time.sleep(5) self.send_accept(best_proposal['args'][0], best_proposal['args'][1], best_proposal['args'][2], best_proposal['args'][3])