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

Use transaction ctx for call #178

Merged
merged 9 commits into from
Jan 14, 2022
Merged
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
92 changes: 6 additions & 86 deletions src/api/contract/call.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
// Copyright 2021 @paritytech/substrate-contracts-explorer authors & contributors
// SPDX-License-Identifier: Apache-2.0

import { BN_ZERO } from '@polkadot/util';
import { encodeSalt, transformUserInput } from 'api/util';
import { transformUserInput } from 'api/util';

import {
BlueprintOptions,
ContractQuery,
ContractOptions,
ContractTx,
ContractCallParams,
CallResult,
RegistryError,
KeyringPair,
ContractDryRunParams,
} from 'types';

let nextId = 0;

function prepareContractTx(tx: ContractTx<'promise'>, options: BlueprintOptions, args: unknown[]) {
export function prepareContractTx(
tx: ContractTx<'promise'>,
options: BlueprintOptions,
args: unknown[]
) {
return args.length > 0 ? tx(options, ...args) : tx(options);
}

Expand Down Expand Up @@ -50,81 +48,3 @@ export function dryRun({
transformed
);
}

export async function call({
contract,
message,
payment: value,
gasLimit,
sender,
argValues,
dispatch,
}: ContractCallParams) {
const salt = encodeSalt();
const transformed = transformUserInput(contract.registry, message.args, argValues);

const callResult: CallResult = {
id: ++nextId,
isComplete: false,
data: '',
log: [],
message,
time: Date.now(),
};

dispatch({ type: 'CALL_INIT', payload: callResult });
if (message.isMutating || message.isPayable) {
const tx = prepareContractTx(
contract.tx[message.method],
{ gasLimit: gasLimit.addn(1), value: message.isPayable ? value || BN_ZERO : undefined, salt },
transformed
);

const unsub = await tx.signAndSend(sender, result => {
const { status, events, dispatchError, dispatchInfo } = result;

const log = events.map(({ event }) => {
return `${event.section}:${event.method}`;
});

let error: RegistryError | undefined;

if (status.isFinalized) {
if (dispatchError) {
error = contract.registry.findMetaError(dispatchError.asModule);
}

dispatch({
type: 'CALL_FINALISED',
payload: {
...callResult,
log: log,
error,
blockHash: status.asFinalized.toString(),
info: dispatchInfo?.toHuman(),
},
});

unsub();
}
});
} else {
const { result, output } = await sendContractQuery(
contract.query[message.method],
sender,
{ gasLimit, value: message.isPayable ? value || BN_ZERO : undefined },
transformed
);

let error: RegistryError | undefined;

if (result.isErr && result.asErr.isModule) {
error = contract.registry.findMetaError(result.asErr.asModule);
}

dispatch({
type: 'CALL_FINALISED',
payload: { ...callResult, data: output?.toHuman(), error },
});
}
}
24 changes: 11 additions & 13 deletions src/types/ui/contexts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,27 +82,25 @@ export enum TxStatus {
Processing = 'processing',
Queued = 'queued',
}

export interface Transaction {
id: number;
status: TxStatus;
export interface TxOptions {
extrinsic: SubmittableExtrinsic<'promise'>;
accountId: string;
events: Record<string, number>;
isValid: (_: SubmittableResult) => boolean;
onSuccess?: (_: SubmittableResult) => Promise<void>;
onSuccess?: ((_: SubmittableResult) => void) | ((_: SubmittableResult) => Promise<void>);
onError?: () => void;
}

export type TransactionOptions = Pick<
Transaction,
'accountId' | 'extrinsic' | 'onSuccess' | 'onError' | 'isValid'
>;
export interface QueuedTxOptions extends TxOptions {
status: TxStatus;
events: Record<string, number>;
}
export interface TransactionsQueue {
[id: number]: QueuedTxOptions | undefined;
}

export interface TransactionsState {
txs: Transaction[];
txs: TransactionsQueue;
process: (_: number) => Promise<void>;
queue: (_: TransactionOptions) => number;
unqueue: (id: number) => void;
queue: (_: TxOptions) => number;
dismiss: (id: number) => void;
}
118 changes: 46 additions & 72 deletions src/ui/components/Transactions.tsx
Original file line number Diff line number Diff line change
@@ -1,81 +1,55 @@
// Copyright 2021 @paritytech/substrate-contracts-explorer authors & contributors
// SPDX-License-Identifier: Apache-2.0

import {
BellIcon,
CheckIcon,
ClockIcon,
ExclamationCircleIcon,
XIcon,
} from '@heroicons/react/outline';
import { BellIcon, XIcon } from '@heroicons/react/outline';
import React from 'react';
import { Spinner } from './common/Spinner';
import { NotificationIcon } from './common/NotificationIcon';
import type { TransactionsState } from 'types';
import { classes } from 'ui/util';
import { classes, isEmptyObj } from 'ui/util';

type Props = React.HTMLAttributes<HTMLDivElement> & TransactionsState;
export function Transactions({
dismiss,
txs,
}: React.HTMLAttributes<HTMLDivElement> & TransactionsState) {
const Notifications: JSX.Element[] = [];
for (const id in txs) {
const { extrinsic, status, events } = txs[id] || {};
const isComplete = status === 'error' || status === 'success';

export function Transactions({ className, dismiss, txs }: Props) {
return (
<div className={classes('z-10 fixed right-3 top-3 w-80', className)}>
{txs.map(({ extrinsic, id, status, events }) => {
const [icon, text] = ((): [React.ReactNode, React.ReactNode] => {
switch (status) {
case 'success':
return [
<CheckIcon key="success" className="dark:text-green-400 w-12 h-12" />,
'complete!',
];
case 'error':
return [
<ExclamationCircleIcon key="error" className="dark:text-red-400 w-12 h-12" />,
'error',
];
case 'processing':
return [<Spinner key="processing" width={12} strokeWidth={4} />, 'processing...'];

default:
return [
<ClockIcon key="queued" className={classes('dark:text-blue-500 w-12 h-12')} />,
'queued',
];
}
})();
const isComplete = status === 'error' || status === 'success';
return (
<>
<div
key={id}
className="max-w-full dark:bg-elevation-3 dark:text-white p-3 flex items-center"
>
{icon}
<div className="pl-2 flex-grow text-sm">
<div>{extrinsic.registry.findMetaCall(extrinsic.callIndex).method}</div>
<div className="dark:text-gray-400">{text}</div>
</div>
{isComplete && (
<XIcon className="dark:text-gray-400 w-4 h-4" onClick={() => dismiss(id)} />
)}
Notifications.push(
<>
<div
key={id}
className="max-w-full dark:bg-elevation-3 dark:text-white p-3 flex items-center"
>
<NotificationIcon status={status} />
<div className="pl-2 flex-grow text-sm">
<div>{extrinsic?.registry.findMetaCall(extrinsic.callIndex).method}</div>
<div className="dark:text-gray-400">{status}</div>
</div>
{isComplete && (
<XIcon className="dark:text-gray-400 w-4 h-4" onClick={() => dismiss(parseInt(id))} />
)}
</div>
{isComplete && events && !isEmptyObj(events) && (
<div className="max-w-full dark:bg-elevation-3 dark:text-white p-3 mt-2 flex items-center">
<BellIcon className="dark:text-yellow-400 w-12 h-12" />
<div className="pl-2 flex-grow text-sm">
{Object.keys(events).map(eventName => {
const times = events[eventName] > 1 ? ` (x${events[eventName]})` : '';
return (
<div key={eventName} className="dark:text-gray-400">
{`${eventName}${times}`}
</div>
);
})}
</div>
{isComplete && (
<div className="max-w-full dark:bg-elevation-3 dark:text-white p-3 mt-2 flex items-center">
<BellIcon className="dark:text-yellow-400 w-12 h-12" />
<div className="pl-2 flex-grow text-sm">
{Object.keys(events).map(eventName => {
const times = events[eventName] > 1 ? ` (x${events[eventName]})` : '';
return (
<div key={eventName} className="dark:text-gray-400">
{`${eventName}${times}`}
</div>
);
})}
</div>
<XIcon className="dark:text-gray-400 w-4 h-4" onClick={() => dismiss(id)} />
</div>
)}
</>
);
})}
</div>
);
<XIcon className="dark:text-gray-400 w-4 h-4" onClick={() => dismiss(parseInt(id))} />
</div>
)}
</>
);
}

return <div className={classes('z-10 fixed right-3 top-3 w-80')}>{...Notifications}</div>;
}
31 changes: 31 additions & 0 deletions src/ui/components/common/NotificationIcon.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright 2021 @paritytech/substrate-contracts-explorer authors & contributors
// SPDX-License-Identifier: Apache-2.0

import { CheckIcon, ClockIcon, ExclamationCircleIcon } from '@heroicons/react/outline';
import React from 'react';
import { Spinner } from './Spinner';
import { TxStatus } from 'types';
import { classes } from 'ui/util';

interface Props {
status?: TxStatus;
}

export const NotificationIcon = ({ status }: Props) => {
switch (status) {
case 'success':
return <CheckIcon key="success" className="dark:text-green-400 w-12 h-12" />;

case 'error':
return <ExclamationCircleIcon key="error" className="dark:text-red-400 w-12 h-12" />;

case 'processing':
return <Spinner key="processing" width={8} strokeWidth={2} className="m-2" />;

case 'queued':
return <ClockIcon key="queued" className={classes('dark:text-blue-500 w-12 h-12')} />;

default:
return null;
}
};
Loading