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 12 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.4",
"@tabler/icons-react": "^3.1.0",
"@tanstack/react-virtual": "^3.3.0",
"@uidotdev/usehooks": "^2.4.1",
Expand Down
162 changes: 159 additions & 3 deletions src/api/requests/tx.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
import { SpawnTransaction, SpendTransaction } from '@spacemesh/sm-codec';
import {
Athena,
SpawnTransaction,
SpendTransaction,
StdMethods,
} from '@spacemesh/sm-codec';
import { DeployArguments } from '@spacemesh/sm-codec/lib/athena/wallet';
import {
SpawnArguments,
SpendArguments,
} from '@spacemesh/sm-codec/lib/std/singlesig';

import { Bech32Address } from '../../types/common';
import { Transaction } from '../../types/tx';
Expand Down Expand Up @@ -67,6 +77,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 @@ -79,16 +90,161 @@ export const fetchTransactionsChunk = async (

export const fetchTransactions = getFetchAll(fetchTransactionsChunk, 100);

type ParseErr = {
error: string;
bytes: Uint8Array;
};

const getMethod = (
tx: TransactionResponseObject & WithExtraData,
isAthena: boolean
) => {
switch (tx.type) {
case 'TRANSACTION_TYPE_SINGLE_SIG_SPAWN':
case 'TRANSACTION_TYPE_SINGLE_SIG_SELFSPAWN':
case 'TRANSACTION_TYPE_MULTI_SIG_SPAWN':
case 'TRANSACTION_TYPE_MULTI_SIG_SELFSPAWN': {
if (isAthena) {
return Athena.Wallet.METHODS_HEX.SPAWN;
}
return StdMethods.Spawn;
}
case 'TRANSACTION_TYPE_MULTI_SIG_SEND':
case 'TRANSACTION_TYPE_SINGLE_SIG_SEND': {
if (isAthena) {
return Athena.Wallet.METHODS_HEX.SPEND;
}
return StdMethods.Spend;
}
case 'TRANSACTION_TYPE_DEPLOY':
return Athena.Wallet.METHODS_HEX.DEPLOY;
default:
return tx.method;
}
};

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>;
case 'TRANSACTION_TYPE_DEPLOY':
return Athena.Templates[
'000000000000000000000000000000000000000000000001'
].methods[Athena.Wallet.METHODS_HEX.DEPLOY].dec(
txBytes
) as Athena.TypedTx<Athena.Wallet.DeployArguments>;
default: {
// eslint-disable-next-line max-len
const errMessage = `Unknown Athnea's transaction type: ${tx.type}`;
// eslint-disable-next-line no-console
console.log(new Error(errMessage));
return {
error: errMessage,
bytes: txBytes,
} as ParseErr;
}
}
};
const getParsedPayload = (
parsed: ReturnType<typeof parse>
): SpawnArguments | SpendArguments | DeployArguments | ParseErr => {
switch (tx.type) {
case 'TRANSACTION_TYPE_SINGLE_SIG_SPAWN':
return {
PublicKey: (
parsed as Athena.TypedTx<Athena.Wallet.SpawnArguments>
).Payload.PubKey,
};
case 'TRANSACTION_TYPE_SINGLE_SIG_SEND':
return {
Destination: (
parsed as Athena.TypedTx<Athena.Wallet.SpendArguments>
).Payload.Recipient,
Amount: (parsed as Athena.TypedTx<Athena.Wallet.SpendArguments>)
.Payload.Amount,
};
case 'TRANSACTION_TYPE_DEPLOY':
return (parsed as Athena.TypedTx<Athena.Wallet.DeployArguments>)
.Payload;
default: {
if (
!(
Object.hasOwn(parsed, 'error') &&
Object.hasOwn(parsed, 'bytes')
)
) {
throw new Error(`Unknown Athnea transaction type ${tx.type}`);
}
// eslint-disable-next-line max-len
const errMessage = `Unknown Athnea's transaction type: ${tx.type}`;
return {
error: errMessage,
bytes: (parsed as ParseErr).bytes,
};
}
}
};

