Skip to content

Commit

Permalink
Clean-up front end
Browse files Browse the repository at this point in the history
  • Loading branch information
DOBEN committed Jan 5, 2024
1 parent 72c1321 commit 424b12e
Show file tree
Hide file tree
Showing 16 changed files with 93 additions and 74 deletions.
4 changes: 2 additions & 2 deletions sponsoredTransactionsAuction/backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ This page describes the sponsored transactions backend for this dapp example.
The following parameters are supported
- `node` the URL of the node's GRPC V2 interface, e.g., `http://node.testnet.concordium.com:20000`
- `port` the port on which the server will listen for incoming requests, e.g., 127.0.0.1:8080.
- `log-level` maximum log level (defaults to `debug` if not given).
- `frontend` the path to the folder, which should be served, defaults to the `public` folder in the current directory.
- `log-level` maximum log level (defaults to `info` if not given).
- `frontend` the path to the folder, which should be served, defaults to the `../frontent/dist` folder.
- `account-key-file` the path to a file which contains the key credentials.
- `cis2-token-smart-contract-index` the smart contract index which the sponsored transaction is submitted to.
- `auction-smart-contract-index` the smart contract index of the auction smart contract.
Expand Down
31 changes: 15 additions & 16 deletions sponsoredTransactionsAuction/frontend/src/auction_contract.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as AuctionContract from '../generated/sponsored_tx_enabled_auction_sponsored_tx_enabled_auction'; // Code generated from a smart contract module.
import * as AuctionContract from '../generated/sponsored_tx_enabled_auction_sponsored_tx_enabled_auction'; // Code generated from a smart contract module. The naming convention of the generated file is `moduleName_smartContractName`.

