Package: pyogmios
PyOgmiosPython implementation of Ogmios ClientWhat is PyOgmios?PyOgmiosis based onOgmiosJSON/RPC lightweight bridge interface
forCardano NodebyMatthias Benkort.It offers aWebSocket APIthat enables local clients to
speakOuroboros' mini-protocolsviaJSON/RPC.OverviewPyOgmiosis a Python library that can be used to convert Python Objects into theirOgmiosRequestsJSON/RPCrepresentation. It can also be used to convertOgmios JSON/RPCResponses to their equivalent Python objects.The Python library allows asynchronous communication withOgmiosServer by interacting with a Websocket client
connection.BackgroundThe standard Ogmios interface uses a websocket and Json WSP messages. While this is good for exposing the node's
information to a lot of different programming environments, there is a lot of boilerplate code to write in each language
to convert json wsp messages into usable objects. This is wherePyOgmioscomes in for the Python language.The api is broken up into using 4 different logical client types:StateQuery,TxSubmit,TxMonitor, andChainSync.FeaturesAsynchronous messaging using Python objectsTransaction submission with enhanced error messagesTransaction EvaluationStructured Python Objects loggingFull ledger state query support:QueryResultSupportedblock_heightThe chain's highest block number.:heavy_check_mark:chain_tipThe chain's current tip.:heavy_check_mark:current_epochThe current epoch of the ledger.:heavy_check_mark:current_protocol_parametersThe current protocol parameters.:heavy_check_mark:delegations_and_rewardsCurrent delegation settings and rewards of given reward accounts.:heavy_check_mark:era_startThe information regarding the beginning of the current era.:heavy_check_mark:era_summariesEra bounds and slotting parameters details, required for proper slot arithmetic.:heavy_check_mark:genesis_configGet a compact version of the era's genesis configuration.:heavy_check_mark:ledger_tipThe most recent block tip known of the ledger.:heavy_check_mark:non_myopic_member_rewardsNon-myopic member rewards for each pool. Used in ranking.:heavy_check_mark:pool_idsThe list of all pool identifiers currently registered and active.:heavy_check_mark:pool_parametersStake pool parameters submitted with registration certificates.:heavy_check_mark:pools_rankingRetrieve stake pools ranking (a.k.a desirability).:heavy_check_mark:proposed_protocol_parametersThe last update proposal w.r.t. protocol parameters, if any.:heavy_check_mark:rewards_provenanceGet details about rewards calculation for the ongoing epoch.:heavy_check_mark:stake_distributionDistribution of the stake across all known stake pools.:heavy_check_mark:system_startThe chain's start time (UTC).:heavy_check_mark:utxoCurrent UTXO, possibly filtered by output reference.:heavy_check_mark:Getting StartedpipinstallpyogmiosSetupIn order to usePyOgmios, you will need to have a running instance of Ogmios pointed at an active instance of
cardano-node. Please refer to the Ogmios documentation for setup instructions.On thePyOgmiosside, all you will need is the ip/dns name of the Ogmios server as well as the port it is running
on (
default: 1337).Hosted Dandelion's instances, byGimbalabs.NetworkURLMainnetwss://ogmios-api.mainnet.dandelion.link/Testnetwss://ogmios-api.testnet.dandelion.link/UsageBelow, you will find a few example usages of thePyOgmiosapi. To find more exhaustive examples, refer to the
example code
in this repository.When you are done using aPyOgmiosclient, you should clean up and call theshutdown()method explicitly, OR you
can initialize theInteractionContextwithInteractionType.ONE_TIMEto ensure clean up happens automatically. This
latter approach is what we will use in the examples.All methods must be called from inside a Coroutine Context. The client methods will suspend until data returns from the
server, or an exception is thrown. Many calls can be made throughPyOgmiosusing the same Client object. Only clean
it up once you are done with it, or it has thrown an error. In the case of errors, it is best to create a new instance
of the Client, so it can re-connect.StateQueryTheStateQueryclient is used for querying the current (or past) state of the node and blockchain. In most cases,
the api will automatically acquire the tip of the blockchain. You should not need to explicitly callacquire(point)unless you have advanced needs.ChainTip Example:importasynciofrompyogmios_client.connectionimport(create_interaction_context,InteractionContextOptions,)frompyogmios_client.enumsimportInteractionTypefrompyogmios_client.ouroboros_mini_protocols.state_query.state_query_clientimportcreate_state_query_clientasyncdefmain():"""This will query the chain tip of the node through Ogmios."""interaction_context_options=InteractionContextOptions(interaction_type=InteractionType.ONE_TIME)interaction_context=awaitcreate_interaction_context(options=interaction_context_options)client=awaitcreate_state_query_client(interaction_context)chain_tip=awaitclient.chain_tip()# await client.shutdown()print(chain_tip)if__name__=="__main__":loop=asyncio.get_event_loop()loop.run_until_complete(main())ChainSyncimportasynciofromtypingimportCallablefrompyogmios_client.connectionimport(create_interaction_context,InteractionContextOptions,)frompyogmios_client.enumsimportInteractionType,Originfrompyogmios_client.modelsimportRollBackward,RollForwardfrompyogmios_client.ouroboros_mini_protocols.chain_sync.chain_sync_clientimportChainSyncMessageHandlers,\create_chain_sync_clientasyncdefmain():"""This run the chain sync client and print the output."""interaction_context_options=InteractionContextOptions(interaction_type=InteractionType.LONG_RUNNING)interaction_context=awaitcreate_interaction_context(options=interaction_context_options)awaitasyncio.sleep(1)print(interaction_context.socket.sock.connected)defroll_backward_callback(roll_backward:RollBackward,callback:Callable[[],None]):"""Roll backward callback:param roll_backward: The roll backward result:param callback: The request next callback"""print(f"Roll backward:{roll_backward}")callback()defroll_forward_callback(roll_forward:RollForward,callback:Callable[[],None]):"""Roll forward callback:param roll_forward: The roll forward result:param callback: The request next callback"""print(f"Roll forward:{roll_forward}")callback()chain_sync_message_handlers=ChainSyncMessageHandlers(roll_backward=roll_backward_callback,roll_forward=roll_forward_callback)chain_sync_client=awaitcreate_chain_sync_client(interaction_context,chain_sync_message_handlers)awaitchain_sync_client.start_sync([Origin.origin],0)awaitasyncio.sleep(10)awaitchain_sync_client.shutdown()if__name__=="__main__":loop=asyncio.get_event_loop()loop.run_until_complete(main())