# Multi chain Agent instance aka Rewriting the agent
## Scope
The goal would be to refactor the agent from outer parts towards internal structures.
First goal should be to reduce the number of RPC calls during event fetching.
## Architecture
### Current Architecture
```graphviz
digraph hierarchy {
nodesep=1.0 // increases the separation between nodes
A
B
node [color=Red,fontname=Courier,shape=box] //All nodes will this shape and colour
edge [color=Blue, style=dashed] //All the lines look like this
EF1 [label="EventFetcher",group=A1]
EF2 [label="EventFetcher", group=A1]
EP1 [label="EventProcessor A->B", group=A1]
A->{EF1, EF4}
B->{EF2, EF3}
EF1->{"EventMonitor (A,RM)"}
EF2->{"EventMonitor (B,FM)"}
"EventMonitor (A,RM)"->{EP1}
"EventMonitor (B,FM)"->{EP1}
EF3 [label="EventFetcher"] EF4 [label="EventFetcher"]
EP2 [label="EventProcessor B->A"]
EF3->{"EventMonitor (B,RM)"}
EF4->{"EventMonitor (A,FM)"}
"EventMonitor (B,RM)"->{EP2}
"EventMonitor (A,FM)"->{EP2}
{rank=same;} // Put them on the same level
}
```
Idea: Start Merging from Top (to Bottom, where needed).
## Rework Agent
```graphviz
digraph hierarchy {
nodesep=1.0 // increases the separation between nodes
A
B
node [color=Red,fontname=Courier,shape=box] //All nodes will this shape and colour
edge [color=Blue, style=dashed] //All the lines look like this
EF1 [label="EventFetcher"]
EF2 [label="EventFetcher"]
EP1 [label="EventProcessor A->B"]
EP2 [label="EventProcessor B->A"]
A->{EF1}
B->{EF2}
EF1->{"EventMonitor A"}
EF2->{"EventMonitor B"}
"EventMonitor A"->{EP1}
"EventMonitor B"->{EP1}
"EventMonitor B"->{EP2}
"EventMonitor A"->{EP2}
{rank=same;} // Put them on the same level
}
```
Start with Peripherals, leave internal state machine as is.
1) Merge EventFetchers per chain
* Already accepts multiple contracts
2) Extend EventMonitors
* Already accepts multiple contracts
* Needs some mechanism to distribute events correctly
### EventProcessor
* Event Processor = Main Thread of agent's business logic
* Two jobs: consuming events + outgoing actions
* State Machine Progress
* Sending Transactions (posting to the chains)
* Two Eventprocessors = Two Threads = Nonce Issue
* Option 1: Merging Event Processors
* Option 2: Outsource Transaction Module
* Option 1:
* Separation on context level
* Option 2:
* Separation on EP Level -> multiple event queues
#### Distribution/Filtering of events
* Previously filtering was done implicitly by the agent instances
* For Multiple EPs, EM needs to distribute
* For single EP, EP needs to filter for Context
* Or Events are applied to all contexts (prob. more inefficient but less complex?)