Пример #1
0
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
    synergetic_contract = Contract(CONTRACT_TEXT)
    print('Creating contract..')
    api.sync(api.contracts.create(entity, synergetic_contract, 4096))
    print('Contract submitted ({}.{}).'.format(
        synergetic_contract.digest.to_hex(), synergetic_contract.owner))

    # create a whole series of random data to submit to the DAG
    random_ints = [random.randint(0, 200) for _ in range(10)]
    api.sync([
        api.contracts.submit_data(entity,
                                  synergetic_contract.digest,
                                  value=value) for value in random_ints
    ])
    print('Data submitted.')

    print('Waiting...')
    api.wait_for_blocks(10)

    print('Issuing query...')
    result = synergetic_contract.query(api, 'query_result')
    print('Query result:', result)
Пример #2
0
def run(options):
    entity1 = Entity()

    # create the APIs
    api = LedgerApi(options['host'], options['port'])

    api.sync(api.tokens.wealth(entity1, 1000000))

    contract = Contract(CONTRACT_TEXT, entity1)
    contract2 = Contract(CONTRACT_TEXT2, entity1)

    api.sync(api.contracts.create(entity1, contract, 20000))
    api.sync(api.contracts.create(entity1, contract2, 20000))

    current_block = api.tokens._current_block_number()

    api.sync(
        contract.action(api, 'c2c_call', 40000, [entity1],
                        str(contract2.address)))

    time.sleep(2)

    later_block = contract.query(api, 'query_block_number_state')
    assert later_block > current_block, \
        'Expected number larger than {}, found {}'.format(
            current_block, later_block)
Пример #3
0
def create_balance(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.transfer(test_instance._benefactor_entity, entity,
                                 amount, BASE_TX_FEE)

        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 send funds to node!")
    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)
Пример #5
0
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()
        output('Submit data, available balance: ', api.tokens.balance(entity))
        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} ")
Пример #6
0
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)
Пример #7
0
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))

    result = contract.query(api, 'check_x_with_default')
    assert result == 999,\
        'Expected to receive default value of 999, got {}'.format(result)
    try:
        contract.query(api, 'check_x')
        assert False, 'Expected query to fail'
    except RuntimeError:
        pass

    api.sync(contract.action(api, 'set_x_to_3', 200, entity1))

    result = contract.query(api, 'check_x_with_default')
    assert result == 3, \
        'Expected to receive value of 3, got {}'.format(result)
    result = contract.query(api, 'check_x')
    assert result == 3, \
        'Expected to receive value of 3, got {}'.format(result)

    api.sync(contract.action(api, 'set_x_to_5', 200, entity1))

    result = contract.query(api, 'check_x_with_default')
    assert result == 5, \
        'Expected to receive value of 5, got {}'.format(result)
    result = contract.query(api, 'check_x')
    assert result == 5, \
        'Expected to receive value of 5, got {}'.format(result)
def generate_fetchai_wealth(arguments: argparse.Namespace) -> None:
    """
    Generate tokens to be able to make a transaction.

    :param arguments: the arguments
    :return: None
    """
    try:
        api = LedgerApi(arguments.addr, arguments.port)
    except Exception:
        logging.info("Couldn't connect! Please check your add and port.")
        sys.exit(1)

    try:
        if arguments.private_key is None or arguments.private_key == "":
            raise ValueError
    except ValueError:
        logging.error("Please provide a private key. --private-key .... ")
        sys.exit(1)

    logging.info("Waiting for token wealth generation...")
    entity_to_generate_wealth = Entity.from_hex(
        Path(arguments.private_key).read_text())
    api.sync(api.tokens.wealth(entity_to_generate_wealth, arguments.amount))
    address = Address(entity_to_generate_wealth)
    balance = api.tokens.balance(address)
    logging.info('The new balance of the address {} is : {} FET'.format(
        address, balance))
Пример #9
0
 def __init__(self, network, port):
     self.network = network
     self.host = self.get_ip()
     self.port = port
     self.api = LedgerApi(self.host, self.port)
     self.contracts = {}  # {'name': ContractInfo}
     self.entities = {}  # {'name' : Entity}
Пример #10
0
def main():
    # load up the previously created private key
    with open('private.key', 'r') as private_key_file:
        entity1 = Entity.prompt_load(private_key_file)

    # load up the deployed contract
    with open('sample.contract', 'r') as contract_file:
        contract = Contract.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])
Пример #11
0
    def prepare_contract(self, price):
        # Setting API up
        self._api = LedgerApi('127.0.0.1', 8100)

        self.scheduler = {}

        self.price = price
        self.rate = 20
        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))

        with open('contract.txt','r') as ff:
            self.digest = ff.readline().split('\n')[0]
            self.owner = ff.readline()

        self.chargers = [Entity(), ]

        self._api.contracts.action(self.digest, self.owner, 'addCharger', 2456766, [self._entity],
                              Address(self.chargers[0]), self.latitude, self.longitude, self.price, self.rate, self.max_count)
