Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement/event based form integration #251

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion agent-node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"bech32": "^2.0.0",
"dotenv": "^16.4.5",
"kuber-client": "^2.0.0",
"libcardano": "1.4.2",
"libcardano": "1.4.4",
"luxon": "^3.4.4",
"node-cron": "^3.0.3",
"ws": "^8.18.0"
Expand Down
9 changes: 3 additions & 6 deletions agent-node/src/constants/global.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import { EventTriggerTypeDetails } from '../types/types'
import { IEventBasedAction } from '../types/eventTriger'

export const globalState: {
eventTriggerTypeDetails: EventTriggerTypeDetails
eventTypeDetails: IEventBasedAction[]
agentName: string
} = {
eventTriggerTypeDetails: {
eventType: false,
function_name: '',
},
eventTypeDetails: [],
agentName: '',
}

Expand Down
1 change: 1 addition & 0 deletions agent-node/src/executor/AgentRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export class AgentRunner {
method: string,
...args: any
) {

this.executor.invokeFunction(method, ...args).then((result) => {
saveTxLog(result, this.managerInterface, triggerType, instanceIndex)
})
Expand Down
124 changes: 124 additions & 0 deletions agent-node/src/service/EventTriggerHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { ManagerInterface } from './ManagerInterfaceService'
import { Transaction } from 'libcardano/cardano/ledger-serialization/transaction'
import { AgentRunner } from '../executor/AgentRunner'
import {
compareValue,
} from '../utils/validator'
import { IBooleanNode, IEventBasedAction, IFieldNode, IFilterNode } from "../types/eventTriger";
import { node } from "globals";

export class EventTriggerHandler {
eventBasedActions: IEventBasedAction[] = []
managerInterface: ManagerInterface
constructor(managerInterface: ManagerInterface) {
this.managerInterface = managerInterface
}

onBlock(transactions: Transaction[], agentRunners: AgentRunner[]) {
if (this.eventBasedActions.length) {
transactions.forEach((tx: Transaction) => {
this.eventBasedActions.forEach((eventBasedAction) => {
const handler = (this as any)[
(eventBasedAction.eventTrigger as IFieldNode).id + 'Handler'
]
if (handler !== undefined && handler !== 'constructor') {
handler.bind(this)(tx, eventBasedAction, agentRunners)
}
})
})
}
}

transactionHandler(
tx: Transaction,
eventBasedAction: IEventBasedAction,
agentRunners?: AgentRunner[]
) {
let result
try {
console.log("Tx:", tx.hash.toString('hex'), "tx.outputs=", tx.body.outputs.length, "inputs=", tx.body.inputs.length)
result = this.solveNode({ tx: tx.body, transaction: tx.body }, eventBasedAction.eventTrigger, [])
console.log("tx=", tx.hash.toString('hex'), "solution=", result)
}catch (e){
console.error("Error handling event",e);
return
}

const {function_name,parameters} = eventBasedAction.triggeringFunction
if (result && agentRunners) {
agentRunners.forEach((runner, index) => {
runner.invokeFunction(
'EVENT',
index,
function_name,
...parameters
)
})
}
}
solveNode(targetObject: any,filterNode: IFilterNode,parentNodes:string[]){
return this.solveNodeInternal(targetObject,filterNode,filterNode.id,parentNodes)
}
solveNodeInternal(targetObject: any,filterNode: IFilterNode,nodes:string[]|string|undefined,parent_nodes:string[]): boolean{

if(nodes ===undefined || nodes.length==0 ) {
let result= 'children' in filterNode ? this.solveBooleanNode(targetObject, filterNode, parent_nodes)
: this.solveFieldNode(targetObject, filterNode, parent_nodes)
return filterNode.negate?!result:result
}else if(typeof nodes==="string") {
nodes=[nodes]
}

let result
const propertyValue = targetObject[nodes[0]]
parent_nodes.push(nodes[0])

let subArray = nodes.slice(1)
if (Array.isArray(propertyValue)) {
const node_pos=parent_nodes.length
parent_nodes.push('')
result= propertyValue.reduce((acc, node,index:number) => {
if(acc){
return acc
}
parent_nodes[node_pos]=index.toString()
const result=this.solveNodeInternal(node, filterNode, subArray,parent_nodes)
console.log(parent_nodes.join('.'),": result=",result)
return result
}, false)
parent_nodes.pop()
} else {
result= this.solveNodeInternal(propertyValue, filterNode, subArray,parent_nodes)
}
parent_nodes.pop()
return result

}

solveBooleanNode(targetObject: any,filterNode: IBooleanNode,parent_nodes:string[]=[]): boolean{
let orOperator=(a:boolean,b:boolean)=> a || b
let operator=orOperator
if(filterNode.operator === 'AND'){
operator= (a:boolean,b:boolean)=> a && b
}
const result= filterNode.children.reduce((acc,node)=>{
return operator(acc,this.solveNodeInternal(targetObject,node,node.id,parent_nodes))
},operator !== orOperator)
console.log("id=",filterNode.id,"operator=",filterNode.operator,"result=",result)
return result
}

solveFieldNode(targetObject: any,filterNode: IFieldNode,parent_nodes:string[]) : boolean{

return compareValue(
filterNode.operator,
filterNode.value,
targetObject,
parent_nodes
)
}

addEventActions(actions: IEventBasedAction[]) {
this.eventBasedActions = actions
}
}
41 changes: 12 additions & 29 deletions agent-node/src/service/RpcTopicHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,22 @@ import { ManagerInterface } from './ManagerInterfaceService'
import { TxListener } from '../executor/TxListener'
import { BlockEvent } from 'libcardano/types'
import { parseRawBlockBody } from 'libcardano/cardano/ledger-serialization/transaction'
import { globalState } from '../constants/global'
import { clearScheduledTasks, scheduleFunctions } from '../utils/scheduler'
import {
checkIfAgentWithEventTriggerTypeExists,
createActionDtoForEventTrigger,
} from '../utils/agent'
import { checkIfAgentWithEventTriggerTypeExists } from '../utils/agent'
import { ScheduledTask } from 'node-cron'
import { AgentRunner } from '../executor/AgentRunner'
import { EventTriggerHandler } from './EventTriggerHandler'

export class RpcTopicHandler {
managerInterface: ManagerInterface
txListener: TxListener
eventTriggerHandlers: EventTriggerHandler
constructor(managerInterface: ManagerInterface, txListener: TxListener) {
this.managerInterface = managerInterface
this.txListener = txListener
this.eventTriggerHandlers = new EventTriggerHandler(
this.managerInterface
)
}
handleEvent(
eventName: string,
Expand All @@ -42,37 +43,19 @@ export class RpcTopicHandler {
'txCount=' + transactions.length
)
this.txListener.onBlock({ ...block, body: transactions })
if (
globalState.eventTriggerTypeDetails.eventType &&
transactions.length
) {
transactions.forEach((tx: any) => {
if (Array.isArray(tx.body.proposalProcedures)) {
tx.body.proposalProcedures.forEach(
(proposal: any, index: number) => {
const { function_name, parameters } =
createActionDtoForEventTrigger(tx, index)
agentRunners.forEach((runner, index) => {
runner.invokeFunction(
'EVENT',
index,
function_name,
...(parameters as any)
)
})
}
)
}
})
}
this.eventTriggerHandlers.onBlock(transactions, agentRunners)
}
initial_config(
message: any,
agentRunners: Array<AgentRunner>,
scheduledTasks: ScheduledTask[]
) {
const { configurations } = message
checkIfAgentWithEventTriggerTypeExists(configurations)
const eventBasedActions =
checkIfAgentWithEventTriggerTypeExists(configurations)
if (eventBasedActions) {
this.eventTriggerHandlers.addEventActions(eventBasedActions)
}
agentRunners.forEach((runner, index) => {
scheduleFunctions(
this.managerInterface,
Expand Down
25 changes: 25 additions & 0 deletions agent-node/src/types/eventTriger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Action } from '../service/triggerService'

export type BooleanOperator = 'AND' | 'OR'
export type ComparisonOperator = 'equals' | 'greaterThan' | 'lessThan' | 'in'

export interface IEventBasedAction {
eventTrigger: IBooleanNode | IFieldNode
triggeringFunction: Action
}

export interface IFieldNode {
id: string | string[]
value: any
negate: boolean
operator: ComparisonOperator
}

export interface IBooleanNode {
id?:string|string[]
children: IFilterNode[]
negate: boolean
operator: BooleanOperator
}

export type IFilterNode = IFieldNode | IBooleanNode
5 changes: 0 additions & 5 deletions agent-node/src/types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,3 @@ export type AgentWalletDetails = {
payment_verification_key_hash: string
drep_id: string
}

export type EventTriggerTypeDetails = {
eventType: boolean
function_name: string
}
14 changes: 8 additions & 6 deletions agent-node/src/utils/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import {
Configuration,
TriggerType,
} from '../service/triggerService'
import { globalState } from '../constants/global'
import { ManagerInterface } from '../service/ManagerInterfaceService'
import { CallLog } from '../executor/Executor'
import { ILog, InternalLog } from '../service/TriggerActionHandler'
import { DateTime } from 'luxon'
import { IEventBasedAction, IFilterNode } from "../types/eventTriger";

export function getParameterValue(
parameters: ActionParameter[] = [],
Expand All @@ -21,19 +21,21 @@ export function getParameterValue(
export function checkIfAgentWithEventTriggerTypeExists(
configurations: Configuration[]
) {
const eventBasedAction: IEventBasedAction[] = []
configurations.forEach((config) => {
if (config.type === 'EVENT') {
globalState.eventTriggerTypeDetails = {
eventType: true,
function_name: config.action.function_name,
}
eventBasedAction.push({
eventTrigger: config.data as unknown as IFilterNode,
triggeringFunction: config.action,
})
}
})
return eventBasedAction.flat()
}

export function createActionDtoForEventTrigger(tx: any, index: number): Action {
return {
function_name: globalState.eventTriggerTypeDetails.function_name,
function_name: 'voteOnProposal',
parameters: [
{
name: 'proposal',
Expand Down
23 changes: 23 additions & 0 deletions agent-node/src/utils/cardano.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,29 @@ export function rewardAddressBech32(
)
}

export function convertToBufferIfBech32(address: any): Buffer | string| any {
if (!address) return ''
else if (typeof address !== 'string') return address
else if (
address.includes('stake') ||
address.includes('drep') ||
address.includes('addr')
) {
const decoded = bech32.decode(address, 1000)
const data = bech32.fromWords(decoded.words)
return Buffer.from(data)
}
return address
}

export function convertToHexIfBech32(address: string): string {
const bufferVal = convertToBufferIfBech32(address)
if (Buffer.isBuffer(bufferVal)) {
return bufferVal.toString('hex')
}
return bufferVal
}

export function loadRootKeyFromBuffer() {
const rootKeyBuffer = globalRootKeyBuffer.value
if (!rootKeyBuffer) {
Expand Down
Loading
Loading