import {
AccountTransactionType,
Expand Down Expand Up @@ -34,14 +34,15 @@ const contract = AuctionContract.createUnchecked(
ContractAddress.create(Number(process.env.AUCTION_CONTRACT_INDEX), CONTRACT_SUB_INDEX),
);

// This function submits a transaction to add an item to the auction contract.
export const AUCTION_CONTRACT = contract;

/**
* Add new item to the auction contract.
* This function submits a transaction to add an item to the auction contract.
*
* @param connection - The wallet connection to use for sending the transaction
* @param accountAddress - The account address to send from
* @param addItemParameter - The parameter for the add item function
* @throws If the contract could not be updated
* @param connection - The wallet connection to use for sending the transaction.
* @param accountAddress - The account address to send from.
* @param addItemParameter - The parameter for the addItem function.
* @throws If simulating the contract update fails.
* @returns A promise resolving with the corresponding {@linkcode TransactionHash.Type}
*/
export async function addItem(
Expand All @@ -63,11 +64,11 @@ export async function addItem(
);
}

const maxContractExecutionEnergy = Energy.create(dryRunResult.usedEnergy.value + EPSILON_ENERGY); // + EPSILON_ENERGY needs to be here, as there seems to be an issue with running out of energy 1 energy prior to reaching the execution limit
const maxContractExecutionEnergy = Energy.create(dryRunResult.usedEnergy.value + EPSILON_ENERGY);

const payload: Omit<UpdateContractPayload, 'message'> = {
amount: CcdAmount.zero(),
address: ContractAddress.create(Number(process.env.AUCTION_CONTRACT_INDEX), CONTRACT_SUB_INDEX),
address: contract.contractAddress,
receiveName: ReceiveName.create(AuctionContract.contractName, EntrypointName.fromString('addItem')),
maxContractExecutionEnergy,
};
Expand All @@ -94,13 +95,11 @@ export async function addItem(
}

/**
* TODO: update comment
* View item state.
* @param connection - The wallet connection to use for sending the transaction
* @param accountAddress - The account address to send from
* @param mintParameter - The parameter for the mint function
* @throws If the contract could not be updated
* @returns A promise resolving with the corresponding {@linkcode TransactionHash.Type}
* This function views the item state in the auction contract.
*
* @param viewItemState - The parameter for the viewItemState function.
* @throws If the communicate with the Concordium node fails, the smart contract reverts, or parsing the returnValue fails.
* @returns A promise resolving with the corresponding {@linkcode AuctionContract.ReturnValueViewItemState}
*/
export async function viewItemState(
viewItemState: AuctionContract.ViewItemStateParameter,
Expand Down
29 changes: 14 additions & 15 deletions sponsoredTransactionsAuction/frontend/src/cis2_token_contract.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as Cis2MultiContract from '../generated/cis2_multi_cis2_multi'; // Code generated from a smart contract module.
import * as Cis2MultiContract from '../generated/cis2_multi_cis2_multi'; // Code generated from a smart contract module. The naming convention of the generated file is `moduleName_smartContractName`.

import {
AccountTransactionType,
Expand Down Expand Up @@ -33,14 +33,15 @@ const contract = Cis2MultiContract.createUnchecked(
ContractAddress.create(Number(process.env.CIS2_TOKEN_CONTRACT_INDEX), CONTRACT_SUB_INDEX),
);

// This function submits a transaction to mint/airdrop tokens to an account.
export const CIS2_TOKEN_CONTRACT = contract;

/**
* Mints new cis2 tokens to the account specified in the mintParameter.
* This function submits a transaction to mint/airdrop cis2_multi tokens to an account.
*
* @param connection - The wallet connection to use for sending the transaction
* @param accountAddress - The account address to send from
* @param mintParameter - The parameter for the mint function
* @throws If the contract could not be updated
* @param connection - The wallet connection to use for sending the transaction.
* @param accountAddress - The account address to send from.
* @param mintParameter - The parameter for the mint function.
* @throws If simulating the contract update fails or the `mintParameter.owner` is not an account.
* @returns A promise resolving with the corresponding {@linkcode TransactionHash.Type}
*/
export async function mint(
Expand All @@ -62,11 +63,11 @@ export async function mint(
);
}

const maxContractExecutionEnergy = Energy.create(dryRunResult.usedEnergy.value + EPSILON_ENERGY); // + EPSILON_ENERGY needs to be here, as there seems to be an issue with running out of energy 1 energy prior to reaching the execution limit
const maxContractExecutionEnergy = Energy.create(dryRunResult.usedEnergy.value + EPSILON_ENERGY);

const payload: Omit<UpdateContractPayload, 'message'> = {
amount: CcdAmount.zero(),
address: ContractAddress.create(Number(process.env.CIS2_TOKEN_CONTRACT_INDEX), CONTRACT_SUB_INDEX),
address: contract.contractAddress,
receiveName: ReceiveName.create(Cis2MultiContract.contractName, EntrypointName.fromString('mint')),
maxContractExecutionEnergy,
};
Expand Down Expand Up @@ -105,13 +106,11 @@ export async function mint(
}

/**
* Mints new cis2 tokens to the account specified in the mintParameter.
* This function views the nonce (CIS3 standard) of an acccount in the cis2_multi contract.
*
* @param connection - The wallet connection to use for sending the transaction
* @param accountAddress - The account address to send from
* @param mintParameter - The parameter for the mint function
* @throws If the contract could not be updated
* @returns A promise resolving with the corresponding {@linkcode TransactionHash.Type}
* @param nonceOfParameter - The parameter for the nonceOf function.
* @throws If the communicate with the Concordium node fails, the smart contract reverts, or parsing the returnValue fails.
* @returns A promise resolving with the corresponding {@linkcode Cis2MultiContract.ReturnValueNonceOf}
*/
export async function nonceOf(
nonceOfParameter: Cis2MultiContract.NonceOfParameter,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import {
} from '@concordium/web-sdk';

import { AUCTION_END, AUCTION_START } from '../constants';
import { addItem } from '../auction_contract';

import { addItem } from '../auction_contract';
import * as AuctionContract from '../../generated/sponsored_tx_enabled_auction_sponsored_tx_enabled_auction'; // Code generated from a smart contract module.

interface ConnectionProps {
Expand Down Expand Up @@ -88,7 +88,7 @@ export default function AddItemToAuction(props: ConnectionProps) {

setItemIndex(parsedEvent.content.item_index);
} else {
setItemIndexError('Tansaction failed or event decoding failed.');
setItemIndexError('Tansaction failed and event decoding failed.');
}
})
.catch((e) => {
Expand Down
14 changes: 9 additions & 5 deletions sponsoredTransactionsAuction/frontend/src/components/App/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ import Footer from '../Footer';
import { BROWSER_WALLET, REFRESH_INTERVAL } from '../../constants';

import { nonceOf } from '../../cis2_token_contract';
import * as Cis2MultiContract from '../../../generated/cis2_multi_cis2_multi'; // Code generated from a smart contract module.
import * as Cis2MultiContract from '../../../generated/cis2_multi_cis2_multi';

/*
/**
* The main component that manages the wallet connection.
* It imports and displays the four components `MintTokens`, `AddItemToAuction`, `ViewItem`, and `Bid`.
*/
Expand All @@ -47,6 +47,9 @@ export default function App(props: WalletConnectionProps) {
const [txHash, setTxHash] = useState<undefined | TransactionHash.Type>(undefined);
const [transactionError, setTransactionError] = useState<string | undefined>(undefined);

/**
* This function querries the nonce (CIS3 standard) of an acccount in the cis2_multi contract.
*/
const refreshNonce = useCallback(() => {
if (grpcClient && account) {
const nonceOfParam: Cis2MultiContract.NonceOfParameter = [AccountAddress.fromBase58(account)];
Expand All @@ -72,9 +75,10 @@ export default function App(props: WalletConnectionProps) {
return () => clearInterval(interval);
}, [refreshNonce]);

/*
* This function gets the public key of an account.
* This function works with a wallet account that has just one public-private key pair in its two-level key map.
/**
* This function gets the public key of an account. The function can be used
* for accounts generated in the browser and mobile wallets
* that have just one public-private key pair in their two-level key map.
*/
const getPublicKey = useCallback(
(account: string | undefined) => {
Expand Down
21 changes: 14 additions & 7 deletions sponsoredTransactionsAuction/frontend/src/components/Bid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,13 @@ import {
SERIALIZATION_HELPER_SCHEMA_ADDITIONAL_DATA,
SERIALIZATION_HELPER_SCHEMA_PERMIT_MESSAGE,
TRANSFER_SCHEMA,
VERIFIER_URL,
} from '../constants';

import { submitBid, validateAccountAddress } from '../utils';
import { viewItemState } from '../auction_contract';

import { viewItemState } from '../auction_contract';
import * as AuctionContract from '../../generated/sponsored_tx_enabled_auction_sponsored_tx_enabled_auction'; // Code generated from a smart contract module.

/*
/**
* This function generates the transfer message to be signed in the browser wallet.
*/
async function generateTransferMessage(
Expand All @@ -37,6 +35,7 @@ async function generateTransferMessage(
throw new Error(`ItemIndex is NaN.`);
}

// Figure out the `tokenId` that the item is up for auction.
const itemState: AuctionContract.ReturnValueViewItemState = await viewItemState(viewItemStateParam);

setTokenID(itemState.token_id);
Expand All @@ -48,10 +47,13 @@ async function generateTransferMessage(

const hexStringData = [...data.buffer].map((b) => b.toString(16).padStart(2, '0')).join('');

// Generate transfer parameter.
const transfer = [
{
amount,
data: hexStringData, // e.g. 0100 (for item with index 1)
// The item index in the auction contract is of type u16.
// A little endian hex string of 2 bytes represents the index here. E.g. `0100` for item with index 1.
data: hexStringData,
from: {
Account: [account],
},
Expand Down Expand Up @@ -99,7 +101,7 @@ interface ConnectionProps {
setTransactionError: (error: string | undefined) => void;
}

/*
/**
* A component that manages the input fields and corresponding state to sign a bid message and submit the signature to the backend.
*/
export default function Bid(props: ConnectionProps) {
Expand Down Expand Up @@ -129,6 +131,9 @@ export default function Bid(props: ConnectionProps) {
}
const formBid = useForm<FormTypeBid>({ mode: 'all' });

/**
* When submitting the form, the browser wallet is prompt to sign the transferMessage.
*/
async function onSubmitSigning(data: FormTypeGenerateSignature) {
setSigningError(undefined);
setSignature(undefined);
Expand Down Expand Up @@ -165,14 +170,16 @@ export default function Bid(props: ConnectionProps) {
}
}

/**
* When submitting the form, the generated signature from the previous step is sent to the backend.
*/
function onSubmitBid(data: FormTypeBid, accountAddress: string | undefined) {
setTxHash(undefined);
setTransactionError(undefined);
setShowMessage(false);

if (accountAddress && signature) {
const tx = submitBid(
VERIFIER_URL,
data.signer,
nonce,
signature,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ interface TxHashLinkProps {
txHash: TransactionHash.Type;
}

/*
/**
* A component that displays the CCDScan link of a transaction hash.
*/
export const TxHashLink = function TxHashLink(props: TxHashLinkProps) {
Expand All @@ -30,7 +30,7 @@ interface AccountLinkProps {
account: string;
}

/*
/**
* A component that displays the CCDScan link to an account address.
*/
export const AccountLink = function AccountLink(props: AccountLinkProps) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { version } from '../../package.json';

/*
/**
* A component that displays a link to the developer documentation and the version of the app.
*/
export default function Footer() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import { useForm } from 'react-hook-form';
import { Alert, Button, Form } from 'react-bootstrap';

import { WalletConnection } from '@concordium/react-components';
import { mint } from '../cis2_token_contract';
import { AccountAddress, TransactionHash } from '@concordium/web-sdk';

import { METADATA_URL } from '../constants';
import { validateAccountAddress } from '../utils';

import { mint } from '../cis2_token_contract';
import * as Cis2MultiContract from '../../generated/cis2_multi_cis2_multi'; // Code generated from a smart contract module.
import { validateAccountAddress } from '../utils';

interface ConnectionProps {
setTxHash: (hash: TransactionHash.Type | undefined) => void;
Expand All @@ -18,7 +18,7 @@ interface ConnectionProps {
connection: WalletConnection;
}

/*
/**
* A component that manages the input fields and corresponding state to mint/airdrop some cis2 tokens to the user.
* This component creates an `Update` transaction.
*/
Expand Down Expand Up @@ -48,6 +48,9 @@ export default function MintTokens(props: ConnectionProps) {
hash: { type: 'None' },
url: METADATA_URL, // In production, you should consider using a different metadata file for each token_id.
},
// The token id in the cis2 token contract is of type u8.
// A hex string of 1 byte represents the token id here. E.g. `01` for token id 1.
// The input field has a max/min value validation, so that `data.tokenID` is not greater than 255.
token_id: `0${Number(data.tokenID).toString(16)}`.slice(-2),
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ interface ConnectionProps {
grpcClient: ConcordiumGRPCClient | undefined;
}

/*
/**
* A component that manages the input fields and corresponding state to view an item in the auction contract.
*/
export default function ViewItem(props: ConnectionProps) {
Expand Down
5 changes: 5 additions & 0 deletions sponsoredTransactionsAuction/frontend/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ export const AUCTION_CONTRACT_NAME = ContractName.fromString('sponsored_tx_enabl

export const CONTRACT_SUB_INDEX = 0n;

// Before submitting a transaction we simulate/dry-run the transaction to get an
// estimate of the energy needed for executing the transaction. In addition, we
// allow an additional small amount of energy `EPSILON_ENERGY` to be consumed by
// the transaction to cover small variations (e.g. changes to the smart contract
// state) caused by transactions that have been executed meanwhile.
export const EPSILON_ENERGY = 1000n;

export const AUCTION_START = '2000-01-01T12:00:00Z'; // Hardcoded value for simplicity for this demo dApp.
Expand Down

This file was deleted.

1 change: 0 additions & 1 deletion sponsoredTransactionsAuction/frontend/src/scss/index.scss
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
@import 'config';
@import 'bootstrap-config';
@import 'layout';
@import 'components';

This file was deleted.

This file was deleted.

Loading

0 comments on commit 424b12e

Please sign in to comment.