Пример #12
0
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
    print('Create wealth...')
    api.sync(api.tokens.wealth(entity1, 100000000))

    contract = Contract(CONTRACT_TEXT, entity1)

    # deploy the contract to the network
    print('Create contract...')
    api.sync(api.contracts.create(entity1, contract, 10000))

    api.sync(api.tokens.transfer(entity1, contract.address, 10000, 500))

    submit_synergetic_data(api, contract, [100, 20, 3], entity1)

    print('Query init state...')
    init_result = contract.query(api, 'query_init_test')
    print('Init state: ', init_result)
    assert init_result == 123

    print('Execute action...')
    api.sync(contract.action(api, 'action_test', 10000, [entity1]))

    print('Query action state...')
    action_result = contract.query(api, 'query_action_test')
    print('Action state: ', action_result)
    assert action_result == 456
Пример #13
0
class InitLedger(OEFAgent):
    """Class that implements the behaviour of the charger agent."""
    def __init__(self, *args, **kwargs):
        super(InitLedger, self).__init__(*args, **kwargs)

        self._entity = Entity()
        self._address = Address(self._entity)

        with open("../02_full_contract.etch", "r") as fb:
            self._source = fb.read()

        self.prepare_contract()

    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()
Пример #14
0
def releaseEscrew(entity1, contract, entity2):
    api = LedgerApi(HOST, 8100)
    fet_tx_fee = 40
    api.sync(contract.action(api, 'releaseEscrew', fet_tx_fee,
                             [entity1], entity2,
                             ))
    print("Escrew Released.")
Пример #15
0
class TransportAgent(OEFAgent):
    """Class that implements the behaviour of the scooter agent."""

    scooter_description = Description(
        {
            "price_per_km": True,
        },
        JOURNEY_MODEL
    )

    def __init__(self, data, *args, **kwargs):
        super(TransportAgent, self).__init__(*args, **kwargs)
        self.data = data
        self._entity = Entity()
        self._address = Address(self._entity)

    #      with open("./full_contract.etch", "r") as fb:
    #          self._source = fb.read()

    #      self.prepare_contract()

    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 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 = 1

        # prepare the proposal with a given price.
        proposal = Description({"price_per_km": price})
        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
        contract = {"contract": "data"}

        # Sending contract
        encoded_data = json.dumps(contract).encode("utf-8")
        print("[{0}]: Sending contract to {1}".format(self.public_key, origin))
        self.data['status'] = 'RIDES'
        self.send_message(0, dialogue_id, origin, encoded_data)
Пример #16
0
def setEscrew(entity, contract, amount):
    api = LedgerApi(HOST, 8100)
    fet_tx_fee = 40
    print('-- BEFORE --')
    print_address_balances(api, contract, [entity])
    api.sync(contract.action(api, 'setEscrew', fet_tx_fee,
                              [entity], Address(entity),
                              amount))
    print('-- AFTER --')
    print_address_balances(api, contract, [entity])
Пример #17
0
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]

    api.sync(api.tokens.transfer(entity1, contract.address, 10000, 500))

    block_number = status.exit_code
    v = contract.query(api, 'get_init_block_number_state')
    assert block_number > 0
    assert block_number == v, \
        'Returned block number by the contract ({}) is not what expected ({})'.format(
            v, block_number)

    api.sync(contract.action(api, 'set_block_number_state', 400, entity1))

    assert block_number <= contract.query(api, 'query_block_number_state')
Пример #18
0
 def wait_for_blocks(self, node_index, number_of_blocks):
     """
     Wait for a specific number of blocks in the selected node
     :param node_index: which node we are interested in
     :param number_of_blocks: for how many new block to wait
     :return:
     """
     port = self._nodes[node_index]._port_start
     output(f"Waiting for {number_of_blocks} blocks on node {port}")
     api = LedgerApi("localhost", port)
     api.wait_for_blocks(number_of_blocks)
Пример #19
0
    def __init__(self, *args, **kwargs):
        super(RiderAgent, self).__init__(*args, **kwargs)

        riders = [ '904f302f980617d5f40219337ef826cdf64992e577676cdd83295f189af82ff4',
                '03f807bbf02cf849145fc51d7dd4438559dc4756a3b2321bbdf42e8f7910a3df',
                'dfe06a3baa93ad1d2f248317c601f710821cc1916e09d7c6e261f432563e50f1',
                'a92e7c9a1c091bb7bc70874da36fdc44a8217577758a061e008344bd402a6118',
                '672ebe1ef50a3c49532fe2118686d7025048de51e4f77ed8d0880cd52efe80a7']
        self._entity = Entity.from_hex(riders[int(sys.argv[1])-1])
        self._address = Address(self._entity)
        self._api = LedgerApi('127.0.0.1', 8000)
        self._api.sync(self._api.tokens.wealth(self._entity, 5000000))
