Skip to content

Commit

Permalink
Merge pull request #192 from cardanoapi/enhancement/refactor-metadata…
Browse files Browse the repository at this point in the history
…-and-context

Enhancement/refactor metadata and context
  • Loading branch information
mesudip authored Sep 19, 2024
2 parents baa61c2 + 17123a2 commit ebd71df
Show file tree
Hide file tree
Showing 19 changed files with 400 additions and 391 deletions.
4 changes: 2 additions & 2 deletions agent-manager/src/service/AgentManagerRPC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ export class AgentManagerRPC extends WsRpcServer {
return data.reduce((totalVal: number, item: any) => totalVal + item.value.lovelace, 0) / 10 ** 6
})
} else if (method === 'saveMetadata') {
const [fileName, content] = args
return metaDataService.saveMetadata(fileName, content)
const [content] = args
return metaDataService.saveMetadata(content)
} else {
throw new Error('No such method exists')
}
Expand Down
8 changes: 5 additions & 3 deletions agent-manager/src/service/Metadata_service.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import environments from '../config/environments'
import * as blake from 'blakejs'

class MetadataService {
constructor() {}

async saveMetadata(filename: string, content: string) {
const res = await fetch(`${environments.metaDataBaseURL}/data/${filename}`, {
async saveMetadata(content: string) {
const hash = blake.blake2bHex(content, undefined, 32)
const res = await fetch(`${environments.metaDataBaseURL}/data/${hash}`, {
method: 'PUT',
body: content,
})
if (res.ok) {
return `${environments.metaDataBaseURL}/data/${filename}`
return { dataHash: hash, url: `${environments.metaDataBaseURL}/data/${hash}` }
} else {
throw new Error((await res.text()) || (await res.json()))
}
Expand Down
53 changes: 9 additions & 44 deletions agent-node/src/executor/BaseFunction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export interface Wallet {
address: string
paymentKey: Key
stakeKey: Key
// stakeAddress():string
rewardAddress: string
drepId: string
buildAndSubmit(spec: any, stakeSigning?: boolean): Promise<any>
signTx(txRaw: Buffer, stakeSigning?: boolean): Buffer
Expand Down Expand Up @@ -62,56 +62,21 @@ export interface Builtins {
data: Record<any, any> | any[] | string
) => Promise<any>
loadFunds: (amount: number) => Promise<any>
saveMetadata: (fileName: string, content: string) => Promise<any>

// DRep functions
// dRepRegistration(anchor?: OffchainData): Promise<any>
// dRepDeRegistration(): Promise<any>
// registerStake(): Promise<any>
// stakeDeRegistration(): Promise<any>
// abstainDelegation(target: DelegationTarget): Promise<any>
// waitTxConfirmation(
// txId: string,
// confirmation: number,
// timeout: number
// ): Promise<any>
// transferADA(
// address: string,
// amount: string | number | Record<string, any>
// ): Promise<any>
//
// // Vote functions
// voteOnProposal(proposal: string, anchor?: OffchainData): Promise<TxInfo>;
//
// // Proposal functions
// proposalNewConstitution(anchor: OffchainData, newConstitution: OffchainData): Promise<TxInfo>;
// createInfoGovAction(anchor: OffchainData): Promise<TxInfo>;
//
//
// treasuryWithdrawal(withdrawal: Array<{
// stakeAddress: string;
// amount: number;
// }>, anchor: OffchainData): Promise<TxInfo>;
// noConfidence(anchor:OffchainData): Promise<TxInfo>;
//
//
//
// updateCommittee(anchor: OffchainData, quorum: {
// numerator: number;
// denominator: number;
// }, add?: Array<{
// stakeAddress: string;
// activeEpoch: number;
// }>, remove?: Array<string>): Promise<TxInfo>;
//
saveMetadata: (content: string) => Promise<any>
}

// Others
export interface Helpers {
generateProposalMetadataContent: () => string
generateDrepMetadataContent: () => string
generateVoteMetadataContent: () => string
}

export interface FunctionContext {
wallet: Wallet
kuber: KuberApi
builtins: Builtins
agentName: string
helpers: Helpers
}

// Create a restricted execution environment
Expand Down
44 changes: 36 additions & 8 deletions agent-node/src/executor/Executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import { ManagerInterface } from '../service/ManagerInterfaceService'
import { FunctionGroup, getHandlers } from './AgentFunctions'
import { Builtins, FunctionContext, Key, Wallet } from './BaseFunction'
import { TxListener } from './TxListener'
import { generateProposalMetadataContent } from '../utils/metadataContent/proposalMetadataContent'
import { generateRegisterDrepMetadataContent } from '../utils/metadataContent/drepMetadataContent'
import { generateVoteMetadataContent } from '../utils/metadataContent/voteMetadataContent'
import { rewardAddressBech32 } from '../utils/cardano'

export interface CallLog {
function: string
Expand Down Expand Up @@ -37,8 +41,24 @@ export class Executor {
},
builtins: this.getBuiltins(wallet),
agentName: '',
helpers: this.getHelpers(wallet, ''),
}
}

getHelpers(wallet: any, agentName: string) {
const context = this.functionContext
return {
generateProposalMetadataContent: () =>
generateProposalMetadataContent(agentName),
generateDrepMetadataContent: () =>
generateRegisterDrepMetadataContent(
agentName,
wallet.paymentKey.private
),
generateVoteMetadataContent: () => generateVoteMetadataContent(),
}
}

makeWallet(walletDetails: AgentWalletDetails): Wallet {
const txSubmissionHold: any[] = []
let isProcessing: boolean = false
Expand All @@ -64,15 +84,21 @@ export class Executor {
throw new Error('Key.signRaw is not implemented')
},
}
const rewardAddress = rewardAddressBech32(
0,
walletDetails.stake_verification_key_hash
)
console.log(
'Account keys received : address =>',
walletDetails.agent_address
'Account keys received : addresses =>',
walletDetails.agent_address,
rewardAddress
)
return {
address: walletDetails.agent_address,
paymentKey: paymentKey,
stakeKey: stakeKey,
drepId: walletDetails.drep_id,
rewardAddress: rewardAddress,
buildAndSubmit: (spec: any, stakeSigning?: boolean) => {
spec.selections = [
walletDetails.agent_address,
Expand Down Expand Up @@ -147,6 +173,10 @@ export class Executor {
this.functionContext.wallet
)
this.functionContext.agentName = agentName
this.functionContext.helpers = this.getHelpers(
this.functionContext.wallet,
agentName
)
managerInterface
.getFaucetBalance(this.functionContext.wallet.address)
.then((balance) => {
Expand Down Expand Up @@ -211,6 +241,7 @@ export class Executor {
callLog: callLog,
}
}

getBuiltins(wallet: Wallet): Builtins {
const builtins = this.functions.builtins
const context = this.functionContext
Expand All @@ -233,13 +264,10 @@ export class Executor {
)
},
loadFunds: async (amount: number): Promise<any> => {
return await this.rpcInterface.loadFunds(
context.wallet.address,
amount
)
return await this.rpcInterface.loadFunds(wallet.address, amount)
},
saveMetadata: async (fileName, content) => {
return await this.rpcInterface.saveMetadata(fileName, content)
saveMetadata: async (content) => {
return await this.rpcInterface.saveMetadata(content)
},
...updatedBuiltins,
} as Builtins
Expand Down
85 changes: 6 additions & 79 deletions agent-node/src/functions/createInfoGovAction.ts
Original file line number Diff line number Diff line change
@@ -1,96 +1,23 @@
import { FunctionContext } from '../executor/BaseFunction'
import { rewardAddressBech32 } from '../utils/cardano'
import * as blake from 'blakejs'

export default async function handler(
context: FunctionContext,
anchor: Record<string, any>
) {
const metadata = JSON.stringify(generateProposalMetadata(context.agentName))
const hash = blake.blake2bHex(metadata, undefined, 32)
const url = await context.builtins.saveMetadata(hash, metadata)
const rewardAddress = rewardAddressBech32(
0,
context.wallet.stakeKey.pubKeyHash
const { dataHash, url } = await context.builtins.saveMetadata(
context.helpers.generateProposalMetadataContent()
)
const anchorData =
anchor['url'] && anchor['dataHash'] ? anchor : { url, dataHash }
const req = {
proposals: [
{
refundAccount: rewardAddress,
anchor: anchor || {
url,
dataHash: hash,
},
refundAccount: context.wallet.rewardAddress,
anchor: anchorData,
},
],
}
return await context.wallet.buildAndSubmit(req).catch((e) => {
throw e
})
}
function generateProposalMetadata(agentName: string) {
return {
'@context': {
CIP100: 'https://github.com/cardano-foundation/CIPs/blob/master/CIP-0100/README.md#',
CIP108: 'https://github.com/cardano-foundation/CIPs/blob/master/CIP-0108/README.md#',
hashAlgorithm: 'CIP100:hashAlgorithm',
body: {
'@id': 'CIP108:body',
'@context': {
references: {
'@id': 'CIP108:references',
'@container': '@set',
'@context': {
GovernanceMetadata:
'CIP100:GovernanceMetadataReference',
Other: 'CIP100:OtherReference',
label: 'CIP100:reference-label',
uri: 'CIP100:reference-uri',
referenceHash: {
'@id': 'CIP108:referenceHash',
'@context': {
hashDigest: 'CIP108:hashDigest',
hashAlgorithm: 'CIP100:hashAlgorithm',
},
},
},
},
title: 'CIP108:title',
abstract: 'CIP108:abstract',
motivation: 'CIP108:motivation',
rationale: 'CIP108:rationale',
},
},
authors: {
'@id': 'CIP100:authors',
'@container': '@set',
'@context': {
name: 'http://xmlns.com/foaf/0.1/name',
witness: {
'@id': 'CIP100:witness',
'@context': {
witnessAlgorithm: 'CIP100:witnessAlgorithm',
publicKey: 'CIP100:publicKey',
signature: 'CIP100:signature',
},
},
},
},
},
authors: [],
hashAlgorithm: 'blake2b-256',
body: {
abstract: `This proposal is created automatically by agent: ${agentName}`,
motivation:
'This proposal is automatically generated by autonomous-agent-testing',
references: [
{
'@type': 'Other',
label: 'autonomous-agent-testing',
uri: 'https://cardanoapi.github.io/autonomous-agents/archietecture_docusaurus/docs/architecture',
},
],
title: 'Automated Proposal by AAT',
},
}
}
Loading

0 comments on commit ebd71df

Please sign in to comment.