const parsed = parse();
const method = getMethod(tx, isAthena);
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: getParsedPayload(parsed),
state: tx.state,
message: tx.message,
touched: tx.touched,
};
} 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, String(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
19 changes: 17 additions & 2 deletions src/api/schemas/tx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { z } from 'zod';
import { Bech32Address } from '../../types/common';

import { Bech32AddressSchema } from './address';
import { Base64Schema } from './common';
import { Base64Schema, HexStringSchema } from './common';
import { BigIntStringSchema } from './strNumber';

// Common stuff
Expand All @@ -21,11 +21,26 @@ 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',
'TRANSACTION_TYPE_DEPLOY',
]);

export const TransactionSchema = z.object({
id: TransactionIdSchema,
type: TransactionTemplateMethodType,
principal: Bech32AddressSchema,
template: Bech32AddressSchema,
method: z.number(),
method: z.union([z.number(), HexStringSchema]),
nonce: NonceSchema,
maxGas: BigIntStringSchema,
gasPrice: BigIntStringSchema,
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
32 changes: 26 additions & 6 deletions src/components/AddNetworkDrawer.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { useState } from 'react';
import { useMemo, useState } from 'react';
import { Form, useForm } from 'react-hook-form';

import {
Button,
Checkbox,
Drawer,
DrawerBody,
DrawerCloseButton,
Expand All @@ -18,6 +19,7 @@ import {

import { fetchNetworkInfo } from '../api/requests/netinfo';
import useNetworks from '../store/useNetworks';
import { toISO, toMs } from '../utils/datetime';
import { normalizeURL } from '../utils/url';

import FormInput from './FormInput';
Expand All @@ -36,6 +38,7 @@ type FormValues = {
explorer: string;
layerDuration: string;
layersPerEpoch: string;
isAthena: boolean;
};

function AddNetworkDrawer({ isOpen, onClose }: Props): JSX.Element {
Expand All @@ -46,8 +49,14 @@ function AddNetworkDrawer({ isOpen, onClose }: Props): JSX.Element {
reset,
control,
handleSubmit,
watch,
formState: { errors, isSubmitted },
} = useForm<FormValues>();
const genesisTimeValue = watch('genesisTime');
const genesisTimeMs = useMemo(
() => toMs(genesisTimeValue),
[genesisTimeValue]
);

const [apiError, setApiError] = useState('');
const [apiLoading, setApiLoading] = useState(false);
Expand All @@ -64,9 +73,10 @@ function AddNetworkDrawer({ isOpen, onClose }: Props): JSX.Element {
explorerUrl: data.explorer,
hrp: data.hrp,
genesisID: data.genesisID,
genesisTime: new Date(data.genesisTime).getTime(),
genesisTime: toMs(data.genesisTime),
layerDuration: parseInt(data.layerDuration, 10),
layersPerEpoch: parseInt(data.layersPerEpoch, 10),
isAthena: data.isAthena ?? false,
});

close();
Expand Down Expand Up @@ -113,9 +123,7 @@ function AddNetworkDrawer({ isOpen, onClose }: Props): JSX.Element {
if (!info) {
throw new Error('Cannot fetch network info');
}
const isoTime = new Date(info.genesisTime)
.toISOString()
.slice(0, 16);
const isoTime = toISO(info.genesisTime);
setValue('genesisTime', isoTime);
setValue('hrp', info.hrp);
setValue('genesisID', info.genesisId);
Expand Down Expand Up @@ -194,7 +202,11 @@ function AddNetworkDrawer({ isOpen, onClose }: Props): JSX.Element {
inputProps={{ type: 'datetime-local' }}
errors={errors}
isSubmitted={isSubmitted}
/>
>
<Text fontSize="xx-small" px={4} mt={0.5}>
UNIX Time: {Number.isNaN(genesisTimeMs) ? '???' : genesisTimeMs}
</Text>
</FormInput>
<FormInput
label="Layer Duration (sec)"
register={register('layerDuration', {
Expand All @@ -213,6 +225,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
Loading