Skip to content

Commit

Permalink
add txResults in hooks, other improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
juliancwirko committed Jan 28, 2023
1 parent 5a4035d commit 48aa498
Show file tree
Hide file tree
Showing 20 changed files with 1,075 additions and 919 deletions.
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ API_ALLOWED_DAPP_HOST = http://localhost:3000
NEXT_PUBLIC_EGLD_TRANSFER_ADDRESS = erd17a4wydhhd6t3hhssvcp9g23ppn7lgkk4g2tww3eqzx4mlq95dukss0g50f

# The smart contract address used for minting the NFT token (as example deployed Elven Tools Smart Contract)
NEXT_PUBLIC_MINT_SMART_CONTRACT_ADDRESS = erd1qqqqqqqqqqqqqpgq5za2pty2tlfqhj20z9qmrrpjmyt6advcgtkscm7xep
NEXT_PUBLIC_MINT_SMART_CONTRACT_ADDRESS = erd1qqqqqqqqqqqqqpgqztp5vpqrxe2tha224jwsa3sv2800a88zgtksar2kc8

# The function/endpoint name for minting on the smart contract
NEXT_PUBLIC_MINT_FUNCTION_NAME = mint
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
### [4.3.0](https://github.com/xdevguild/nextjs-dapp-template/releases/tag/v4.3.0) (2023-01-28)
- `txResults` is now returned in `useTransaction` and `useScTransaction` hooks (it is ITransactionOnNetwork in sdk-core)
- dependencies updates

### [4.2.0](https://github.com/xdevguild/nextjs-dapp-template/releases/tag/v4.2.0) (2023-01-14)
- rebrand to multiversx (continuation)
- npm packages are replaced
Expand Down
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ It has straightforward and complete functionality.
### Main assumption for the dapp:

- it works on Nextjs
- it uses erdjs 11.* without the dapp-core library.
- it uses sdk-core 11.* without the dapp-core library.
it uses backed-side redirections to hide the API endpoint. The only exposed one is `/api/multiversx` and it is used only by the dapp internally
- it uses the .env file - there is an example in the repo (for all configurations, also for the demo config)
- it uses chakra-ui
Expand Down Expand Up @@ -58,7 +58,7 @@ const NextJSDappTemplate = ({ Component, pageProps }: AppProps) => {

#### LoginModalButton

The component provides the `Connect` button with the modal, which will contain another three buttons for four different authentication possibilities (Maiar Mobile App, Maiar Defi Wallet - browser extension, MultiversX Web Wallet). You should be able to use it in any place on the website.
The component provides the `Connect` button with the modal, which will contain another three buttons for four different authentication possibilities (xPortal Mobile App, MultiversX Defi Wallet - browser extension, MultiversX Web Wallet). You should be able to use it in any place on the website.

```jsx
import { LoginModalButton } from '../tools/LoginModalButton';
Expand Down Expand Up @@ -107,7 +107,7 @@ It can display the spinner and also the fallback React element.
The hook provides all that is required for triggering transactions. useTransaction can also take a callback function as an argument.

```jsx
const { pending, triggerTx, transaction, error } = useTransaction({ cb });
const { pending, triggerTx, transaction, txResult, error } = useTransaction({ cb });

const handleSendTx = useCallback(() => {
const demoMessage = 'Transaction demo!';
Expand All @@ -125,7 +125,7 @@ const handleSendTx = useCallback(() => {
The hook provides all that is required for triggering smart contract transactions. useScTransaction can also take a callback function as an argument.

```jsx
const { pending, triggerTx, transaction, error } = useScTransaction({ cb });
const { pending, triggerTx, transaction, txResult, error } = useScTransaction({ cb });

const handleSendTx = useCallback(() => {
triggerTx({
Expand Down Expand Up @@ -154,7 +154,7 @@ const {
payload: {
scAddress: process.env.NEXT_PUBLIC_MINT_SMART_CONTRACT_ADDRESS,
funcName: process.env.NEXT_PUBLIC_QUERY_FUNCTION_NAME,
args: [], // arguments for the query in hex format, you can use erdjs for that, for example: args: [ new Address('erd1....').hex() ] etc. It will be also simplified in the future.
args: [], // arguments for the query in hex format, you can use sdk-core for that, for example: args: [ new Address('erd1....').hex() ] etc. It will be also simplified in the future.
},
autoInit: false, // you can enable or disable the trigger of the query on the component mount
abiJSON: yourImportedAbiJSONObject // required for SCQueryType.COMPLEX type
Expand All @@ -172,7 +172,7 @@ const { data } = useScQuery<TypedOutcomeBundle>({
payload: {
scAddress: 'erd1qqq...',
funcName: 'yourScFunction',
args: [], // args in hex format, use erdjs for conversion, see above
args: [], // args in hex format, use sdk-core for conversion, see above
},
autoInit: true,
abiJSON,
Expand All @@ -193,7 +193,7 @@ interface TypedOutcomeBundle {
}
```

You can then process the data. For example `data.firstValue.valueOf()` or `data.firstValue.toString()` if applicable. The returned type can be further processed using erdjs.
You can then process the data. For example `data.firstValue.valueOf()` or `data.firstValue.toString()` if applicable. The returned type can be further processed using sdk-core.

#### useLoggingIn()

Expand Down
4 changes: 2 additions & 2 deletions components/demo/SimpleDemo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export const SimpleDemo = () => {
</Box>
{loginMethod === LoginMethodsEnum.walletconnect && (
<Box>
Confirm it on the Maiar mobile app and wait till it finishes.
Confirm it on the xPortal mobile app and wait till it finishes.
</Box>
)}
{loginMethod === LoginMethodsEnum.ledger && (
Expand Down Expand Up @@ -143,7 +143,7 @@ export const SimpleDemo = () => {
<Text fontWeight="black" fontSize="xl" display="inline-block">
{result.content}
</Text>{' '}
NFTs to mint left!
NFTs left to mint!
</Box>
</>
)}
Expand Down
2 changes: 1 addition & 1 deletion components/tools/ActionButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const ActionButton: FC<PropsWithChildren<ActionButtonProps>> = ({
}) => {
const handleClick = useCallback(() => {
if (!disabled) {
onClick?.();
onClick();
}
}, [disabled, onClick]);

Expand Down
2 changes: 1 addition & 1 deletion components/tools/MobileLoginQR.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export const MobileLoginQR: FunctionComponent<MobileLoginQRProps> = ({
rel="noopener noreferrer nofollow"
target="_blank"
>
Maiar Login
xPortal Login
</Box>
</Flex>
) : null}
Expand Down
3 changes: 2 additions & 1 deletion config/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ export const networkConfig: Record<string, NetworkType> = {
walletConnectBridgeAddresses: ['https://bridge.walletconnect.org'],
walletAddress: 'https://devnet-wallet.multiversx.com',
apiAddress:
process.env.NEXT_PUBLIC_MULTIVERSX_API || 'https://devnet-api.multiversx.com',
process.env.NEXT_PUBLIC_MULTIVERSX_API ||
'https://devnet-api.multiversx.com',
explorerAddress: 'https://devnet-explorer.multiversx.com',
apiTimeout: '4000',
},
Expand Down
6 changes: 3 additions & 3 deletions hooks/auth/useNetworkSync.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ export const useNetworkSync = () => {
if (!dappProvider) {
const networkConfiguration = getActiveNetworkConfiguration();
switch (loginMethod) {
// Browser extension auth (Maiar defi wallet)
// Browser extension auth (MultiversX defi wallet)
case LoginMethodsEnum.extension:
dappProvider = ExtensionProvider.getInstance();
try {
Expand All @@ -154,7 +154,7 @@ export const useNetworkSync = () => {
console.warn("Can't initialize the Dapp Provider!");
}
break;
// Maiar mobile app auth
// xPortal mobile app auth
case LoginMethodsEnum.walletconnect:
const providerHandlers = {
onClientLogin: () =>
Expand All @@ -178,7 +178,7 @@ export const useNetworkSync = () => {
await dappProvider.init();
if (!dappProvider.isInitialized()) {
console.warn(
'Something went wrong trying to sync with the Maiar app!'
'Something went wrong trying to sync with the xPortal app!'
);
} else {
network.setNetworkState('dappProvider', dappProvider);
Expand Down
23 changes: 19 additions & 4 deletions hooks/core/common-helpers/sendTxOperations.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
// Tools used internally by sent transactions hooks
import { Account, TransactionWatcher, Transaction } from '@multiversx/sdk-core';
import {
Account,
TransactionWatcher,
Transaction,
ITransactionOnNetwork,
} from '@multiversx/sdk-core';
import { ExtensionProvider } from '@multiversx/sdk-extension-provider';
import { WalletConnectProvider } from '@multiversx/sdk-wallet-connect-provider';
import { HWProvider } from '@multiversx/sdk-hw-provider';
Expand All @@ -15,18 +20,21 @@ export interface TransactionCb {
transaction?: Transaction | null;
error?: string;
pending?: boolean;
txResult?: ITransactionOnNetwork | null;
}

export const postSendTxOperations = async (
tx: Transaction,
setTransaction: Dispatch<SetStateAction<Transaction | null>>,
setTxResult: Dispatch<SetStateAction<ITransactionOnNetwork | null>>,
apiNetworkProvider: ApiNetworkProvider,
cb?: (params: TransactionCb) => void
) => {
const transactionWatcher = new TransactionWatcher(apiNetworkProvider);
await transactionWatcher.awaitCompleted(tx);
const txResult = await transactionWatcher.awaitCompleted(tx);
setTransaction(tx);
cb?.({ transaction: tx, pending: false });
setTxResult(txResult);
cb?.({ transaction: tx, pending: false, txResult });
const sender = tx.getSender();
const senderAccount = new Account(sender);
const userAccountOnNetwork = await apiNetworkProvider.getAccount(sender);
Expand All @@ -42,6 +50,7 @@ export const sendTxOperations = async (
loginInfoSnap: LoginInfoState,
apiNetworkProvider: ApiNetworkProvider,
setTransaction: Dispatch<SetStateAction<Transaction | null>>,
setTxResult: Dispatch<SetStateAction<ITransactionOnNetwork | null>>,
setError: Dispatch<SetStateAction<string>>,
setPending: Dispatch<SetStateAction<boolean>>,
webWalletRedirectUrl?: string,
Expand All @@ -65,7 +74,13 @@ export const sendTxOperations = async (
}
if (loginInfoSnap.loginMethod !== LoginMethodsEnum.wallet) {
await apiNetworkProvider.sendTransaction(tx);
await postSendTxOperations(tx, setTransaction, apiNetworkProvider, cb);
await postSendTxOperations(
tx,
setTransaction,
setTxResult,
apiNetworkProvider,
cb
);
}
} catch (e) {
const err = errorParse(e);
Expand Down
5 changes: 4 additions & 1 deletion hooks/core/common-helpers/useWebWalletTxSend.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
WALLET_PROVIDER_CALLBACK_PARAM,
WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED,
} from '@multiversx/sdk-web-wallet-provider';
import { Transaction } from '@multiversx/sdk-core';
import { Transaction, ITransactionOnNetwork } from '@multiversx/sdk-core';
import { useSnapshot } from 'valtio';
import { getParamFromUrl } from '../../../utils/getParamFromUrl';
import { getNetworkState } from '../../../store/network';
Expand All @@ -16,13 +16,15 @@ import { errorParse } from '../../../utils/errorParse';
interface UseWebWalletTxSendProps {
setPending: Dispatch<SetStateAction<boolean>>;
setTransaction: Dispatch<SetStateAction<Transaction | null>>;
setTxResult: Dispatch<SetStateAction<ITransactionOnNetwork | null>>;
setError: Dispatch<SetStateAction<string>>;
cb?: (params: TransactionCb) => void;
}

export const useWebWalletTxSend = ({
setPending,
setTransaction,
setTxResult,
cb,
setError,
}: UseWebWalletTxSendProps) => {
Expand Down Expand Up @@ -56,6 +58,7 @@ export const useWebWalletTxSend = ({
await postSendTxOperations(
transaction,
setTransaction,
setTxResult,
apiNetworkProvider,
cb
);
Expand Down
2 changes: 1 addition & 1 deletion hooks/core/useScQuery.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export function useScQuery<T extends number | string | boolean | unknown>({

const parseData = (data: string | number | undefined | unknown) => {
if (data === undefined || data === null) return;

if (type === SCQueryType.COMPLEX && !abiJSON) {
throw new Error(
'Please provide the ABI JSON contents if you want to use the COMPLEX queries in useScQuery! Check README.md for more info.'
Expand Down
10 changes: 9 additions & 1 deletion hooks/core/useScTransaction.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// This hook is an abstraction for standard useTransaction, it hides the payload preparation for smart contract
// In the future both will be merged in one

/* eslint-disable react-hooks/exhaustive-deps */
import {
ContractFunction,
Expand All @@ -6,6 +9,7 @@ import {
TypedValue,
TokenPayment,
ContractCallPayloadBuilder,
ITransactionOnNetwork,
} from '@multiversx/sdk-core';
import { ApiNetworkProvider } from '@multiversx/sdk-network-providers';
import { useSnapshot } from 'valtio';
Expand Down Expand Up @@ -42,6 +46,7 @@ export function useScTransaction(
const [pending, setPending] = useState(false);
const [error, setError] = useState('');
const [transaction, setTransaction] = useState<Transaction | null>(null);
const [txResult, setTxResult] = useState<ITransactionOnNetwork | null>(null);
const accountSnap = useSnapshot(accountState);
const loginInfoSnap = useSnapshot(loginInfoState);

Expand All @@ -50,7 +55,7 @@ export function useScTransaction(
getNetworkState<ApiNetworkProvider>('apiNetworkProvider');
const currentNonce = accountSnap.nonce;

useWebWalletTxSend({ setPending, setTransaction, setError, cb });
useWebWalletTxSend({ setPending, setTransaction, setTxResult, setError, cb });

const triggerTx = async ({
smartContractAddress,
Expand All @@ -60,6 +65,7 @@ export function useScTransaction(
value,
}: ScTransactionParams) => {
setTransaction(null);
setTxResult(null);
setError('');
if (
dappProvider &&
Expand Down Expand Up @@ -94,6 +100,7 @@ export function useScTransaction(
loginInfoSnap,
apiNetworkProvider,
setTransaction,
setTxResult,
setError,
setPending,
webWalletRedirectUrl,
Expand All @@ -110,6 +117,7 @@ export function useScTransaction(
pending,
triggerTx,
transaction,
txResult,
error,
};
}
7 changes: 6 additions & 1 deletion hooks/core/useTransaction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
ITransactionPayload,
IGasLimit,
TokenPayment,
ITransactionOnNetwork,
} from '@multiversx/sdk-core';
import { ApiNetworkProvider } from '@multiversx/sdk-network-providers';
import { useSnapshot } from 'valtio';
Expand Down Expand Up @@ -40,6 +41,7 @@ export function useTransaction(
const [pending, setPending] = useState(false);
const [error, setError] = useState('');
const [transaction, setTransaction] = useState<Transaction | null>(null);
const [txResult, setTxResult] = useState<ITransactionOnNetwork | null>(null);
const accountSnap = useSnapshot(accountState);
const loginInfoSnap = useSnapshot(loginInfoState);

Expand All @@ -48,7 +50,7 @@ export function useTransaction(
getNetworkState<ApiNetworkProvider>('apiNetworkProvider');
const currentNonce = accountSnap.nonce;

useWebWalletTxSend({ setPending, setTransaction, setError, cb });
useWebWalletTxSend({ setPending, setTransaction, setTxResult, setError, cb });

const triggerTx = async ({
address,
Expand All @@ -57,6 +59,7 @@ export function useTransaction(
value,
}: TransactionParams) => {
setTransaction(null);
setTxResult(null);
setError('');

if (
Expand Down Expand Up @@ -87,6 +90,7 @@ export function useTransaction(
loginInfoSnap,
apiNetworkProvider,
setTransaction,
setTxResult,
setError,
setPending,
webWalletRedirectUrl,
Expand All @@ -103,6 +107,7 @@ export function useTransaction(
pending,
triggerTx,
transaction,
txResult,
error,
};
}
Loading

0 comments on commit 48aa498

Please sign in to comment.