Skip to content

Commit

Permalink
chore(rwa): start with errors (#2674)
Browse files Browse the repository at this point in the history
  • Loading branch information
sstraatemans authored Nov 20, 2024
1 parent edcfbe0 commit a2010ad
Show file tree
Hide file tree
Showing 18 changed files with 1,210 additions and 3,559 deletions.
2 changes: 2 additions & 0 deletions .changeset/nasty-emus-compete.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,13 @@ export const AddAgentForm: FC<IProps> = ({ onClose }) => {
const { account, sign } = useAccount();
const { addTransaction } = useTransactions();
const [openModal, setOpenModal] = useState(false);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, setError] = useState<string | null>(null);
const { register, handleSubmit } = useForm<IAddAgentProps>({
defaultValues: {
agent: '',
accountName: '',
},
});

const onSubmit = async (data: IAddAgentProps) => {
setError(null);
try {
const tx = await addAgent(data, account!);

Expand All @@ -55,9 +52,7 @@ export const AddAgentForm: FC<IProps> = ({ onClose }) => {
data: { ...res, ...data },
});
console.log('DONE');
} catch (e: any) {
setError(e?.message || e);
}
} catch (e: any) {}

onClose();
};
Expand All @@ -80,7 +75,7 @@ export const AddAgentForm: FC<IProps> = ({ onClose }) => {
<RightAsideContent>
<TextField
label="Agent Account"
{...register('agent', { required: true })}
{...register('accountName', { required: true })}
/>
</RightAsideContent>
<RightAsideFooter>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useAccount } from '@/hooks/account';
import { useTransactions } from '@/hooks/transactions';
import type { IRegisterIdentityProps } from '@/services/registerIdentity';
import { registerIdentity } from '@/services/registerIdentity';
import { getClient } from '@/utils/client';
Expand All @@ -10,7 +11,6 @@ import {
RightAsideHeader,
} from '@kadena/kode-ui/patterns';
import type { FC } from 'react';
import { useState } from 'react';
import { useForm } from 'react-hook-form';

