Skip to content

Commit

Permalink
Migrate sign and send
Browse files Browse the repository at this point in the history
  • Loading branch information
nikitayutanov committed Aug 8, 2024
1 parent 9af1ec5 commit c66deef
Show file tree
Hide file tree
Showing 11 changed files with 42 additions and 403 deletions.
2 changes: 0 additions & 2 deletions idea/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"@hcaptcha/react-hcaptcha": "1.8.1",
"@hookform/resolvers": "3.3.2",
"@polkadot/api": "11.0.2",
"@polkadot/extension-dapp": "0.46.5",
"@polkadot/react-identicon": "3.6.3",
"@polkadot/types": "11.0.2",
"@polkadot/util": "12.6.2",
Expand Down Expand Up @@ -44,7 +43,6 @@
"zod": "3.22.4"
},
"devDependencies": {
"@polkadot/extension-inject": "^0.50.1",
"@types/lodash.isequal": "4.5.6",
"@types/lodash.isplainobject": "4.0.7",
"@types/lodash.isstring": "4.0.7",
Expand Down
7 changes: 3 additions & 4 deletions idea/frontend/src/hooks/use-sign-and-send.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { DEFAULT_ERROR_OPTIONS, DEFAULT_SUCCESS_OPTIONS, useAccount, useAlert }
import { AddressOrPair, SubmittableExtrinsic } from '@polkadot/api/types';
import { Event } from '@polkadot/types/interfaces';
import { ISubmittableResult } from '@polkadot/types/types';
import { web3FromSource } from '@polkadot/extension-dapp';
import { ReactNode } from 'react';

import { getErrorMessage } from '@/shared/helpers';
Expand Down Expand Up @@ -30,7 +29,7 @@ const DEFAULT_OPTIONS = {
} as const;

function useSignAndSend() {
const { account } = useAccount();
const { account, signer } = useAccount();
const alert = useAlert();
const getExtrinsicFailedMessage = useExtrinsicFailedMessage();

Expand Down Expand Up @@ -82,7 +81,7 @@ function useSignAndSend() {

return (extrinsic: Extrinsic, method: string, options?: Partial<Options>) => {
if (!account) throw new Error('Account is not found');
const { address, meta } = account;
const { address } = account;

const optionsWithDefaults = { ...DEFAULT_OPTIONS, ...options };
const { onError, onFinally, addressOrPair } = optionsWithDefaults;
Expand All @@ -95,7 +94,7 @@ function useSignAndSend() {
const signAndSend = () =>
addressOrPair
? extrinsic.signAndSend(addressOrPair, statusCallback)
: web3FromSource(meta.source).then(({ signer }) => extrinsic.signAndSend(address, { signer }, statusCallback));
: extrinsic.signAndSend(address, { signer }, statusCallback);

signAndSend().catch((error) => {
alert.update(alertId, getErrorMessage(error), DEFAULT_ERROR_OPTIONS);
Expand Down
11 changes: 3 additions & 8 deletions idea/frontend/src/hooks/useCodeUpload/useCodeUpload.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { web3FromSource } from '@polkadot/extension-dapp';
import { HexString } from '@polkadot/util/types';
import { useApi, useAccount } from '@gear-js/react-hooks';

Expand All @@ -10,7 +9,7 @@ import { ParamsToUploadCode } from './types';

const useCodeUpload = () => {
const { api, isApiReady } = useApi();
const { account } = useAccount();
const { account, signer } = useAccount();
const { showModal } = useModal();

const addMetadata = useAddMetadata();
Expand All @@ -33,12 +32,8 @@ const useCodeUpload = () => {
if (!isApiReady) throw new Error('API is not initialized');
if (!account) throw new Error('Account not found');

const { address, meta } = account;

const [{ codeHash, extrinsic: codeExtrinsic }, { signer }] = await Promise.all([
api.code.upload(optBuffer),
web3FromSource(meta.source),
]);
const { address } = account;
const { codeHash, extrinsic: codeExtrinsic } = await api.code.upload(optBuffer);

const extrinsic = voucherId ? api.voucher.call(voucherId, { UploadCode: codeExtrinsic }) : codeExtrinsic;
const { partialFee } = await api.code.paymentInfo(address, { signer });
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { useApi, useAlert, useAccount } from '@gear-js/react-hooks';
import { web3FromSource } from '@polkadot/extension-dapp';
import { useCallback } from 'react';

import { useModal, useSignAndSend } from '@/hooks';
Expand All @@ -11,7 +10,7 @@ import { ParamsToSendMessage, ParamsToReplyMessage } from './types';

const useMessageActions = () => {
const { api, isApiReady } = useApi();
const { account } = useAccount();
const { account, signer } = useAccount();
const alert = useAlert();
const { showModal } = useModal();
const signAndSend = useSignAndSend();
Expand All @@ -22,13 +21,12 @@ const useMessageActions = () => {
if (!isApiReady) throw new Error('API is not initialized');
checkWallet(account);

const { meta, address } = account!;
const { address } = account!;

const sendExtrinsic = api.message.send(message, metadata, payloadType);

const extrinsic = voucherId ? api.voucher.call(voucherId, { SendMessage: sendExtrinsic }) : sendExtrinsic;

const { signer } = await web3FromSource(meta.source);
const { partialFee } = await api.message.paymentInfo(address, { signer });

const handleConfirm = () =>
Expand Down Expand Up @@ -60,13 +58,12 @@ const useMessageActions = () => {
if (!isApiReady) throw new Error('API is not initialized');
checkWallet(account);

const { meta, address } = account!;
const { address } = account!;

const replyExtrinsic = await api.message.sendReply(reply, metadata, payloadType);

const extrinsic = voucherId ? api.voucher.call(voucherId, { SendReply: replyExtrinsic }) : replyExtrinsic;

const { signer } = await web3FromSource(meta.source);
const { partialFee } = await api.message.paymentInfo(address, { signer });

const handleConfirm = () =>
Expand Down
19 changes: 6 additions & 13 deletions idea/frontend/src/hooks/useMessageClaim/useMessageClaim.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
import { useCallback } from 'react';
import { EventRecord } from '@polkadot/types/interfaces';
import { web3FromSource } from '@polkadot/extension-dapp';
import { UserMessageRead } from '@gear-js/api';
import { useApi, useAccount, useAlert, DEFAULT_SUCCESS_OPTIONS, DEFAULT_ERROR_OPTIONS } from '@gear-js/react-hooks';

import { useModal } from '@/hooks';
import { Method } from '@/features/explorer';
import { OperationCallbacks, ParamsToSignAndSend } from '@/entities/hooks';
import { OperationCallbacks } from '@/entities/hooks';
import { PROGRAM_ERRORS, TransactionName, TransactionStatus } from '@/shared/config';
import { checkWallet, getExtrinsicFailedMessage } from '@/shared/helpers';

import { ParamsToClaimMessage } from './types';

const useMessageClaim = () => {
const { api, isApiReady } = useApi();
const { account } = useAccount();
const { account, signer } = useAccount();
const alert = useAlert();
const { showModal } = useModal();

Expand All @@ -30,7 +29,7 @@ const useMessageClaim = () => {
const reasonKey = Object.keys(reason)[0];
const reasonValue = reason[reasonKey];

const message = `${data.id.toHuman()}\n ${reasonKey}: ${reasonValue}`;
const message = `${data.id.toHuman() as string}\n ${reasonKey}: ${reasonValue}`;

alert.success(message, alertOptions);
} else if (method === Method.ExtrinsicFailed) {
Expand All @@ -41,7 +40,7 @@ const useMessageClaim = () => {
});
};

const signAndSend = async ({ signer, reject, resolve }: ParamsToSignAndSend) => {
const signAndSend = async ({ reject, resolve }: OperationCallbacks) => {
const alertId = alert.loading('SignIn', { title: TransactionName.ClaimMessage });

try {
Expand Down Expand Up @@ -78,19 +77,13 @@ const useMessageClaim = () => {
if (!isApiReady) throw new Error('API is not initialized');
checkWallet(account);

const { meta, address } = account!;
const { address } = account!;

api.claimValueFromMailbox.submit(messageId);

const { signer } = await web3FromSource(meta.source);
const { partialFee } = await api.claimValueFromMailbox.paymentInfo(address, { signer });

const handleConfirm = () =>
signAndSend({
signer,
reject,
resolve,
});
const handleConfirm = () => signAndSend({ reject, resolve });

showModal('transaction', {
fee: partialFee.toHuman(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { useApi, useAccount } from '@gear-js/react-hooks';
import { web3FromSource } from '@polkadot/extension-dapp';
import { ISubmittableResult } from '@polkadot/types/types';
import { generatePath } from 'react-router-dom';

Expand All @@ -14,7 +13,7 @@ import { ContractApi, Program, Values } from './types';

const useProgramActions = () => {
const { api, isApiReady } = useApi();
const { account } = useAccount();
const { account, signer } = useAccount();
const { isDevChain } = useChain();

const addMetadata = useAddMetadata();
Expand Down Expand Up @@ -69,8 +68,7 @@ const useProgramActions = () => {
if (!isApiReady) throw new Error('API is not initialized');
if (!account) throw new Error('Account not found');

const { meta, address } = account;
const { signer } = await web3FromSource(meta.source);
const { address } = account;
const { partialFee } = await api.program.paymentInfo(address, { signer });

const successAlert = getSuccessAlert(program.programId);
Expand Down
4 changes: 1 addition & 3 deletions utils/gear-hooks/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,13 @@
"peerDependencies": {
"@gear-js/api": "0.38.1",
"@polkadot/api": "11.0.2",
"@polkadot/extension-dapp": "0.46.5",
"@tanstack/react-query": "5.29.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"sails-js": "0.1.8"
},
"dependencies": {
"@polkadot/api-derive": "11.0.2",
"@polkadot/extension-inject": "0.46.5",
"@polkadot/util": "12.6.2",
"@substrate/connect": "0.8.10",
"bignumber.js": "9.1.2",
Expand All @@ -41,7 +39,7 @@
"devDependencies": {
"@gear-js/api": "0.38.1",
"@polkadot/api": "11.0.2",
"@polkadot/extension-dapp": "0.46.5",
"@polkadot/extension-inject": "0.51.1",
"@polkadot/types": "11.0.2",
"@rollup/plugin-commonjs": "25.0.5",
"@rollup/plugin-node-resolve": "15.2.3",
Expand Down
14 changes: 4 additions & 10 deletions utils/gear-hooks/src/hooks/api/useProgram/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { web3FromSource } from '@polkadot/extension-dapp';
import { GasLimit, ProgramMetadata } from '@gear-js/api';
import { AnyJson } from '@polkadot/types/types';
import { useAccount, useAlert, useApi } from 'context';
Expand Down Expand Up @@ -26,7 +25,7 @@ function useProgram(
): UseProgram {
const alert = useAlert();
const { api, isApiReady } = useApi();
const { account } = useAccount();
const { account, signer } = useAccount();

const { handleSignStatus, handleInitStatus, handleError } = useHandlers();

Expand All @@ -44,21 +43,16 @@ function useProgram(
const program = { [codeKey]: codeOrCodeId, initPayload, gasLimit, value, salt };
const callbacks = { onSuccess, onError };

const { meta, address } = account;
const { source } = meta;
const { address } = account;

// @ts-ignore
const { programId } = api.program[method](program, metadata, payloadType);

const alertId = alert.loading('SignIn', { title });
const initialization = waitForProgramInit(api, programId);

return web3FromSource(source)
.then(({ signer }) =>
api.program.signAndSend(address, { signer }, (result) =>
handleSignStatus({ result, callbacks, alertId, programId }),
),
)
return api.program
.signAndSend(address, { signer }, (result) => handleSignStatus({ result, callbacks, alertId, programId }))
.then(() => initialization)
.then((status) => handleInitStatus({ status, programId, onError }))
.catch(({ message }: Error) => handleError({ message, alertId, onError }));
Expand Down
8 changes: 2 additions & 6 deletions utils/gear-hooks/src/hooks/api/useSendMessage.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { GasLimit, MessageQueued, ProgramMetadata } from '@gear-js/api';
import { web3FromSource } from '@polkadot/extension-dapp';
import { EventRecord } from '@polkadot/types/interfaces';
import { AnyJson, IKeyringPair, ISubmittableResult } from '@polkadot/types/types';
import { HexString } from '@polkadot/util/types';
Expand Down Expand Up @@ -31,7 +30,7 @@ function useSendMessage(
{ disableAlerts, pair }: UseSendMessageOptions = {},
) {
const { api, isApiReady } = useApi();
const { account } = useAccount();
const { account, signer } = useAccount();
const alert = useAlert();

const title = 'gear.sendMessage';
Expand Down Expand Up @@ -106,8 +105,7 @@ function useSendMessage(
const alertId = disableAlerts ? '' : alert.loading('Sign In', { title });

const { payload, gasLimit, value = 0, voucherId, onSuccess, onInBlock, onError } = args;
const { address, meta } = account;
const { source } = meta;
const { address } = account;

const baseMessage = { destination, payload, gasLimit, value };

Expand All @@ -123,8 +121,6 @@ function useSendMessage(
if (pair) {
await extrinsic.signAndSend(pair, callback);
} else {
const { signer } = await web3FromSource(source);

await extrinsic.signAndSend(address, { signer }, callback);
}
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { web3FromSource } from '@polkadot/extension-dapp';
import { useMutation } from '@tanstack/react-query';

import { useAccount } from 'context';
Expand All @@ -24,7 +23,7 @@ function usePrepareProgramTransaction<
serviceName,
functionName,
}: UsePrepareProgramTransactionParameters<TProgram, TServiceName, TFunctionName>) {
const { account: connectedAccount } = useAccount();
const { account: connectedAccount, signer } = useAccount();

const prepareTransaction = async ({
args,
Expand All @@ -44,8 +43,7 @@ function usePrepareProgramTransaction<
} else {
if (!connectedAccount) throw new Error('Account is not found');

const { address, meta } = connectedAccount;
const { signer } = await web3FromSource(meta.source);
const { address } = connectedAccount;
transaction.withAccount(address, { signer });
}

Expand Down
Loading

0 comments on commit c66deef

Please sign in to comment.