Skip to content

Commit

Permalink
Adjust extrinsics using v2/v1 weights (#8193)
Browse files Browse the repository at this point in the history
* Adjust for v2 weights

* readability

* Remove unused param

* Renaming system events

* useWeight adjustment

* Remove (now) misplaced comment

* Adjust tests
  • Loading branch information
jacogr authored Oct 4, 2022
1 parent 88126da commit 38e2280
Show file tree
Hide file tree
Showing 10 changed files with 56 additions and 26 deletions.
1 change: 1 addition & 0 deletions packages/page-accounts/src/Accounts/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,7 @@ describe('Accounts page', () => {
mockApiHooks.setDelegations([{ asDelegating: { target: bob as unknown as AccountId } as unknown as VotingDelegating, isDelegating: true } as Voting]);
mockApiHooks.setProxies([[[{ delegate: alice as unknown as AccountId, proxyType: { isAny: true, isGovernance: true, isNonTransfer: true, isStaking: true, toNumber: () => 1 } } as unknown as ProxyDefinition], new BN(1)]]);
});

describe('when genesis hash is not set', () => {
beforeEach(async () => {
accountsPage.renderAccountsWithDefaultAddresses(
Expand Down
10 changes: 6 additions & 4 deletions packages/page-accounts/src/modals/MultisigApprove.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ function MultisigApprove ({ className = '', onClose, ongoing, threshold, who }:
const { allAccounts } = useAccounts();
const [callHex, setCallHex] = useState<string>('');
const [{ callData, callError, callInfo }, setCallData] = useState<CallData>(EMPTY_CALL);
const { encodedCallLength, v1Weight } = useWeight(callData);
const { encodedCallLength, weight } = useWeight(callData);
const [hash, setHash] = useState<string | null>(() => ongoing[0][0].toHex());
const [{ isMultiCall, multisig }, setMultisig] = useState<MultiInfo>(() => ({ isMultiCall: false, multisig: null }));
const [isCallOverride, setCallOverride] = useState(true);
Expand Down Expand Up @@ -139,20 +139,22 @@ function MultisigApprove ({ className = '', onClose, ongoing, threshold, who }:
? isMultiCall && isCallOverride
? callData
? multiMod.asMulti.meta.args.length === 6
? multiMod.asMulti(threshold, others, multisig.when, callData.toHex(), false, v1Weight)
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
? multiMod.asMulti(threshold, others, multisig.when, callData.toHex(), false, weight as any)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore (We are doing toHex here since we have a Vec<u8> input)
: multiMod.asMulti(threshold, others, multisig.when, callData)
: null
: multiMod.approveAsMulti.meta.args.length === 5
? multiMod.approveAsMulti(threshold, others, multisig.when, hash, v1Weight)
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
? multiMod.approveAsMulti(threshold, others, multisig.when, hash, weight as any)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
: multiMod.approveAsMulti(threshold, others, multisig.when, hash)
: multiMod.cancelAsMulti(threshold, others, multisig.when, hash)
: null
);
}, [api, callData, hash, isCallOverride, isMultiCall, others, multisig, threshold, type, v1Weight]);
}, [api, callData, hash, isCallOverride, isMultiCall, others, multisig, threshold, type, weight]);

const isAye = type === 'aye';

Expand Down
4 changes: 2 additions & 2 deletions packages/page-council/src/Motions/Close.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ function Close ({ hasFailed, hash, idNumber, proposal }: Props): React.ReactElem
const { api } = useApi();
const [isOpen, toggleOpen] = useToggle();
const [accountId, setAccountId] = useState<string | null>(null);
const { encodedCallLength, v1Weight } = useWeight(proposal);
const { encodedCallLength, weight } = useWeight(proposal);
const modLocation = useCollectiveInstance('council');

// protect against older versions
Expand Down Expand Up @@ -63,7 +63,7 @@ function Close ({ hasFailed, hash, idNumber, proposal }: Props): React.ReactElem
api.tx[modLocation].close.meta.args.length === 4
? hasFailed
? [hash, idNumber, 0, 0]
: [hash, idNumber, v1Weight, encodedCallLength]
: [hash, idNumber, weight, encodedCallLength]
: [hash, idNumber]
}
tx={api.tx[modLocation].closeOperational || api.tx[modLocation].close}
Expand Down
7 changes: 6 additions & 1 deletion packages/page-explorer/src/BlockInfo/ByHash.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ function BlockByHash ({ className = '', error, value }: Props): React.ReactEleme
[api, runtimeVersion]
);

const systemEvents = useMemo(
() => events && events.filter(({ record: { phase } }) => !phase.isApplyExtrinsic),
[events]
);

useEffect((): void => {
value && Promise
.all([
Expand Down Expand Up @@ -162,7 +167,7 @@ function BlockByHash ({ className = '', error, value }: Props): React.ReactEleme
<Events
error={evtError}
eventClassName='explorer--BlockByHash-block'
events={events && events.filter(({ record: { phase } }) => !phase.isApplyExtrinsic)}
events={systemEvents}
label={t<string>('system events')}
/>
</Columar.Column>
Expand Down
6 changes: 5 additions & 1 deletion packages/page-explorer/src/BlockInfo/Summary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ function extractEventDetails (events?: KeyedEvent[] | null): [BN?, BN?, BN?] {
? transfers.iadd(data[2] as Balance)
: transfers,
section === 'system' && ['ExtrinsicFailed', 'ExtrinsicSuccess'].includes(method)
? weight.iadd(convertWeight(((method === 'ExtrinsicSuccess' ? data[0] : data[1]) as DispatchInfo).weight).v1Weight)
? weight.iadd(
convertWeight(
((method === 'ExtrinsicSuccess' ? data[0] : data[1]) as DispatchInfo).weight
).v1Weight
)
: weight
], [new BN(0), new BN(0), new BN(0)])
: [];
Expand Down
4 changes: 2 additions & 2 deletions packages/page-tech-comm/src/Proposals/Close.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ function Close ({ hasFailed, hash, idNumber, proposal, type }: Props): React.Rea
const { api } = useApi();
const [isOpen, toggleOpen] = useToggle();
const [accountId, setAccountId] = useState<string | null>(null);
const { encodedCallLength, v1Weight } = useWeight(proposal);
const { encodedCallLength, weight } = useWeight(proposal);
const modLocation = useCollectiveInstance(type);

if (!modLocation) {
Expand Down Expand Up @@ -64,7 +64,7 @@ function Close ({ hasFailed, hash, idNumber, proposal, type }: Props): React.Rea
api.tx[modLocation].close.meta.args.length === 4
? hasFailed
? [hash, idNumber, 0, 0]
: [hash, idNumber, v1Weight, encodedCallLength]
: [hash, idNumber, weight, encodedCallLength]
: [hash, idNumber]
}
tx={api.tx[modLocation].closeOperational || api.tx[modLocation].close}
Expand Down
10 changes: 3 additions & 7 deletions packages/react-hooks/src/useTxBatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,8 @@ function useTxBatchImpl (txs?: SubmittableExtrinsic<'promise'>[] | null | false,
txs && txs.length && allAccounts[0] && api.call.transactionPaymentApi &&
nextTick(async (): Promise<void> => {
try {
const weight = convertWeight(
(
await txs[0].paymentInfo(allAccounts[0])
).weight
);
const paymentInfo = await txs[0].paymentInfo(allAccounts[0]);
const weight = convertWeight(paymentInfo.weight);
const maxBlock = convertWeight(
api.consts.system.blockWeights
? api.consts.system.blockWeights.maxBlock
Expand All @@ -65,8 +62,7 @@ function useTxBatchImpl (txs?: SubmittableExtrinsic<'promise'>[] | null | false,
weight.v1Weight.isZero()
? prev
: Math.floor(
maxBlock
.v1Weight
maxBlock.v1Weight
.muln(64) // 65% of the block weight on a single extrinsic (64 for safety)
.div(weight.v1Weight)
.toNumber() / 100
Expand Down
28 changes: 22 additions & 6 deletions packages/react-hooks/src/useWeight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type { BN } from '@polkadot/util';

import { useEffect, useState } from 'react';

import { BN_ZERO, nextTick } from '@polkadot/util';
import { BN_ZERO, isFunction, nextTick, objectSpread } from '@polkadot/util';

import { createNamedHook } from './createNamedHook';
import { useApi } from './useApi';
Expand All @@ -26,16 +26,19 @@ interface V2WeightConstruct {

interface Result {
encodedCallLength: number;
isWeightV2: boolean;
v1Weight: BN;
v2Weight: V2WeightConstruct;
weight: BN | V2WeightConstruct;
}

// a random address that we are using for our queries
const ZERO_ACCOUNT = '5CAUdnwecHGxxyr5vABevAfZ34Fi4AaraDRMwfDQXQ52PXqg';
const EMPTY_STATE: Result = {
const EMPTY_STATE: Partial<Result> = {
encodedCallLength: 0,
v1Weight: BN_ZERO,
v2Weight: { refTime: BN_ZERO }
v2Weight: { refTime: BN_ZERO },
weight: BN_ZERO
};

// return both v1 & v2 weight structures (would depend on actual use)
Expand All @@ -55,7 +58,9 @@ export function convertWeight (weight: V1Weight | V2Weight): { v1Weight: BN, v2W
function useWeightImpl (call?: Call | null): Result {
const { api } = useApi();
const mountedRef = useIsMountedRef();
const [state, setState] = useState(EMPTY_STATE);
const [state, setState] = useState<Result>(() => objectSpread({
isWeightV2: !isFunction(api.registry.createType('Weight').toBn)
}, EMPTY_STATE));

useEffect((): void => {
if (call && api.call.transactionPaymentApi) {
Expand All @@ -65,13 +70,24 @@ function useWeightImpl (call?: Call | null): Result {
(await api.tx(call).paymentInfo(ZERO_ACCOUNT)).weight
);

mountedRef.current && setState({ encodedCallLength: call.encodedLength, v1Weight, v2Weight });
mountedRef.current && setState((prev) =>
objectSpread({}, prev, {
encodedCallLength: call.encodedLength,
v1Weight,
v2Weight,
weight: prev.isWeightV2
? v2Weight
: v1Weight
})
);
} catch (error) {
console.error(error);
}
});
} else {
setState(EMPTY_STATE);
setState((prev) =>
objectSpread({}, prev, EMPTY_STATE)
);
}
}, [api, call, mountedRef]);

Expand Down
7 changes: 5 additions & 2 deletions packages/react-signer/src/TxSigned.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,13 @@ async function wrapTx (api: ApiPromise, currentItem: QueueTx, { isMultiCall, mul

if (multiRoot) {
const multiModule = api.tx.multisig ? 'multisig' : 'utility';
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const [info, { weight }] = await Promise.all([
api.query[multiModule].multisigs<Option<Multisig>>(multiRoot, tx.method.hash),
tx.paymentInfo(multiRoot)
tx.paymentInfo(multiRoot) as Promise<{ weight: any }>
]);

console.log('multisig max weight=', weight.toString());
console.log('multisig max weight=', (weight as string).toString());

const { threshold, who } = extractExternal(multiRoot);
const others = who.filter((w) => w !== signAddress);
Expand All @@ -138,11 +139,13 @@ async function wrapTx (api: ApiPromise, currentItem: QueueTx, { isMultiCall, mul
tx = isMultiCall
? api.tx[multiModule].asMulti.meta.args.length === 6
// We are doing toHex here since we have a Vec<u8> input
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
? api.tx[multiModule].asMulti(threshold, others, timepoint, tx.method.toHex(), false, weight)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
: api.tx[multiModule].asMulti(threshold, others, timepoint, tx.method)
: api.tx[multiModule].approveAsMulti.meta.args.length === 5
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
? api.tx[multiModule].approveAsMulti(threshold, others, timepoint, tx.method.hash, weight)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Expand Down
5 changes: 4 additions & 1 deletion packages/test-support/src/pages/Page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ export abstract class Page {
});

const noop = () => Promise.resolve(() => { /**/ });
const registry = new TypeRegistry();
const api = {
consts: {
babe: {
Expand Down Expand Up @@ -153,7 +154,7 @@ export abstract class Page {
account: noop
}
},
genesisHash: new TypeRegistry().createType('Hash', POLKADOT_GENESIS),
genesisHash: registry.createType('Hash', POLKADOT_GENESIS),
query: {
democracy: {
votingOf: noop
Expand All @@ -165,6 +166,8 @@ export abstract class Page {
registry: {
chainDecimals: [12],
chainTokens: ['Unit'],
createType: (...args: Parameters<typeof registry.createType>) =>
registry.createType(...args),
lookup: {
names: []
}
Expand Down

0 comments on commit 38e2280

Please sign in to comment.