interface IProps {
Expand All @@ -20,31 +20,32 @@ interface IProps {
export const AddInvestorForm: FC<IProps> = ({ onClose }) => {
const { account, sign } = useAccount();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, setError] = useState<string | null>(null);
const { addTransaction } = useTransactions();
const { register, handleSubmit } = useForm<IRegisterIdentityProps>({
defaultValues: {
investor: '',
accountName: '',
},
});

const onSubmit = async (data: IRegisterIdentityProps) => {
const newData: IRegisterIdentityProps = { ...data, agent: account! };
setError(null);
//try {
const tx = await registerIdentity(newData);
console.log(tx);
const signedTransaction = await sign(tx);
if (!signedTransaction) return;
try {
const tx = await registerIdentity(newData);
const signedTransaction = await sign(tx);
if (!signedTransaction) return;

const client = getClient();
const res = await client.submit(signedTransaction);
console.log(res);
const client = getClient();
const res = await client.submit(signedTransaction);
console.log(res);

await client.listen(res);
console.log('DONE');
// } catch (e: any) {
// setError(e?.message || e);
// }
addTransaction({
...res,
type: 'IDENTITY-REGISTERED',
data: { ...res, ...data },
});

console.log('DONE');
} catch (e: any) {}

onClose();
};
Expand All @@ -57,7 +58,7 @@ export const AddInvestorForm: FC<IProps> = ({ onClose }) => {
<RightAsideContent>
<TextField
label="Investor Account"
{...register('investor', { required: true })}
{...register('accountName', { required: true })}
/>
</RightAsideContent>
<RightAsideFooter>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,12 @@ export const InvestorList: FC = () => {
try {
const tx = await deleteIdentity({ investor: accountName }, account!);

console.log(tx);
console.log(JSON.parse(tx.cmd));

const signedTransaction = await sign(tx);
if (!signedTransaction) return;

const client = getClient();
const res = await client.submit(signedTransaction);

console.log(res);
await client.listen(res);
console.log('DONE');
} catch (e: any) {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
import { useNetwork } from '@/hooks/networks';
import { getClient } from '@/utils/client';
import type { ICommandResult } from '@kadena/client';
import { useNotifications } from '@kadena/kode-ui/patterns';
import type { FC, PropsWithChildren } from 'react';
import { createContext, useCallback, useState } from 'react';

export interface ITransaction {
requestKey: string;
type: string;
data: Record<string, string | number>;
data: Record<string, any>;
listener?: Promise<void | ICommandResult>;
result?: boolean;
}
Expand All @@ -25,21 +26,47 @@ export const TransactionsContext = createContext<ITransactionsContext>({
getTransactions: () => [],
});

const interpretErrorMessage = (result: any, data: ITransaction): string => {
if (result.result.error?.message?.includes('Insert: row found for key')) {
return `{data.type}: This key already exists`;
}

return `${data.type}: ${result.result.error.message}`;
};

export const TransactionsProvider: FC<PropsWithChildren> = ({ children }) => {
const { addNotification } = useNotifications();
const [transactions, setTransactions] = useState<
Record<ITransaction['requestKey'], ITransaction>
>({});

const { activeNetwork } = useNetwork();

const addListener = useCallback((requestKey: string) => {
const addListener = useCallback((data: ITransaction) => {
return getClient()
.listen({
requestKey,
requestKey: data.requestKey,
chainId: activeNetwork.chainId,
networkId: activeNetwork.networkId,
})
.catch(console.log);
.then((result) => {
if (result.result.status === 'failure') {
addNotification({
intent: 'negative',
label: 'there was an error',
message: interpretErrorMessage(result, data),
url: `https://explorer.kadena.io/${activeNetwork.networkId}/transaction/${data.requestKey}`,
});
}
})
.catch((e) => {
addNotification({
intent: 'negative',
label: 'there was an error',
message: JSON.stringify(e),
url: `https://explorer.kadena.io/${activeNetwork.networkId}/transaction/${data.requestKey}`,
});
});
}, []);

const getTransactions = (type: string) => {
Expand All @@ -55,7 +82,7 @@ export const TransactionsProvider: FC<PropsWithChildren> = ({ children }) => {
}

const data = { ...request };
data.listener = addListener(data.requestKey);
data.listener = addListener(data);
setTransactions((v) => {
return { ...v, [request.requestKey]: { ...data } };
});
Expand Down
8 changes: 5 additions & 3 deletions packages/apps/rwa-demo/src/hooks/getInvestors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ export const useGetInvestors = () => {
error,
} = useEventsQuery({
variables: {
qualifiedName: 'RWA.identity-registry.IDENTITY-REGISTERED',
qualifiedName: 'RWA.mvp-token.IDENTITY-REGISTERED',
},
});

const { data: removedData, loading: removedLoading } = useEventsQuery({
variables: {
qualifiedName: 'RWA.identity-registry.IDENTITY-REMOVED',
qualifiedName: 'RWA.mvp-token.IDENTITY-REMOVED',
},
});

Expand Down Expand Up @@ -81,14 +81,16 @@ export const useGetInvestors = () => {
} as const;
}) ?? [];

console.log({ agentsAdded, agentsRemoved });

setInnerData([
...filterRemovedRecords([...agentsAdded, ...agentsRemoved]),
...promiseResults,
]);
};

useEffect(() => {
const tx = getTransactions('ADDAGENT');
const tx = getTransactions('IDENTITY-REGISTERED');
// eslint-disable-next-line @typescript-eslint/no-floating-promises
initInnerData(tx);
}, [transactions, addedData, removedData, removedLoading, addedLoading]);
Expand Down
6 changes: 3 additions & 3 deletions packages/apps/rwa-demo/src/services/addAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { getNetwork } from '@/utils/client';
import { Pact } from '@kadena/client';

export interface IAddAgentProps {
agent: string;
accountName: string;
}

const createPubKeyFromAccount = (account: string): string => {
Expand All @@ -26,9 +26,9 @@ export const addAgent = async (
withCap(`RWA.mvp-token.ONLY-OWNER`, ''),
withCap(`coin.GAS`),
])
.addData('agent', data.agent)
.addData('agent', data.accountName)
.addData('agent_guard', {
keys: [createPubKeyFromAccount(data.agent)],
keys: [createPubKeyFromAccount(data.accountName)],
pred: 'keys-all',
})

Expand Down
6 changes: 2 additions & 4 deletions packages/apps/rwa-demo/src/services/deleteIdentity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,13 @@ export const deleteIdentity = async (
account: IWalletAccount,
) => {
return Pact.builder
.execution(
`(RWA.identity-registry.delete-identity (read-string 'investor) (read-string 'agent))`,
)
.execution(`(RWA.mvp-token.delete-identity (read-string 'investor))`)
.setMeta({
senderAccount: account.address,
chainId: getNetwork().chainId,
})
.addSigner(account.keyset.guard.keys[0], (withCap) => [
withCap(`RWA.mvp-token.ONLY-AGENT`, account.address),
withCap(`RWA.mvp-token.ONLY-AGENT`, 'whitelist-manager'),
withCap(`coin.GAS`),
])
.addData('investor', data.investor)
Expand Down
8 changes: 4 additions & 4 deletions packages/apps/rwa-demo/src/services/registerIdentity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { getNetwork } from '@/utils/client';
import { Pact } from '@kadena/client';

export interface IRegisterIdentityProps {
investor: string;
accountName: string;
agent: IWalletAccount;
}

Expand All @@ -19,17 +19,17 @@ export const registerIdentity = async (data: IRegisterIdentityProps) => {
`,
)
.addData('investor-keyset', {
keys: [createPubKeyFromAccount(data.investor)],
keys: [createPubKeyFromAccount(data.accountName)],
pred: 'keys-all',
})
.addData('investor', data.investor)
.addData('investor', data.accountName)
.addData('agent', data.agent.address)
.setMeta({
senderAccount: data.agent.address,
chainId: getNetwork().chainId,
})
.addSigner(data.agent.keyset.guard.keys[0], (withCap) => [
withCap(`RWA.mvp-token.ONLY-AGENT`, data.agent.address),
withCap(`RWA.mvp-token.ONLY-AGENT`, 'whitelist-manager'),
withCap(`coin.GAS`),
])

Expand Down
9 changes: 4 additions & 5 deletions packages/apps/rwa-demo/src/utils/filterRemovedRecords.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,22 @@ export interface IRecord {

export const filterRemovedRecords = (arr: IRecord[]): IRecord[] => {
return arr
.filter((v, idx, self) => {
return idx === self.findIndex((t) => t.accountName === v.accountName);
})
.sort((a, b) => {
if (
new Date(a.creationTime).getTime() < new Date(b.creationTime).getTime()
)
return -1;
return 1;
})

.reduce((acc: IRecord[], val: IRecord) => {
if (val.isRemoved) {
const newAcc = acc.filter((v) => v.accountName !== val.accountName);
return newAcc;
}
acc.push(val);
return acc;
}, []);
}, [])
.filter((v, idx, self) => {
return idx === self.findIndex((t) => t.accountName === v.accountName);
});
};
5 changes: 2 additions & 3 deletions packages/libs/kode-ui/.storybook/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const config: StorybookConfig = {
},
getAbsolutePath('@storybook/addon-mdx-gfm'),
getAbsolutePath('@storybook/addon-webpack5-compiler-swc'),
'@chromatic-com/storybook',
],
framework: {
name: getAbsolutePath('@storybook/react-webpack5'),
Expand All @@ -36,9 +37,7 @@ const config: StorybookConfig = {
},
},
},
docs: {
autodocs: true,
},
docs: {},
// Add this for Vanilla Extract
webpackFinal(config) {
// Add Vanilla-Extract and MiniCssExtract Plugins
Expand Down
2 changes: 2 additions & 0 deletions packages/libs/kode-ui/.storybook/preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@ const preview: Preview = {
},
},
},

decorators: [withCenteredStory],
tags: ['autodocs'],
};

export default preview;
Loading

0 comments on commit a2010ad

Please sign in to comment.