def query_balance(parameters, test_instance): nodes = parameters["nodes"] variable = parameters["save_as"] for node_index in nodes: node_instance = test_instance._nodes[node_index] node_host = "localhost" node_port = node_instance._port_start api = LedgerApi(node_host, node_port) # create the entity from the node's private key entity = Entity(get_nodes_private_key(test_instance, node_index)) b = api.tokens.balance(entity) address = Address(entity) output( f"Requested balance ({b}) {address.to_hex()}, saved as {variable}") if not hasattr(node_instance, "_variables"): setattr(node_instance, "_variables", {}) node_instance._variables[variable] = b
def run(options, benefactor): entity1 = Entity() # build the ledger API api = LedgerApi(options['host'], options['port']) # create funds so that we have the funds to be able to create contracts on the network api.sync(api.tokens.transfer(benefactor, entity1, 100000, 1000)) contract = Contract(CONTRACT_TEXT, entity1) # deploy the contract to the network status = api.sync(api.contracts.create(entity1, contract, 2000))[0] saved_address = contract.query(api, 'query_owner_address') assert str(Address(entity1)) == saved_address, \ 'Expected owner address {} but found {}'.format( Address(entity1), saved_address)
def setup(api): entity1 = Entity() api.sync(api.tokens.wealth(entity1, 100000)) contract1 = Contract(TRANSFER_CONTRACT_TEXT, entity1) contract2 = Contract(CONTRACT_TEXT, entity1) master_contract = Contract(MASTER_CONTRACT_TEXT, entity1) initial_owner_balance = api.tokens.balance(Address(entity1)) assert initial_owner_balance == 100000, \ 'Expected initial directly-queried balance to be 0, found {}'.format( 100000, initial_owner_balance) api.sync(api.contracts.create(entity1, contract1, 2000)) api.sync(api.contracts.create(entity1, contract2, 2000)) api.sync(api.contracts.create(entity1, master_contract, 2000)) return entity1, contract1, contract2, master_contract
def main(): api = LedgerApi(HOST, PORT) # in our examples we use Addresses with funds, which we load from hex-encoded private keys. identity1 = Entity.from_hex('6e8339a0c6d51fc58b4365bf2ce18ff2698d2b8c40bb13fcef7e1ba05df18e4b') identity2 = Entity.from_hex('e833c747ee0aeae29e6823e7c825d3001638bc30ffe50363f8adf2693c3286f8') # we make a Transfer which returns a transaction id. tx = api.tokens.transfer(identity1, identity2, 2500, 20) # wait for the transaction to complete so that the information is 100% present api.sync(tx) # we Verify that the transaction is the submitted transaction is the sent transaction # TxContents object (below contents variable) contains all properties sent to ledger in transaction API call contents = api.tx.contents(tx) # below we access a subset of the properties of our TxContents object valid_until = contents.valid_until valid_from = contents.valid_from from_address = contents.from_address transfers = contents.transfers # iterate over the transfers in the transaction, which is singular in this instance for to_address, amount in transfers.items(): print( "\nThe submitted transaction is from Address: {}\nto Address: {} \nof amount: {}\nand is valid from (block number): {} \nand valid until (block number): {}".format( str(from_address), to_address, amount, valid_from, valid_until)) nonexistent_entity = Entity() # check the amount being transferred to a particular address; zero in the below instance amount = contents.transfers_to(nonexistent_entity) if amount == 0: print("\nAs expected, nothing is being transferred to Address: ", str(Address(nonexistent_entity))) else: print("\nExample failure: nothing should be transferred to Address: ", str(Address(nonexistent_entity))) # check the status of a transaction. This is an alternative to calling the LedgerApi's sync method, which itself polls the below status endpoint status = api.tx.status(tx) print('\nCurrent Status is :', status.status)
def run(options, benefactor): entity1 = Entity() # create the APIs api = LedgerApi(options['host'], options['port']) api.sync(api.tokens.transfer(benefactor, entity1, 1000000, 1000)) contract = Contract(CONTRACT_TEXT, entity1) api.sync(api.contracts.create(entity1, contract, 2000)) try: api.sync( contract.action(api, 'c2c_call', 400, entity1, str(contract.address))) assert False, \ 'Expected transaction to fail' except RuntimeError: pass
def run(options, benefactor): entity1 = Entity() # create the APIs api = LedgerApi(options['host'], options['port']) api.sync(api.tokens.transfer(benefactor, entity1, 1000000, 1000)) contract = Contract(CONTRACT_TEXT, entity1) contract2 = Contract(CONTRACT_TEXT2, entity1) api.sync(api.contracts.create(entity1, contract, 2000)) api.sync(api.contracts.create(entity1, contract2, 2000)) api.sync(contract.action(api, 'c2c_call', 400, entity1, str(contract2.address))) result = contract.query(api, 'query_eleven') assert result == 11, \ 'Expected 11, found {}'.format(result)
def main(): print('Creating private key...') # create our first private key pair entity1 = Entity() # save the private key to disk with open('private.key', 'w') as private_key_file: entity1.prompt_dump(private_key_file) print('Creating private key...complete') # build the ledger API api = LedgerApi('127.0.0.1', 8000) print('Creating initial balance...') # create wealth so that we have the funds to be able to create contracts on the network api.sync(api.tokens.wealth(entity1, 10000)) print('Creating initial balance...complete')
def add_parking(): global contract global wallet_owner global contract_user global wallet_address global user_address if requests.method == 'POST': lat = request.form['lat'] lon = request.form['long'] contract.action(api, 'addParkingProvider', 2456766, [contract_user, wallet_owner], user_address, wallet_address) contract.action(api, 'addParking', 2456766, [contract_user, wallet_owner], user_address, wallet_address, lat, long) print("Wait for parking txs to be mined ...") time.sleep(5) parking = Entity() parking_address = Address(parking) # Printing balance of the creating address1 print(contract.query(api, 'getParkingFleetSize'), " parking in fleet") return json.dumps({"address", str(parking_address)})
def main(): key_path = '/Users/nhutton/repos/ledger/build_debug/node1/p2p.key' with open(key_path, 'rb') as key_file: key_bytes = key_file.read() # create the entity from this private key entity = Entity(key_bytes) address = Address(entity) print('Address:', address) # create the APIs api = LedgerApi(HOST, PORT) # create the balance print('Submitting wealth creation...') api.sync(api.tokens.wealth(entity, 10000)) print('Balance:', api.tokens.balance(entity)) print('Stake..:', api.tokens.stake(entity)) # submit and wait for the transfer to be complete print('Submitting stake request...') api.sync(api.tokens.add_stake(entity, 1000, 50)) while True: print('Balance............:', api.tokens.balance(entity)) print('Stake..............:', api.tokens.stake(entity)) print('Stake on cooldown..:', api.tokens.stake_cooldown(entity)) # De-stake half of the staked balance to_destake = int(api.tokens.stake(entity)/2) api.sync(api.tokens.de_stake(entity, to_destake, 500)) # Collect cooled down stakes api.sync(api.tokens.collect_stake(entity, 500)) time.sleep(1)
def run(options, benefactor): entity1 = Entity() api = LedgerApi(options['host'], options['port']) api.sync(api.tokens.transfer(benefactor, entity1, 100000000, 1000)) contract = Contract(CONTRACT_TEXT, entity1) api.sync(api.contracts.create(entity1, contract, 10000)) api.sync(api.tokens.transfer(entity1, contract.address, 1000, 500)) assert contract.query(api, 'query_init_test') == 0 api.sync(contract.action(api, 'action_test', 200, [entity1])) v = contract.query(api, 'query_action_test') assert 800 <= v <= 1000, \ 'Expected query_action_test result to be between 800 and 1000, found {}'.format( v) submit_synergetic_data(api, contract, [100, 20, 3], entity1) v = contract.query(api, 'query_clear_test') assert 800 <= v <= 1000, \ 'Expected query_clear_test result to be between 800 and 1000, found {}'.format( v) # Provide the contract with funds api.sync(api.tokens.transfer(entity1, contract.address, 1234, 200)) api.sync(contract.action(api, 'action_test', 200, [entity1])) v = contract.query(api, 'query_action_test') assert 2000 < v < 2234, \ 'Expected query_action_test result to be between 2000 and 2234, found {}'.format( v) submit_synergetic_data(api, contract, [100, 20, 3], entity1) v = contract.query(api, 'query_clear_test') assert 2000 < v < 2234, \ 'Expected query_clear_test result to be between 2000 and 2234, found {}'.format( v)
def __init__(self, data, *args, **kwargs): super(TripAgent, self).__init__(*args, **kwargs) self._entity = Entity() self._address = Address(self._entity) self.data = { "account_id": data['account_id'], "can_be_driver": data['can_be_driver'], "trip_id": data['trip_id'], "from_location_latitude": float(data['from_location'].latitude), "from_location_longitude": float(data['from_location'].longitude), "to_location_latitude": float(data['to_location'].latitude), "to_location_longitude": float(data['to_location'].longitude), "distance_area": data['distance_area'], } self.trip_description = Description(self.data, TRIP_DATAMODEL()) self.data['state'] = 'free' self.data['position'] = Location(self.data['from_location_latitude'], self.data['from_location_longitude']) self.data['transp_location'] = None self.possible_trips = []
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)) contract = Contract(CONTRACT_TEXT, entity1) # deploy the contract to the network status = api.sync(api.contracts.create(entity1, contract, 2000))[0] block_number = status.exit_code assert block_number > 0 assert block_number == contract.query(api, 'get_init_block_number_state') api.sync(contract.action(api, 'set_block_number_state', 400, [entity1])) assert block_number <= contract.query(api, 'query_block_number_state')
def create_synergetic_contract(parameters, test_instance): nodes = parameters["nodes"] name = parameters["name"] fee_limit = parameters["fee_limit"] transfer_amount = parameters.get("transfer_amount", -1) for node_index in nodes: node_host = "localhost" node_port = test_instance._nodes[node_index]._port_start api = LedgerApi(node_host, node_port) # create the entity from the node's private key entity = Entity(get_nodes_private_key(test_instance, node_index)) output('Create contract, available balance: ', api.tokens.balance(entity)) helper = SynergeticContractTestHelper( name, api, entity, test_instance._workspace) helper.create_new(fee_limit) test_instance._nodes[node_index]._contract = helper if transfer_amount > 0: api.sync(api.tokens.transfer( entity, helper.contract.address, transfer_amount, 1000))
def generateEntity(): print('Creating private key...') # create our first private key pair entity1 = Entity() # save the private key to disk # with open('private.key', 'w') as private_key_file: # entity1.dump(private_key_file) print('Creating private key...complete') # build the ledger API api = LedgerApi(HOST, 8100) print('Creating initial balance...') # create wealth so that we have the funds to be able to create contracts on the network api.sync(api.tokens.wealth(entity1, 100000)) print('Creating initial balance...complete') return entity1
def test_action(self, mock_shard_mask): # create contract owner = Entity() contract = Contract(CONTRACT_TEXT, owner) # Mock api for providing number of lanes and receiving create call api = mock.Mock(spec=LedgerApi) api.server = mock.Mock() lane_number = 2 api.server.num_lanes.side_effect = [lane_number] api.contracts = mock.Mock(spec=ContractsApi) # Mock shard mask static method dummy_shard_mask = mock.Mock() mock_shard_mask.side_effect = [dummy_shard_mask] contract.action(api, 'action1', 1000, owner, 'arg1', 'arg2') # Check shard mask gen called with contract digest address base_contract_address = 'fetch.contract.state.{}'.format( str(contract.address)) expected_resources = [ base_contract_address, '{}.value_.arg1'.format(base_contract_address), '{}.value_.arg2'.format(base_contract_address), ] # TODO: Due to parser errors the contract can not correctly distinguish the bit vectors. This means a wild card # bit vector is used. #mock_shard_mask.assert_called_once_with(expected_resources, lane_number) # Check api create method called api.contracts.action.assert_called_once_with(contract.address, 'action1', 1000, owner, 'arg1', 'arg2', shard_mask=BitVector())
def add_charge(): global contract global wallet_owner global contract_user global wallet_address global user_address if requests.method == 'POST': lat = request.form['lat'] lon = request.form['long'] contract.action(api, 'addChargeProvider', 2456766, [contract_user, wallet_owner], user_address, wallet_address) contract.action(api, 'addCharge', 2456766, [contract_user, wallet_owner], user_address, wallet_address, lat, lon) print("Wait for charge txs to be mined ...") time.sleep(5) charge = Entity() charge_address = Address(charge) # Printing balance of the creating address1 print(contract.query(api, 'getChargeFleetSize'), " charge in fleet") return json.dumps({"address", str(charge_address)})
def main(): # create the API api = LedgerApi('127.0.0.1', 8000) # create an entity and provide it some wealth print('Setup...') entity = Entity() api.sync(api.tokens.wealth(entity, 100000000)) print('Setup...complete') # create the contract on the ledger synergy_contract = SynergeticContract(CONTRACT_TEXT) print(synergy_contract.digest) api.sync(api.contracts.create(entity, synergy_contract, 4096)) # create a whole series of random data to submit to the DAG random_ints = [random.randint(0, 200) for _ in range(4000)] api.sync([ api.synergetic.submit_data(entity, synergy_contract.digest, value=value) for value in random_ints ])
def run_contract(parameters, test_instance): nodes = parameters["nodes"] contract_name = parameters["contract_name"] wait_for_blocks_num = parameters["wait_for_blocks"] for node_index in nodes: node_host = "localhost" node_port = test_instance._nodes[node_index]._port_start api = LedgerApi(node_host, node_port) # create the entity from the node's private key entity = Entity(get_nodes_private_key(test_instance, node_index)) try: contract_helper = test_instance._nodes[node_index]._contract except AttributeError: output( f"No contract stored in test_instance (node_index={node_index})! Loading from file..." ) contract_helper = SynergeticContractTestHelper( contract_name, api, entity, test_instance._workspace) contract_helper.load() contract_helper.submit_random_data(10, (0, 200)) api.wait_for_blocks(wait_for_blocks_num) valid = contract_helper.validate_execution() if not valid: output( f"Synergetic contract ({contract_name}) execution failed on node {node_index}!" ) raise Exception( f"Synergetic contract ({contract_name}) execution failed on node {node_index}!" ) else: output( f"Synergetic contract ({contract_name}) executed on node {node_index} " )
def send_txs(parameters, test_instance): name = parameters["name"] amount = parameters["amount"] nodes = parameters["nodes"] if len(nodes) != 1: output("Only one node supported for sending TXs to at this time!") sys.exit(1) # Create or load the identities up front identities = [Entity() for i in range(amount)] for node_index in nodes: node_host = "localhost" node_port = test_instance._nodes[node_index]._port_start # create the API objects we use to interface with the nodes api = LedgerApi(node_host, node_port) tx_and_identity = [] for index in range(amount): # get next identity identity = identities[index] amount = index + 1 # create and send the transaction to the ledger, capturing the tx # hash tx = api.tokens.transfer(test_instance._benefactor_entity, identity, amount, BASE_TX_FEE) tx_and_identity.append((tx, identity, amount)) output(f"Sent balance {amount} to node") # Attach this to the test instance so it can be used for verification test_instance._metadata = tx_and_identity
def run(options): entity1 = Entity() api = LedgerApi(options['host'], options['port']) api.sync(api.tokens.wealth(entity1, 100000000)) contract = Contract(CONTRACT_TEXT, entity1) api.sync(api.contracts.create(entity1, contract, 10000)) assert contract.query(api, 'query_init_test') == 0 api.sync(contract.action(api, 'action_test', 10000, [entity1])) assert contract.query(api, 'query_action_test') == 0 submit_synergetic_data(api, contract, [100, 20, 3], entity1) assert contract.query(api, 'query_clear_test') == 0 # Provide the contract with funds api.tokens.transfer(entity1, contract.address, 1234, 200) api.sync(contract.action(api, 'action_test', 10000, [entity1])) assert contract.query(api, 'query_action_test') == 1234 submit_synergetic_data(api, contract, [100, 20, 3], entity1) assert contract.query(api, 'query_clear_test') == 1234
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 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 makeClient(number: int): #check if entity has already been created if(os.path.exists('./workdir/Agent3/client/client'+str(number)+'_private.key')): #locate the agent account entity for interacting with the ledger. with open ('./workdir/Agent3/client/client'+str(number)+'_private.key', 'r') as private_key_file: client_agentID = Entity.load(private_key_file) else: #create new entity for the agent client_agentID = Entity() #store private key of newly formed entity with open('./workdir/Agent3/client/client'+str(number)+'_private.key', 'w') as private_key_file: client_agentID.dump(private_key_file) #give the account starting tokens api.sync(api.tokens.wealth(client_agentID, 2000)) startBalance = api.tokens.balance(client_agentID) highest_price = random.randint(500, 1000) # define an OEF Agent client= ClientAgent(str(Address(client_agentID)), highest_price, client_agentID, oef_addr="127.0.0.1", oef_port=10000) print('Balance Before:', startBalance) # connect it to the OEF Node client.connect() # query OEF for DataService providers echo_query1 = Query([Constraint("timezone", Eq(3)), Constraint("twentyfour", Eq(False))],TIME_AGENT()) client.search_services(0, echo_query1) client.run()
def run(options, benefactor): entity1 = Entity() # create the APIs api = LedgerApi(options['host'], options['port']) api.sync(api.tokens.transfer(benefactor, entity1, 1000000, 1000)) contracts = [] for i in range(5): contracts += [Contract(CONTRACT_TEXT, entity1)] contract_terminal = Contract(TERMINAL_CONTRACT_TEXT, entity1) for contract in contracts: api.sync(api.contracts.create(entity1, contract, 2000)) api.sync(api.contracts.create(entity1, contract_terminal, 2000)) for i in range(len(contracts) - 1): api.sync(contracts[i].action(api, 'set_callee', 400, entity1, str(contracts[i + 1].address))) api.sync(contracts[-1].action(api, 'set_callee', 400, entity1, str(contract_terminal.address))) api.sync(contracts[0].action(api, 'c2c_call', 400, entity1))
def create_wealth(parameters, test_instance): nodes = parameters["nodes"] amount = parameters["amount"] for node_index in nodes: node_host = "localhost" node_port = test_instance._nodes[node_index]._port_start api = LedgerApi(node_host, node_port) # create the entity from the node's private key entity = Entity(get_nodes_private_key(test_instance, node_index)) tx = api.tokens.wealth(entity, amount) for i in range(10): output('Create balance of: ', amount) api.sync(tx, timeout=120, hold_state_sec=20) for j in range(5): b = api.tokens.balance(entity) output('Current balance: ', b) if b >= amount: return time.sleep(5) time.sleep(5) raise Exception("Failed to create wealth")
def _generate_private_key(cls) -> Entity: entity = Entity() return entity
if __name__ == '__main__': #define the ledger parameters api = LedgerApi('127.0.0.1', 8100) #check if entity has already been created if(os.path.exists('./workdir/Agent4/client/client_private.key')): #locate the agent account entity for interacting with the ledger. with open ('./workdir/Agent4/client/client_private.key', 'r') as private_key_file: client_agentID = Entity.load(private_key_file) else: #create new entity for the agent client_agentID = Entity() #store private key of newly formed entity with open('./workdir/Agent4/client/client_private.key', 'w') as private_key_file: client_agentID.dump(private_key_file) #give the account starting tokens api.sync(api.tokens.wealth(client_agentID, 2000)) startBalance = api.tokens.balance(client_agentID) # define an OEF Agent client_agent = ClientAgent(str(Address(client_agentID)), oef_addr="127.0.0.1", oef_port=10000) print('Balance Before:', startBalance) highest_price = 1700 if highest_price > api.tokens.balance(client_agentID):
if __name__ == '__main__': #define the ledger parameters api = LedgerApi('127.0.0.1', 8100) #checl if entity has already been generated if(os.path.exists('./workdir/Agent_Auction/agent/server_private.key')): #locate the agent account entity for interacting with the ledger. with open ('./workdir/Agent_Auction/agent/server_private.key', 'r') as private_key_file: server_agentID = Entity.load(private_key_file) else: #create the enity for the agent server_agentID = Entity() #store the private key of the newly created entity with open('./workdir/Agent_Auction/agent/server_private.key', 'w') as private_key_file: server_agentID.dump(private_key_file) startBalance = api.tokens.balance(server_agentID) #set trading values price = 20 fet_tx_fee = 40 print('Price:', price) print('Balance Before:', startBalance) # create agent and connect it to OEF server_agent = Demo_Agent(str(Address(server_agentID)), oef_addr="127.0.0.1", oef_port=10000)
import json from flask import Flask, jsonify from fetchai.ledger.api import LedgerApi from fetchai.ledger.contract import SmartContract from fetchai.ledger.crypto import Entity, Address import time app = Flask(__name__) amount = 10000 HOST = '127.0.0.1' PORT = 8100 # create our first private key pair entity1 = Entity() address1 = Address(entity1) # create a second private key pair entity2 = Entity() address2 = Address(entity2) CONTRACT_TEXT = f""" @init function setup(owner: Address) var ttal : UInt64 = {amount}u64; var balance_first = State<UInt64>(Address("{address1}")); var balance_second = State<UInt64>(Address("{address2}")); balance_first.set(ttal); balance_second.set(ttal);
from flask import Flask from fetchai.ledger.api import LedgerApi from fetchai.ledger.contract import SmartContract from fetchai.ledger.crypto import Entity, Address import sys import time import json app = Flask(__name__) wallet_owner = Entity() wallet_address = Address(wallet_owner) api = LedgerApi('127.0.0.1', 8100) contracts = {} @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(): """Creates 10k tokens """ api.sync(api.tokens.wealth(wallet_owner, 100000)) return json.dumps({"status": "done"})