def test_some_party_receives_public_contract(self): some_party_cids = [] publisher_cids = [] with sandbox(AllParty, extra_args=None) as proc: network = Network() network.set_config(url=proc.url, party_groups=[ALL_PARTY]) some_client = network.aio_party(SOME_PARTY) some_client.add_ledger_ready( lambda _: create(PrivateContract, {'someParty': SOME_PARTY})) publisher_client = network.aio_party(PUBLISHER) publisher_client.add_ledger_ready( lambda _: create(PublicContract, { 'publisher': PUBLISHER, 'allParty': ALL_PARTY })) some_client.add_ledger_created( PublicContract, lambda e: some_party_cids.append(e.cid)) some_client.add_ledger_created( PrivateContract, lambda e: some_party_cids.append(e.cid)) publisher_client.add_ledger_created( PublicContract, lambda e: publisher_cids.append(e.cid)) publisher_client.add_ledger_created( PrivateContract, lambda e: publisher_cids.append(e.cid)) network.run_until_complete() print( f'got to the end with some_party contracts: {some_party_cids} and publisher contracts: {publisher_cids}' ) self.assertEqual(len(some_party_cids), 2) self.assertEqual(len(publisher_cids), 1)
async def test_select_template_retrieves_contracts(sandbox): number_of_contracts = 10 async with async_network(url=sandbox, dars=Pending) as network: client = network.aio_new_party() client.add_ledger_ready(lambda _: [ create(Counter, { 'owner': client.party, 'value': 0 }), *[ create(AccountRequest, {'owner': client.party}) for i in range(number_of_contracts) ], ]) @client.ledger_created(AccountRequest) async def on_account_request(event): counter_cid, counter_cdata = await event.acs_find_one(Counter) return [ exercise(event.cid, 'CreateAccount', dict(accountId=counter_cdata['value'])), exercise(counter_cid, 'Increment') ] await network.aio_run(keep_open=False) data = client.find_active(Account) assert len(data) == number_of_contracts
def test_select_template_retrieves_contracts(self): number_of_contracts = 10 with sandbox(Pending) as proc: network = Network() network.set_config(url=proc.url) party_client = network.aio_party(PARTY) party_client.add_ledger_ready(lambda _: [ create(Counter, { 'owner': PARTY, 'value': 0 }), *[ create(AccountRequest, {'owner': PARTY}) for i in range(number_of_contracts) ], ]) @party_client.ledger_created(AccountRequest) async def on_account_request(event): counter_cid, counter_cdata = await event.acs_find_one(Counter) return [ exercise(event.cid, 'CreateAccount', dict(accountId=counter_cdata['value'])), exercise(counter_cid, 'Increment') ] network.run_until_complete() data = party_client.find_active(Account) self.assertEqual(len(data), number_of_contracts)
def test_select_reflects_archive_events(self): notification_count = 3 # we expect that, upon each on_created notification of an OperatorNotification contract, # when we query the ACS, we get precisely the same number of contracts. expected_select_count = notification_count * notification_count actual_select_count = 0 def on_notification_contract(_, __): nonlocal actual_select_count actual_select_count += len( party_client.select(OperatorNotification)) with sandbox(DAML_FILE) as proc: with create_client(participant_url=proc.url, parties=[PARTY]) as client: party_client = client.client(PARTY) party_client.on_ready(lambda *args, **kwargs: create( OperatorRole, {'operator': PARTY})) party_client.on_created( OperatorRole, lambda cid, cdata: exercise( cid, 'PublishMany', dict(count=3))) party_client.on_created( OperatorNotification, lambda cid, _: exercise(cid, 'Archive')) party_client.on_created(OperatorNotification, on_notification_contract) client.run_until_complete() final_select_count = len( party_client.select(OperatorNotification)) self.assertEqual(actual_select_count, expected_select_count) self.assertEqual(0, final_select_count)
def handle_new_listing(event): logging.info(f'Received Listing request - {event}') listing = event.cdata symbol = listing['symbol'] description = listing['description'] calendar_id = listing['calendarId'] quote_currency = listing['quotedAssetId']['label'] price_precision = listing['quotedAssetPrecision'] quantity_precision = listing['tradedAssetPrecision'] min_quantity = listing['minimumTradableQuantity'] max_quantity = listing['maximumTradableQuantity'] status = listing['status'] return create( EXBERRY.CreateInstrumentRequest, { 'integrationParty': client.party, 'symbol': symbol, 'quoteCurrency': quote_currency, 'instrumentDescription': description, 'calendarId': calendar_id, 'pricePrecision': price_precision, 'quantityPrecision': quantity_precision, 'minQuantity': min_quantity, 'maxQuantity': max_quantity, 'status': status })
def handle_order_request(event): logging.info(f"Handling new OrderRequest") sid = get_sid() order = event.cdata['order'] order['isCleared'] = False sid_to_order[sid] = order return create( EXBERRY.NewOrderRequest, { 'order': { 'orderType': 'Limit', 'instrument': make_instrument(order['pair']), 'quantity': float(order['qty']), 'price': float(order['price']), 'side': 'Buy' if order['isBid'] else 'Sell', 'timeInForce': 'GTC', 'mpOrderId': sid, # we use sid for order ids 'userId': make_user_user_id(order['exchParticipant']), }, 'integrationParty': client.party })
def test_select_reflects_archive_events(self): notification_count = 3 # we expect that, upon each on_created notification of an OperatorNotification contract, # when we query the ACS, we get precisely the same number of contracts. expected_select_count = notification_count * notification_count actual_select_count = 0 def on_notification_contract(event): nonlocal actual_select_count actual_select_count += len( event.acs_find_active(OperatorNotification)) with sandbox(Simple) as proc: network = Network() network.set_config(url=proc.url) party_client = network.aio_party(PARTY) party_client.add_ledger_ready( lambda e: create(OperatorRole, {'operator': PARTY})) party_client.add_ledger_created( OperatorRole, lambda e: exercise(e.cid, 'PublishMany', dict(count=3))) party_client.add_ledger_created( OperatorNotification, lambda e: exercise(e.cid, 'Archive')) party_client.add_ledger_created(OperatorNotification, on_notification_contract) network.run_until_complete() final_select_count = len( party_client.find_active(OperatorNotification)) self.assertEqual(actual_select_count, expected_select_count) self.assertEqual(0, final_select_count)
def handle_new_market_pair(event): logging.info(f"Handling new MarketPair") pair = event.cdata symbol = pair['id']['label'] description = pair['description'] calendar_id = pair['calendarId'] quote_currency = pair['quoteTokenId']['label'] price_precision = pair['pricePrecision'] quantity_precision = pair['quantityPrecision'] min_quantity = pair['minQuantity'] max_quantity = pair['maxQuantity'] status = pair['status'][10:] market_pairs[symbol] = pair logging.info(f"New market_pairs is {market_pairs}") return create( EXBERRY.CreateInstrumentRequest, { 'integrationParty': client.party, 'symbol': symbol, 'quoteCurrency': quote_currency, 'instrumentDescription': description, 'calendarId': calendar_id, 'pricePrecision': price_precision, 'quantityPrecision': quantity_precision, 'minQuantity': min_quantity, 'maxQuantity': max_quantity, 'status': status })
def set_up(client_mgr, members): postman_client = client_mgr.new_client(POSTMAN_PARTY) postman_client.on_ready( lambda _, __: create('Main.PostmanRole', dict(postman=POSTMAN_PARTY))) postman_client.on_created( 'Main.PostmanRole', lambda cid, cdata: [cid.exercise('InviteParticipant', m) for m in members])
async def test_select_reflects_archive_events(sandbox): notification_count = 3 # we expect that, upon each on_created notification of an OperatorNotification contract, # when we query the ACS, we get precisely the same number of contracts. expected_select_count = notification_count * notification_count actual_select_count = 0 def on_notification_contract(event): nonlocal actual_select_count actual_select_count += len(event.acs_find_active(OperatorNotification)) async with async_network(url=sandbox, dars=Simple) as network: client = network.aio_new_party() client.add_ledger_ready( lambda e: create(OperatorRole, {'operator': client.party})) client.add_ledger_created( OperatorRole, lambda e: exercise(e.cid, 'PublishMany', dict(count=3))) client.add_ledger_created(OperatorNotification, lambda e: exercise(e.cid, 'Archive')) client.add_ledger_created(OperatorNotification, on_notification_contract) network.start() final_select_count = len(client.find_active(OperatorNotification)) assert actual_select_count == expected_select_count assert 0 == final_select_count
def handle_order_cancel_request(event): order = event.cdata['order'] return create(EXBERRY.CancelOrderRequest, { 'integrationParty': client.party, 'instrument': make_instrument(order['pair']), 'mpOrderId': order['orderId'], 'userId': make_user_user_id(order['exchParticipant']) })
def create_initial_state(event: "ReadyEvent"): try: LOG.info("Uploading our DAR...") event.client.ensure_dar(PostOffice) LOG.info("DAR uploaded. Creating the initial postman role contract...") return create("Main:PostmanRole", dict(postman=event.party)) except: LOG.exception("Failed to set up our initial state!")
def run(self, url): network = Network() network.set_config(url=url) operator = network.aio_party(OPERATOR_PARTY) operator.add_ledger_ready(lambda _: create(Simple.OperatorRole, {'operator': OPERATOR_PARTY})) operator.add_ledger_created(Simple.OperatorRole, self.on_operator) operator.add_ledger_created(Simple.OperatorNotification, self.on_notification) network.run_until_complete(asyncio.sleep(15))
async def init(event: ReadyEvent): assets = event.acs_find_active( 'Main.DonorConfig', match=lambda cdata: cdata['owner'] == owner) if len(assets) == 0: logging.info("Initializing DonorConfig for " + owner) return dazl.create('Main.DonorConfig', { 'owner': owner, 'donateTo': 'Alice' })
async def handle_order_cancel_request(event): cancel_request = event.cdata return create( EXBERRY.CancelOrderRequest, { 'integrationParty': client.party, 'instrument': cancel_request['details']['listingId'], 'mpOrderId': cancel_request['details']['id'], 'userId': make_user_user_id(cancel_request['provider']) })
def run(self, url): with create_client(participant_url=url, parties=ALL_PARTIES) as client_manager: operator = client_manager.client(OPERATOR_PARTY) operator.on_ready(lambda *args, **kwargs: create( Simple.OperatorRole, {'operator': OPERATOR_PARTY})) operator.on_created(Simple.OperatorRole, self.on_operator) operator.on_created(Simple.OperatorNotification, self.on_notification) client_manager.run_until_complete(asyncio.sleep(15))
def run_app(url: str): client_role_dicts = get_client_role_data() all_parties = tuple(c["client"] for c in client_role_dicts) + ("Processor",) with create_client(participant_url=url, parties=all_parties) as client_mgr: for client_role_dict in client_role_dicts: client = client_mgr.client(client_role_dict["client"]) client.on_ready(lambda *args, **kwargs: create(ClientRole, client_role_dict)) register_processor_callbacks("Processor", client_mgr.client("Processor"))
def test_maps(self): with sandbox(TEST_DAML) as proc: with create_client(participant_url=proc.url, parties=[PARTY]) as client: party_client = client.client(PARTY) party_client.on_ready(lambda *args, **kwargs: create( 'AllKindsOf.MappyContract', { 'operator': PARTY, 'value': {'Map_internal': []} })) client.run_until_complete()
def run_test(url): all_parties = [POSTMAN_PARTY] with create_client(parties=all_parties, participant_url=url) as client_mgr: postman_client = client_mgr.new_client(POSTMAN_PARTY) postman_client.on_ready( lambda _, __: create('Main.PostmanRole', dict(postman=POSTMAN_PARTY))) ledger_run = client_mgr.run_until_complete() return ledger_run.exit_code
def handle_clear_market(event): sid = get_sid() pair = event.cdata['pair'] commands = [] instrument = "" if event.cdata['clearedMarket']: logging.info(f"resetting cleared market...") orders = client.find_active(MARKETPLACE.ClearedOrder) for (order_cid, order) in orders.items(): if order['pair'] == pair: commands.append(exercise(order_cid, "ClearedOrder_Cancel")) cancel_requests = client.find_active( MARKETPLACE.ClearedOrderCancelRequest) for (req_cid, req) in cancel_requests.items(): if req['order']['pair'] == pair: commands.append( exercise(req_cid, "ClearedOrderCancelRequest_Reject")) order_requests = client.find_active( MARKETPLACE.ClearedOrderRequest) for (req_cid, req) in order_requests.items(): if req['order']['pair'] == pair: commands.append( exercise(req_cid, "ClearedOrderRequest_Reject")) instrument = make_instrument(pair, True) else: logging.info(f"resetting regular market...") orders = client.find_active(MARKETPLACE.Order) for (order_cid, order) in orders.items(): if order['pair'] == pair: commands.append(exercise(order_cid, "Order_Cancel")) cancel_requests = client.find_active( MARKETPLACE.OrderCancelRequest) for (req_cid, req) in cancel_requests.items(): if req['order']['pair'] == pair: commands.append( exercise(req_cid, "OrderCancelRequest_Reject")) order_requests = client.find_active(MARKETPLACE.OrderRequest) for (req_cid, req) in order_requests.items(): if req['order']['pair'] == pair: commands.append(exercise(req_cid, "OrderRequest_Reject")) instrument = make_instrument(pair) commands.append( create( EXBERRY.MassCancelRequest, { 'integrationParty': client.party, 'sid': sid, 'instrument': instrument })) commands.append(exercise(event.cid, "ResetMarketRequest_Ack")) return commands
def handle_cleared_order_cancel_request(event): logging.info(f"Handling ClearedOrderCancelRequest") order = event.cdata['order'] return create( EXBERRY.CancelOrderRequest, { 'integrationParty': client.party, 'instrument': make_instrument(order['pair'], True), 'mpOrderId': order['orderId'], 'userId': make_user_user_id(order['exchParticipant']) })
async def test_some_party_receives_public_contract(sandbox): some_party_cids = [] publisher_cids = [] # TODO: Switch to a Party allocation API when available. all_party = Party(str(uuid.uuid4())) async with async_network(url=sandbox, dars=AllPartyDar) as network: network.set_config(party_groups=[all_party]) some_client = network.aio_new_party() some_client.add_ledger_ready(lambda _: create( PrivateContract, {"someParty": some_client.party})) publisher_client = network.aio_new_party() publisher_client.add_ledger_ready( lambda _: create(PublicContract, { "publisher": publisher_client.party, "allParty": all_party })) some_client.add_ledger_created(PublicContract, lambda e: some_party_cids.append(e.cid)) some_client.add_ledger_created(PrivateContract, lambda e: some_party_cids.append(e.cid)) publisher_client.add_ledger_created( PublicContract, lambda e: publisher_cids.append(e.cid)) publisher_client.add_ledger_created( PrivateContract, lambda e: publisher_cids.append(e.cid)) network.start() logging.info( "got to the end with some_party contracts: %s and publisher contracts: %s", some_party_cids, publisher_cids, ) assert len(some_party_cids) == 2 assert len(publisher_cids) == 1
async def handle_cancel_order_msg(msg: dict): if 'd' in msg and 'orderId' in msg['d']: LOG.info( f'Received cancel order acknowledgement, creating {EXBERRY.CancelOrderSuccess}' ) return create(EXBERRY.CancelOrderSuccess, { 'integrationParty': env.party, 'sid': msg['sid'] }) elif 'errorType' in msg: msg_data = msg['d'] LOG.info( f'Received cancel order failure, creating {EXBERRY.CancelOrderFailure}' ) return create( EXBERRY.CancelOrderFailure, { 'integrationParty': env.party, 'sid': msg['sid'], 'errorCode': msg_data['errorCode'], 'errorMessage': msg_data['errorMessage'], })
def register_event_handlers(client_mgr): """ Register event handlers with the appropriate clients. """ # initial workflow state (1 of 3): "InviteParticipantsInProgress" # Define a ledger client associated with the 'Operator' party, and how it reacts to events operator_client = client_mgr.new_client("Operator") operator_client.on_created("WorkflowStateExample.GenesisContract", create_initial_workflow_state) operator_client.on_created("WorkflowStateExample.GenesisContract", invite_ticket_seller) operator_client.on_created("WorkflowStateExample.GenesisContract", invite_ticket_buyer) # define a ledger client associated with the ticket seller, and how it reacts to events bob_client = client_mgr.new_client(bob) bob_client.on_created("WorkflowStateExample.TicketSellerInvitation", accept_ticket_seller_invite) # define a ledger client associated with the ticket buyer, and how it reacts to events alice_client = client_mgr.new_client(alice) alice_client.on_created("WorkflowStateExample.TicketBuyerInvitation", accept_ticket_buyer_invite) # transition to workflow state: "TicketTransactionsInProgress" operator_client.on_created( "WorkflowStateExample.WorkflowSetupInProgress", transition_to_ticket_transactions_in_progress, ) # workflow state (2 of 3): "TicketTransactionsInProgress" bob_client.on_created("WorkflowStateExample.TicketSellerRole", offer_ticket_purchase_agreement) # alice purchases a ticket alice_client.on_created( "WorkflowStateExample.TicketPurchaseAgreementOffer", purchase_ticket) alice_client.on_created("WorkflowStateExample.TicketPurchaseAgreement", save_purchase_agreement) # transition to workflow state (3 of 3): "WorkflowCompleted" operator_client.on_created( "WorkflowStateExample.WorkflowTicketTransactionsInProgress", transition_to_workflow_completed, ) # all event handlers are defined; create the genesis contract, and all other event handlers shall react thereafter operator_client.submit([ create("WorkflowStateExample.GenesisContract", {"operator": "Operator"}) ])
async def init(event: ReadyEvent): pings = event.acs_find_active( 'PingPong.Ping', match=lambda cdata: cdata['sender'] == sender) pongs = event.acs_find_active( 'PingPong.Pong', match=lambda cdata: cdata['receiver'] == sender) if len(pings) == 0 and len(pongs) == 0: logging.info("Initializing Ping for " + sender) return dazl.create('PingPong.Ping', { 'sender': sender, 'receiver': receiver, 'count': 0 })
def create_initial_state(event: 'ReadyEvent'): try: LOG.info('Uploading our DAR...') event.client.ensure_dar(PostOffice) while not event.package_store.resolve_template('Main:PostmanRole'): logging.info("Waiting for our DAR to be uploaded...") sleep(1) LOG.info('DAR uploaded. Creating the initial postman role contract...') return create('Main:PostmanRole', dict(postman=event.party)) except: LOG.exception('Failed to set up our initial state!')
def test_select_unknown_template_retrieves_empty_set(self): with sandbox(DAML_FILE) as proc: with create_client(participant_url=proc.url, parties=[PARTY]) as client: party_client = client.client(PARTY) party_client.on_ready(lambda *args, **kwargs: create( OperatorRole, {'operator': PARTY})) client.run_until_complete() data = party_client.select('NonExistentTemplate') self.assertEqual(len(data), 0)
def test_select_unknown_template_retrieves_empty_set(self): with sandbox(Simple) as proc: network = Network() network.set_config(url=proc.url) party_client = network.aio_party(PARTY) party_client.add_ledger_ready( lambda e: create(OperatorRole, {'operator': PARTY})) network.run_until_complete() data = party_client.find_active('NonExistentTemplate') self.assertEqual(len(data), 0)
def test_some_party_receives_public_contract(self): some_party_cids = [] publisher_cids = [] with sandbox(DAML_FILE, extra_args=None) as proc: with create_client(participant_url=proc.url, parties=[SOME_PARTY, PUBLISHER], party_groups=[ALL_PARTY]) as client: some_client = client.client(SOME_PARTY) some_client.on_ready(lambda *args, **kwargs: create(PrivateContract, {'someParty': SOME_PARTY})) publisher_client = client.client(PUBLISHER) publisher_client.on_ready(lambda *args, **kwargs: create(PublicContract, {'publisher': PUBLISHER, 'allParty': ALL_PARTY})) some_client.on_created(PublicContract, lambda cid, cdata: some_party_cids.append(cid)) some_client.on_created(PrivateContract, lambda cid, cdata: some_party_cids.append(cid)) publisher_client.on_created(PublicContract, lambda cid, cdata: publisher_cids.append(cid)) publisher_client.on_created(PrivateContract, lambda cid, cdata: publisher_cids.append(cid)) client.run_until_complete() print(f'got to the end with some_party contracts: {some_party_cids} and publisher contracts: {publisher_cids}') self.assertEqual(len(some_party_cids), 2) self.assertEqual(len(publisher_cids), 1)
def _sandbox_test(self, extra_args=None): cids = [] with sandbox(Simple, extra_args=extra_args) as proc: network = Network() network.set_config(url=proc.url) party_client = network.aio_party(PARTY) party_client.add_ledger_ready(lambda _: create(OperatorRole, {'operator': PARTY})) party_client.add_ledger_created(OperatorRole, lambda e: cids.append(e.cid)) network.run_until_complete() print('got to the end with contracts: ', cids) self.assertEqual(len(cids), 1)