Skip to content

Commit

Permalink
Merge pull request #184 from cardanoapi/enhancement/metadata-hash
Browse files Browse the repository at this point in the history
Enhancement/metadata hash
  • Loading branch information
mesudip authored Sep 16, 2024
2 parents 8107c06 + 5b81419 commit 036f8c4
Show file tree
Hide file tree
Showing 24 changed files with 143 additions and 63 deletions.
14 changes: 12 additions & 2 deletions agent-node/src/functions/delegation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,17 @@ export default async function handler(
return await context.wallet
.buildAndSubmit(req, true)
.then((v) => v)
.catch((e) => {
throw e
.catch(async (e) => {
if (e.includes('StakeKeyNotRegisteredDELEG')) {
await context.builtins.registerStake()
return context.wallet
.buildAndSubmit(req, true)
.then((v) => v)
.catch((e) => {
throw e
})
} else {
throw e
}
})
}
17 changes: 10 additions & 7 deletions api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@
# Allowed Values : development , production
APP_ENV=production

DATABASE_URL=postgresql://root:root@localhost:5432/cardano_autonomous_agent_testing_db
DATABASE_URL=
AGENT_MNEMONIC=""
KAFKA_BROKERS=
KAFKA_ENABLED=true
DOCS_URL=/api/docs
OPENAPI_URL=/api/openapi.json

# Service can un without Kafka but Manual Triggers are disabled.
KAFKA_BROKERS=127.0.0.1:9002
KAFKA_ENABLED=true

KUBER_URL='https://kuber-govtool.cardanoapi.io/api/v3'
KUBER_URL=

JWT_SECRET_KEY=""

AGENT_MNEMONIC="abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art"
JWT_SECRET_KEY="1234567890"
METADATA_API=''
GOV_ACTION_API=''
27 changes: 27 additions & 0 deletions api/backend/app/controllers/internal/metadata_router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import aiohttp
from classy_fastapi import Routable, get

from backend.app.exceptions import HTTPException
from backend.config.api_settings import APISettings


class MetadataRouter(Routable):

def __init__(self):
super().__init__()
self.metadata_api = APISettings().METADATA_API

@get("/metadata")
async def fetch_metadata(self, metadata_url: str):
async with aiohttp.ClientSession() as session:
async with session.get(
f"{self.metadata_api}/metadata?url={metadata_url}&hash=1111111111111111111111111111111111111111111111111111111111111112"
) as resp:
response = await resp.json()
if resp.ok:
if response.get("hash"):
return response.get("hash")
else:
raise HTTPException(status_code=400, content=response.get("message"))
else:
raise HTTPException(status_code=400, content=response.get("message"))
6 changes: 4 additions & 2 deletions api/backend/app/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from fastapi import APIRouter

from backend.app.controllers.internal import proposal_router, drep_router
from backend.app.controllers.internal import proposal_router, drep_router, metadata_router
from backend.app.controllers import (
ready,
demo,
Expand Down Expand Up @@ -57,6 +57,8 @@
root_api_router.include_router(auth_router.AuthRouter().router, tags=["Authentication"], prefix="/auth")


root_api_router.include_router(proposal_router.ProposalRouter().router, tags=["Porposal Router"])
root_api_router.include_router(proposal_router.ProposalRouter().router, tags=["Proposal Router"])

root_api_router.include_router(drep_router.DrepRouter().router, tags=["Drep Router"])

root_api_router.include_router(metadata_router.MetadataRouter().router, tags=["Metadata Router"])
1 change: 1 addition & 0 deletions api/backend/config/api_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ class APISettings(BaseSettings):
SECURE: bool = None
JWT_SECRET_KEY: str = ""
GOV_ACTION_API: str = "https://govtool.cardanoapi.io/api"
METADATA_API: str = ""

def __init__(self, **values):
super().__init__(**values)
Expand Down
8 changes: 4 additions & 4 deletions frontend/next.config.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import nextPwa from "next-pwa";
import runtimeCaching from "next-pwa/cache.js";
import nextPwa from 'next-pwa';
import runtimeCaching from 'next-pwa/cache.js';

import { withSentryConfig } from "@sentry/nextjs";
import { withSentryConfig } from '@sentry/nextjs';

import i18nextConfig from "./next-i18next.config.js";
import i18nextConfig from './next-i18next.config.js';

const i18n = i18nextConfig.i18n;

Expand Down
1 change: 0 additions & 1 deletion frontend/src/app/(pages)/agents/[agentID]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ export default function AgentPageById() {
useEffect(() => {
if (agent) {
setCurrentAgentName(agent?.name || '');
console.log(agent.userAddress, currentConnectedWallet?.address);
agent.userAddress === currentConnectedWallet?.address
? setAgentOwnerIsUser(true)
: setAgentOwnerIsUser(false);
Expand Down
2 changes: 0 additions & 2 deletions frontend/src/app/(pages)/agents/create-agent/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ export default function CreateAgentForm() {
router.push('/agents');
},
onError: () => {
console.log('Error Response');
setSubmittingForm(false);
ErrorToast('Error while creating Agent. Try Again!');
}
Expand Down Expand Up @@ -131,7 +130,6 @@ export default function CreateAgentForm() {
ref={multiSelectorRef}
onChange={(option: IOption) => {
setSelected([option]);
console.log(selected[0]);
form.setValue(
'agentTemplate',
option.value
Expand Down
6 changes: 0 additions & 6 deletions frontend/src/app/(pages)/templates/create-template/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ export default function TemplateForm() {
const [selected, setSelected] = useState<ITemplateOption[]>([]);

function openSelectedOption(option: ITemplateOption) {
console.log(option);
setCurrentDialogForm(option);
toggleDialog();
}
Expand All @@ -113,10 +112,6 @@ export default function TemplateForm() {
}
}, [functions]);

useEffect(() => {
console.log(selected);
}, [selected]);

/* Related to saving parameter fromt the dialog popup*/
function updateSelected({
inputType,
Expand Down Expand Up @@ -158,7 +153,6 @@ export default function TemplateForm() {
const router = useRouter();

function onSubmit(formData: z.infer<typeof templateFormSchema>) {
console.log(formData);
setSubmittingForm(true);
templateMutation.mutateAsync(formData);
}
Expand Down
11 changes: 11 additions & 0 deletions frontend/src/app/api/metaData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { baseAPIurl } from './config';

export async function fetchMetadataHash(url: string) {
const encodedUri = encodeURIComponent(url);
const res = await fetch(`${baseAPIurl}/metadata?metadata_url=${encodedUri}`);
if (res.ok) {
return await res.json();
} else {
throw new Error(await res.json());
}
}
1 change: 0 additions & 1 deletion frontend/src/app/api/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,6 @@ export const deleteTemplatebyID = async (templateID: string) => {
const response = await axios.delete(`${baseAPIurl}/templates/${templateID}`, {
withCredentials: true
});
console.log(response);
if (response.status === 204) {
return true;
} else {
Expand Down
1 change: 0 additions & 1 deletion frontend/src/app/api/triggerHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ export const fetchAllTriggerHistory = async ({
const encodedURL = encodeURI(fetchURL);

const res = await fetch(encodedURL);
console.log(fetchURL);

if (!res.ok) {
throw new Error('Trigger Fetch Failed: Network Error');
Expand Down
5 changes: 2 additions & 3 deletions frontend/src/assets/css/tailwind.css
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@
@apply focus-visible:!outline-none focus-visible:!ring-0 focus-visible:!ring-offset-0 active:!border-none;
}


.pagination-btn-position {
@apply absolute bottom-8 right-10
}
@apply absolute bottom-8 right-10;
}
3 changes: 1 addition & 2 deletions frontend/src/components/Agent/AgentOverview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,8 @@ const AgentOverViewComponent = ({
instance: agentInstance,
agentConfigurations: updatedAgentConfigs
})
.then((res) => {
.then(() => {
setIsEditing(false);
console.log(res);
});
};

Expand Down
20 changes: 12 additions & 8 deletions frontend/src/components/Agent/FormRenderer/FormRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ const FormRenderer = ({
}
});
const handleTrigger = async () => {
const errorIndexes = checkIfRequiredFieldIsEmpty(selectedFunction?.parameters);
const errorIndexes = await checkIfRequiredFieldIsEmpty(
selectedFunction?.parameters
);
setErrorIndex(errorIndexes);
if (!errorIndexes.length) {
const params = extractAnswerFromForm(selectedFunction);
Expand All @@ -61,14 +63,16 @@ const FormRenderer = ({
}
};

function checkIfRequiredFieldIsEmpty(params?: Array<IParameter>) {
async function checkIfRequiredFieldIsEmpty(params?: Array<IParameter>) {
const errorIndexes: number[] = [];
params?.forEach((param, paramIndex) => {
const isParamFieldsValid = validateForDifferentType(param);
if (!isParamFieldsValid) {
errorIndexes.push(paramIndex);
}
});
await Promise.all(
params!.map(async (param, index) => {
const isValid = await validateForDifferentType(param);
if (!isValid) {
errorIndexes.push(index);
}
})
);
return errorIndexes;
}

Expand Down
17 changes: 13 additions & 4 deletions frontend/src/components/Agent/FormRenderer/ObjectParameter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,17 @@ const ObjectParameter = ({

useEffect(() => {
if (errorIndex.includes(paramIndex)) {
const errorText = checkIfToFillAnyOneField(parameter)
? 'Please fill any one field'
: 'Please fill all required fields.';
let errorText = '';
if (
(parameter.id === 'anchor' || parameter.id === 'newConstitution') &&
parameter.parameters![0].errorMsg
) {
errorText = parameter.parameters![0].errorMsg;
} else {
errorText = checkIfToFillAnyOneField(parameter)
? 'Please fill any one field'
: 'Please fill all required fields.';
}
setErrorMsg(errorText);
}
}, [errorIndex]);
Expand Down Expand Up @@ -92,7 +100,8 @@ const ObjectParameter = ({
type={param.type === 'number' ? 'number' : 'text'}
/>
</div>
{errorMsg && !param.value && (
{(param.errorMsg ||
(!param.optional && errorMsg && !param.value)) && (
<span className={'text-xs text-red-500'}>
{errorMsg}
</span>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ const AgentManualTriggerModalView = ({
closeModal();
},
onError: () => {
console.log('Error Response');
ErrorToast('Error while manually triggering Agent Function. Try Again!');
}
});
Expand Down
1 change: 0 additions & 1 deletion frontend/src/components/molecules/SelectedCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ export default function SelectedCard({
handleUnselect = () => {
console.log('Handle unselect');
},
// handleEdit = () => console.log('Handle Edit'),
description
}: {
name: string;
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/models/types/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ interface IParameter {
description: string;
optional: boolean;
data_type: string;
value?: string;
value?: any;
}
export interface IAgentTrigger {
function_name: AgentTriggerFunctionType;
Expand Down
20 changes: 13 additions & 7 deletions frontend/src/models/types/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export interface IParameter {
parameters?: IParameter[];
items?: ItemObject[];
value?: any;
errorMsg?: string;
}

export interface IParameterOption {
Expand Down Expand Up @@ -150,7 +151,7 @@ export const AvailableFunctions: IFunctionsDto[] = [
{
id: 'dataHash',
name: 'Data Hash',
optional: false,
optional: true,
type: 'hash'
}
]
Expand Down Expand Up @@ -203,7 +204,8 @@ export const AvailableFunctions: IFunctionsDto[] = [
{
id: 'dataHash',
name: 'Data Hash',
type: 'hash'
type: 'hash',
optional: true
}
]
},
Expand All @@ -221,7 +223,7 @@ export const AvailableFunctions: IFunctionsDto[] = [
{
id: 'dataHash',
name: 'Data Hash',
optional: false,
optional: true,
type: 'hash'
}
]
Expand Down Expand Up @@ -253,7 +255,8 @@ export const AvailableFunctions: IFunctionsDto[] = [
{
id: 'dataHash',
name: 'Data Hash',
type: 'hash'
type: 'hash',
optional: true
}
]
}
Expand Down Expand Up @@ -300,7 +303,8 @@ export const AvailableFunctions: IFunctionsDto[] = [
{
id: 'dataHash',
name: 'Data Hash',
type: 'hash'
type: 'hash',
optional: true
}
]
}
Expand All @@ -324,7 +328,8 @@ export const AvailableFunctions: IFunctionsDto[] = [
{
id: 'dataHash',
name: 'Data Hash',
type: 'hash'
type: 'hash',
optional: true
}
]
}
Expand All @@ -349,7 +354,8 @@ export const AvailableFunctions: IFunctionsDto[] = [
{
id: 'dataHash',
name: 'Data Hash',
type: 'hash'
type: 'hash',
optional: true
}
]
},
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/store/atoms/formRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ import { atom } from 'jotai';

export const errorAtom = atom<Array<number>>([]);
export const selectedFunctionAtom = atom<IFunctionsItem | null>(null);

export const errorMessageAtom = atom<Array<Record<string, string>>>([]);
2 changes: 0 additions & 2 deletions frontend/src/utils/TriggerHistoryUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ export function calculateTriggerChangeRateforLast24Hours(
((last24HourSuccessTransactionsCount - prior24HourSuccessTransactionsCount) /
prior24HourSuccessTransactionsCount) *
100;
//console.log(`Last 24 hours ${last24HourSuccessTransactionsCount} , Total : ${totalTransactionsCount}`)
//console.log(`Change Rate : ${changeRate}`)
return changeRate;
}

Expand Down
Loading

0 comments on commit 036f8c4

Please sign in to comment.