Пример #20
0
    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 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)
Пример #22
0
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))
        api.sync(api.tokens.wealth(entity, amount))
def releaseEscrew(entity1, contract, entity2):
    api = LedgerApi(HOST, 8100)
    fet_tx_fee = 40
    api.sync(
        contract.action(
            api,
            'releaseEscrew',
            fet_tx_fee,
            [entity1],
            Address(entity2),
        ))
    print("Escrew Released.")
    print_address_balances(api, contract, [entity1, entity2])
Пример #24
0
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])
Пример #25
0
def main():
    entity = Entity.from_hex(
        '6e8339a0c6d51fc58b4365bf2ce18ff2698d2b8c40bb13fcef7e1ba05df18e4b')
    address = Address(entity)
    print('Address:', address)

    # create the APIs
    api = LedgerApi(HOST, PORT)

    # Display balance before
    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)
Пример #26
0
 def test_hostport_or_network(self):
     """Tests that init accepts only a host+port pair, or a network"""
     # If providing host or port, must provide both
     with self.assertRaises(AssertionError):
         a = LedgerApi(host='host')
     with self.assertRaises(AssertionError):
         a = LedgerApi(port=1234)
     # If providing network, may not provide host or port
     with self.assertRaises(AssertionError):
         a = LedgerApi(host='host', network='alpha')
     with self.assertRaises(AssertionError):
         a = LedgerApi(port=1234, network='alpha')
     with self.assertRaises(AssertionError):
         a = LedgerApi(host='host', port=1234, network='alpha')
Пример #27
0
def main():
    # create the API
    api = LedgerApi('127.0.0.1', 8000)

    # create an entity from a private key stored in hex
    entity = Entity.from_hex(
        '6e8339a0c6d51fc58b4365bf2ce18ff2698d2b8c40bb13fcef7e1ba05df18e4b')

    # create the contract on the ledger
    synergetic_contract = Contract(CONTRACT_TEXT, entity)
    print('Creating contract..')
    api.sync(api.contracts.create(entity, synergetic_contract, 4096))

    # create a whole series of random data to submit to the DAG
    random_ints = [random.randint(0, 200) for _ in range(10)]
    fee = 100000000
    api.sync(
        [api.contracts.submit_data(entity, synergetic_contract.digest, synergetic_contract.address, fee, value=value) \
         for value in random_ints])
    print('Data submitted.')

    print('Waiting...')
    api.wait_for_blocks(10)

    print('Issuing query...')
    result = synergetic_contract.query(api, 'query_result')
    print('Query result:', result)
Пример #28
0
def deployContract(entity):
    api = LedgerApi(HOST, 8100)

    # create the smart contract
    contract = Contract(CONTRACT_TEXT)

    print('Deploying contract...')

    # deploy the contract to the network
    api.sync(api.contracts.create(entity, contract, 6000))

    print('Deploying contract...complete')

    return contract
Пример #29
0
    def __init__(self, public_key: str, price: int, interval: int, account: Entity, oef_addr: str, oef_port: int = 10000):
        super().__init__(public_key, oef_addr, oef_port, loop=asyncio.new_event_loop())
        self.cost = 0
        self.pending_cfp = 0
        self.received_proposals = []
        self.received_declines = 0

        self.interval = interval
        self.maxPrice = price
        self.Auction = False
        self.prevPrice = 0

        self.api = LedgerApi('127.0.0.1', 8100)
        self.account = account
Пример #30
0
def destake(parameters, test_instance):
    nodes = parameters["nodes"]

    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)

        # create the entity from the node's private key
        entity = Entity(get_nodes_private_key(test_instance, node_index))

        current_stake = api.tokens.stake(entity)

        output(f'Destaking node {node_index}. Current stake: ', current_stake)
        output(f'Destaking node {node_index}. Current balance: ',
               api.tokens.balance(entity))

        api.sync(api.tokens.add_stake(entity, 1, 500))
        api.sync(api.tokens.de_stake(entity, current_stake, 500))
        api.sync(api.tokens.collect_stake(entity, 500))

        output(f'Destaked node {node_index}. Current stake: ', current_stake)
        output(f'Destaked node {node_index}. Current balance: ',
               api.tokens.balance(entity))
        output(f'Destaked node {node_index}. Current cooldown stake: ',
               api.tokens.stake_cooldown(entity))