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

Athena integration PoC (WIP) #112

Open
wants to merge 6 commits into
base: main
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 package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"@noble/ed25519": "^2.1.0",
"@scure/bip39": "^1.2.2",
"@spacemesh/ed25519-bip32": "^0.2.1",
"@spacemesh/sm-codec": "^0.8.0",
"@spacemesh/sm-codec": "^0.9.0-athena.2",
"@tabler/icons-react": "^3.1.0",
"@tanstack/react-virtual": "^3.3.0",
"@uidotdev/usehooks": "^2.4.1",
Expand Down
91 changes: 88 additions & 3 deletions src/api/requests/tx.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { SpawnTransaction, SpendTransaction } from '@spacemesh/sm-codec';
import {
Athena,
SpawnTransaction,
SpendTransaction,
StdMethods,
} from '@spacemesh/sm-codec';

import { Bech32Address } from '../../types/common';
import { Transaction } from '../../types/tx';
Expand Down Expand Up @@ -67,6 +72,7 @@ export const fetchTransactionsChunk = async (
.then(({ transactions }) =>
transactions.map((tx) => ({
...tx.tx,
type: tx.tx.type,
layer: tx.txResult?.layer || 0,
state: getTxState(
tx.txResult?.status,
Expand All @@ -81,14 +87,93 @@ export const fetchTransactions = getFetchAll(fetchTransactionsChunk, 100);

export const fetchTransactionsByAddress = async (
rpc: string,
address: Bech32Address
address: Bech32Address,
isAthena: boolean
) => {
const txs = await fetchTransactions(rpc, address);

if (isAthena) {
return txs.map((tx) => {
try {
const parse = () => {
const txBytes = fromBase64(tx.raw);
switch (tx.type) {
case 'TRANSACTION_TYPE_SINGLE_SIG_SPAWN':
return Athena.Templates[
'000000000000000000000000000000000000000000000001'
].methods[Athena.Wallet.METHODS_HEX.SPAWN].dec(
txBytes
) as Athena.TypedTx<Athena.Wallet.SpawnArguments>;
case 'TRANSACTION_TYPE_SINGLE_SIG_SEND':
return Athena.Templates[
'000000000000000000000000000000000000000000000001'
].methods[Athena.Wallet.METHODS_HEX.SPEND].dec(
txBytes
) as Athena.TypedTx<Athena.Wallet.SpendArguments>;
default: {
throw new Error(`Unknown Athnea's transaction type: ${tx.type}`);
}
}
};
const parsed = parse();

const method =
tx.type === 'TRANSACTION_TYPE_SINGLE_SIG_SPAWN'
? StdMethods.Spawn
: StdMethods.Spend;
return {
id: toHexString(fromBase64(tx.id), true),
principal: tx.principal,
nonce: {
counter: tx.nonce.counter,
bitfield: tx.nonce.bitfield || 0,
},
gas: {
maxGas: tx.maxGas,
price: tx.gasPrice,
},
template: {
address: tx.template,
method,
name: getTemplateNameByAddress(tx.template, true),
methodName: getMethodName(method),
},
layer: tx.layer,
parsed:
tx.type === 'TRANSACTION_TYPE_SINGLE_SIG_SPAWN'
? {
PublicKey: (
parsed as Athena.TypedTx<Athena.Wallet.SpawnArguments>
).Payload.PubKey,
}
: {
Destination: (
parsed as Athena.TypedTx<Athena.Wallet.SpendArguments>
).Payload.Recipient,
Amount: (
parsed as Athena.TypedTx<Athena.Wallet.SpendArguments>
).Payload.Amount,
},
state: tx.state,
message: tx.message,
touched: tx.touched,
} satisfies Transaction<
(SpawnTransaction | SpendTransaction)['Payload']['Arguments']
>; // TODO: to display it as genvm txs
} catch (err) {
/* eslint-disable no-console */
console.log('Error parsing Athena Transaction', tx);
console.error(err);
/* eslint-enable no-console */
throw err;
}
});
}

return txs.map((tx) => {
const templateAddress = toHexString(getWords(tx.template));
const template = getTemplateMethod(templateAddress, tx.method);
try {
const template = getTemplateMethod(templateAddress, tx.method);
const parsedRaw = template.decode(fromBase64(tx.raw));
const parsed =
tx.method === 0
Expand Down
1 change: 1 addition & 0 deletions src/api/schemas/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export const AccountDataSchema = z.object({
address: Bech32AddressSchema,
current: AccountStateSchema,
projected: AccountStateSchema,
template: Bech32AddressSchema.or(z.literal('')),
});

export const BalanceResponseSchema = z.object({
Expand Down
4 changes: 1 addition & 3 deletions src/api/schemas/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ export const Bech32AddressSchema = z.custom<string>(
if (typeof addr !== 'string') return false;
try {
const p = bech32.decode(addr);
if (!['sm', 'stest', 'standalone'].includes(p.prefix)) return false;
if (bech32.fromWords(p.words).length !== 24) return false;
return true;
return bech32.fromWords(p.words).length === 24;
} catch (err) {
return false;
}
Expand Down
14 changes: 14 additions & 0 deletions src/api/schemas/tx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,22 @@ export type Nonce = z.infer<typeof NonceSchema>;

// Response objects

export const TransactionTemplateMethodType = z.enum([
'TRANSACTION_TYPE_UNSPECIFIED',
'TRANSACTION_TYPE_SINGLE_SIG_SEND',
'TRANSACTION_TYPE_SINGLE_SIG_SPAWN',
'TRANSACTION_TYPE_SINGLE_SIG_SELFSPAWN',
'TRANSACTION_TYPE_MULTI_SIG_SEND',
'TRANSACTION_TYPE_MULTI_SIG_SPAWN',
'TRANSACTION_TYPE_MULTI_SIG_SELFSPAWN',
'TRANSACTION_TYPE_VESTING_SPAWN',
'TRANSACTION_TYPE_VAULT_SPAWN',
'TRANSACTION_TYPE_DRAIN_VAULT',
]);

export const TransactionSchema = z.object({
id: TransactionIdSchema,
type: TransactionTemplateMethodType,
principal: Bech32AddressSchema,
template: Bech32AddressSchema,
method: z.number(),
Expand Down
37 changes: 36 additions & 1 deletion src/components/AccountActionHints.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,42 @@ function AccountActionHints(): JSX.Element | null {
const [account, isSpawned] = data;
if (isSpawned) return null;

const getBorderColor = () => {
if (!!currentAccount?.isAthena !== network.isAthena) {
return 'brand.red';
}
return 'brand.green';
};
const renderContents = () => {
// Is Athena account on Non-Athena network
if (!!currentAccount?.isAthena && !network.isAthena) {
return (
<Box w="100%">
<Text fontSize="md" fontWeight="bold" mb={2}>
That network does not support Athena accounts
</Text>
<Text fontSize="sm">
Please switch to the original Spacemesh account first.
</Text>
</Box>
);
}
// Is Athena account on Non-Athena network
if (!currentAccount?.isAthena && !!network.isAthena) {
return (
<Box w="100%">
<Text fontSize="md" fontWeight="bold" mb={2}>
That network supports only Athena accounts
</Text>
<Text fontSize="sm">
Please switch to the Athena account first.
<br />
You may need to create it first on the &quot;Keys &amp;
Accounts&quot; page.
</Text>
</Box>
);
}
// No balance
if (
account.state.current.balance === '0' ||
Expand Down Expand Up @@ -128,7 +163,7 @@ function AccountActionHints(): JSX.Element | null {
<Card
my={4}
variant="outline"
borderColor="brand.green"
borderColor={getBorderColor()}
maxW={{ base: '100%', md: '600px' }}
>
<CardBody>{renderContents()}</CardBody>
Expand Down
11 changes: 11 additions & 0 deletions src/components/AddNetworkDrawer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Form, useForm } from 'react-hook-form';

import {
Button,
Checkbox,
Drawer,
DrawerBody,
DrawerCloseButton,
Expand Down Expand Up @@ -36,6 +37,7 @@ type FormValues = {
explorer: string;
layerDuration: string;
layersPerEpoch: string;
isAthena: boolean;
};

function AddNetworkDrawer({ isOpen, onClose }: Props): JSX.Element {
Expand Down Expand Up @@ -67,6 +69,7 @@ function AddNetworkDrawer({ isOpen, onClose }: Props): JSX.Element {
genesisTime: new Date(data.genesisTime).getTime(),
layerDuration: parseInt(data.layerDuration, 10),
layersPerEpoch: parseInt(data.layersPerEpoch, 10),
isAthena: data.isAthena ?? false,
});

close();
Expand Down Expand Up @@ -213,6 +216,14 @@ function AddNetworkDrawer({ isOpen, onClose }: Props): JSX.Element {
errors={errors}
isSubmitted={isSubmitted}
/>
<Checkbox
size="lg"
mt={2}
pl={4}
{...register('isAthena', { value: false })}
>
<Text fontSize="md">Running under Athena VM</Text>
</Checkbox>
</DrawerBody>

<DrawerFooter>
Expand Down
Loading