@polkadot/util#BN_TEN TypeScript Examples
The following examples show how to use
@polkadot/util#BN_TEN.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: util.ts From crust-apps with Apache License 2.0 | 7 votes |
/**
* This is where we tweak the input values, based on what was specified, be it the input number
* or the direction and turnout adjustments
*
* @param votes The votes that should be adjusted, will be either aye/nay
* @param total The actual total of applied votes (same as turnout from derived)
* @param change The actual change value we want to affect
* @param inc The increment to apply here
* @param totalInc The increment for the total. 0 for conviction-only changes, 1 of 1x added conviction vote
* @param direction The direction, either increment (1) or decrement (-1)
*/
function getDiffs (votes: BN, total: BN, change: BN, inc: BN, totalInc: 0 | 0.1 | 1, direction: 1 | -1): [BN, BN, BN] {
// setup
const multiplier = direction === 1 ? BN_ONE : ONEMIN;
const voteChange = change.add(inc);
// since we allow 0.1 as well, we first multiply by 10, before dividing by the same
const totalChange = BN_ONE.muln(totalInc * 10).mul(voteChange).div(BN_TEN);
// return the change, vote with change applied and the total with the same. For the total we don't want
// to go negative (total votes/turnout), since will do sqrt on it (and negative is non-sensical anyway)
return [
voteChange,
votes.add(multiplier.mul(voteChange)),
BN.max(BN_ZERO, total.add(multiplier.mul(totalChange)))
];
}
Example #2
Source File: InputCsmNumber.tsx From crust-apps with Apache License 2.0 | 6 votes |
function inputToBn (api: ApiPromise, input: string, si: SiDef | null, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): [BN, boolean] {
const [siPower, basePower, siUnitPower] = getSiPowers(si);
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
const isDecimalValue = input.match(/^(\d+)\.(\d+)$/);
let result;
if (isDecimalValue) {
if (siUnitPower - isDecimalValue[2].length < -basePower) {
result = new BN(-1);
}
const div = new BN(input.replace(/\.\d*$/, ''));
const modString = input.replace(/^\d+\./, '').substr(0, api.registry.chainDecimals[0]);
const mod = new BN(modString);
result = div
.mul(BN_TEN.pow(siPower))
.add(mod.mul(BN_TEN.pow(new BN(basePower + siUnitPower - modString.length))));
} else {
result = new BN(input.replace(/[^\d]/g, ''))
.mul(BN_TEN.pow(siPower));
}
return [
result,
isValidNumber(result, bitLength, isZeroable, maxValue)
];
}
Example #3
Source File: InputNumber.tsx From subscan-multisig-react with Apache License 2.0 | 6 votes |
function getValuesFromBn(
valueBn: BN,
si: SiDef | null,
isZeroable: boolean,
_decimals?: number
): [string, BN, boolean] {
const decimals = isUndefined(_decimals) ? formatBalance.getDefaults().decimals : _decimals;
const value = si ? valueBn.div(BN_TEN.pow(new BN(decimals + si.power))).toString() : valueBn.toString();
return [value, valueBn, isZeroable ? true : valueBn.gt(BN_ZERO)];
}
Example #4
Source File: InputNumber.tsx From subscan-multisig-react with Apache License 2.0 | 6 votes |
function inputToBn(
api: ApiPromise,
input: string,
si: SiDef | null,
bitLength: BitLength,
isZeroable: boolean,
maxValue?: BN,
decimals?: number
): [BN, boolean] {
const [siPower, basePower, siUnitPower] = getSiPowers(si, decimals);
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
const isDecimalValue = input.match(/^(\d+)\.(\d+)$/);
let result;
if (isDecimalValue) {
// eslint-disable-next-line no-magic-numbers
if (siUnitPower - isDecimalValue[2].length < -basePower) {
result = new BN(-1);
}
const div = new BN(input.replace(/\.\d*$/, ''));
const modString = input.replace(/^\d+\./, '').substr(0, api.registry.chainDecimals[0]);
const mod = new BN(modString);
result = div.mul(BN_TEN.pow(siPower)).add(mod.mul(BN_TEN.pow(new BN(basePower + siUnitPower - modString.length))));
} else {
result = new BN(input.replace(/[^\d]/g, '')).mul(BN_TEN.pow(siPower));
}
return [result, isValidNumber(result, bitLength, isZeroable, maxValue)];
}
Example #5
Source File: referendumApproxChanges.ts From sdk with Apache License 2.0 | 6 votes |
/**
* This is where we tweak the input values, based on what was specified, be it the input number
* or the direction and turnout adjustments
*
* @param votes The votes that should be adjusted, will be either aye/nay
* @param total The actual total of applied votes (same as turnout from derived)
* @param change The actual change value we want to affect
* @param inc The increment to apply here
* @param totalInc The increment for the total. 0 for conviction-only changes, 1 of 1x added conviction vote
* @param direction The direction, either increment (1) or decrement (-1)
*/
function getDiffs(
votes: BN,
total: BN,
change: BN,
inc: BN,
totalInc: 0 | 0.1 | 1,
direction: 1 | -1
): [BN, BN, BN] {
// setup
const multiplier = direction === 1 ? BN_ONE : ONEMIN;
const voteChange = change.add(inc);
// since we allow 0.1 as well, we first multiply by 10, before dividing by the same
const totalChange = BN_ONE.muln(totalInc * 10)
.mul(voteChange)
.div(BN_TEN);
// return the change, vote with change applied and the total with the same. For the total we don't want
// to go negative (total votes/turnout), since will do sqrt on it (and negative is non-sensical anyway)
return [
voteChange,
votes.add(multiplier.mul(voteChange)),
BN.max(BN_ZERO, total.add(multiplier.mul(totalChange))),
];
}
Example #6
Source File: index.ts From contracts-ui with GNU General Public License v3.0 | 6 votes |
export function toSats(api: ApiPromise, balance: BN | number): BN {
let bn: BN;
if (isNumber(balance)) {
bn = new BN(balance);
} else {
bn = balance;
}
return bn.mul(BN_TEN.pow(new BN(api.registry.chainDecimals[0])));
}
Example #7
Source File: index.ts From contracts-ui with GNU General Public License v3.0 | 6 votes |
export function toBalance(api: ApiPromise, value: string | number): BN {
const asString = isNumber(value) ? value.toString() : value;
const siPower = new BN(api.registry.chainDecimals[0]);
const isDecimalValue = /^(\d+)\.(\d+)$/.exec(asString);
if (isDecimalValue) {
const div = new BN(asString.replace(/\.\d*$/, ''));
const modString = asString.replace(/^\d+\./, '').substr(0, api.registry.chainDecimals[0]);
const mod = new BN(modString);
return div
.mul(BN_TEN.pow(siPower))
.add(mod.mul(BN_TEN.pow(new BN(siPower.subn(modString.length)))));
} else {
return new BN(asString.replace(/[^\d]/g, '')).mul(BN_TEN.pow(siPower));
}
}
Example #8
Source File: InputNumber.tsx From crust-apps with Apache License 2.0 | 6 votes |
function getValuesFromBn (valueBn: BN, si: SiDef | null, isZeroable: boolean): [string, BN, boolean] {
const value = si
? valueBn.div(BN_TEN.pow(new BN(formatBalance.getDefaults().decimals + si.power))).toString()
: valueBn.toString();
return [
value,
valueBn,
isZeroable ? true : valueBn.gt(BN_ZERO)
];
}
Example #9
Source File: InputNumber.tsx From crust-apps with Apache License 2.0 | 6 votes |
function inputToBn (api: ApiPromise, input: string, si: SiDef | null, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): [BN, boolean] {
const [siPower, basePower, siUnitPower] = getSiPowers(si);
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
const isDecimalValue = input.match(/^(\d+)\.(\d+)$/);
let result;
if (isDecimalValue) {
if (siUnitPower - isDecimalValue[2].length < -basePower) {
result = new BN(-1);
}
const div = new BN(input.replace(/\.\d*$/, ''));
const modString = input.replace(/^\d+\./, '').substr(0, api.registry.chainDecimals[0]);
const mod = new BN(modString);
result = div
.mul(BN_TEN.pow(siPower))
.add(mod.mul(BN_TEN.pow(new BN(basePower + siUnitPower - modString.length))));
} else {
result = new BN(input.replace(/[^\d]/g, ''))
.mul(BN_TEN.pow(siPower));
}
return [
result,
isValidNumber(result, bitLength, isZeroable, maxValue)
];
}
Example #10
Source File: InputCsmNumber.tsx From crust-apps with Apache License 2.0 | 6 votes |
function getValuesFromBn (valueBn: BN, si: SiDef | null): [string, BN, boolean] {
const value = si
? valueBn.div(BN_TEN.pow(new BN(formatBalance.getDefaults().decimals + si.power))).toString()
: valueBn.toString();
return [
value,
valueBn,
true
];
}
Example #11
Source File: InputCsmBalance.tsx From crust-apps with Apache License 2.0 | 6 votes |
function reformat (value: string | BN, isDisabled?: boolean): string {
if (isBn(value)) {
let fmt = (value.mul(BN_THOUSAND).div(BN_TEN.pow(new BN(formatBalance.getDefaults().decimals))).toNumber() / 1000).toFixed(3);
while (fmt.length !== 1 && ['.', '0'].includes(fmt[fmt.length - 1])) {
const isLast = fmt.endsWith('.');
fmt = fmt.substr(0, fmt.length - 1);
if (isLast) {
break;
}
}
return fmt;
}
return formatBalance(value, { forceUnit: '-', withSi: false }).replace(',', isDisabled ? ',' : '');
}
Example #12
Source File: InputCandyNumber.tsx From crust-apps with Apache License 2.0 | 6 votes |
function getValuesFromBn (valueBn: BN, si: SiDef | null): [string, BN, boolean] {
const value = si
? valueBn.div(BN_TEN.pow(new BN(formatBalance.getDefaults().decimals + si.power))).toString()
: valueBn.toString();
return [
value,
valueBn,
true
];
}
Example #13
Source File: InputCandyNumber.tsx From crust-apps with Apache License 2.0 | 6 votes |
function inputToBn (api: ApiPromise, input: string, si: SiDef | null, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): [BN, boolean] {
const [siPower, basePower, siUnitPower] = getSiPowers(si);
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
const isDecimalValue = input.match(/^(\d+)\.(\d+)$/);
let result;
if (isDecimalValue) {
if (siUnitPower - isDecimalValue[2].length < -basePower) {
result = new BN(-1);
}
const div = new BN(input.replace(/\.\d*$/, ''));
const modString = input.replace(/^\d+\./, '').substr(0, api.registry.chainDecimals[0]);
const mod = new BN(modString);
result = div
.mul(BN_TEN.pow(siPower))
.add(mod.mul(BN_TEN.pow(new BN(basePower + siUnitPower - modString.length))));
} else {
result = new BN(input.replace(/[^\d]/g, ''))
.mul(BN_TEN.pow(siPower));
}
return [
result,
isValidNumber(result, bitLength, isZeroable, maxValue)
];
}
Example #14
Source File: InputCandyBalance.tsx From crust-apps with Apache License 2.0 | 6 votes |
function reformat (value: string | BN, isDisabled?: boolean): string {
if (isBn(value)) {
let fmt = (value.mul(BN_THOUSAND).div(BN_TEN.pow(new BN(formatBalance.getDefaults().decimals))).toNumber() / 1000).toFixed(3);
while (fmt.length !== 1 && ['.', '0'].includes(fmt[fmt.length - 1])) {
const isLast = fmt.endsWith('.');
fmt = fmt.substr(0, fmt.length - 1);
if (isLast) {
break;
}
}
return fmt;
}
return formatBalance(value, { forceUnit: '-', withSi: false }).replace(',', isDisabled ? ',' : '');
}
Example #15
Source File: InputBalance.tsx From crust-apps with Apache License 2.0 | 6 votes |
function reformat (value: string | BN, isDisabled?: boolean): string {
if (isBn(value)) {
// format for 4 decimals (align with util)
const valStr = value
.mul(BN_TEN_THOUSAND)
.div(BN_TEN.pow(new BN(formatBalance.getDefaults().decimals)))
.toString()
.padStart(5, '0'); // 4 after decimal, 1 before, min 5
// dive using string format (the value may be too large for 2^53-1)
let fmt = `${valStr.substr(0, valStr.length - 4)}.${valStr.slice(-4)}`;
// remove all trailing 0's until the decimal
while (fmt.length !== 1 && ['.', '0'].includes(fmt[fmt.length - 1])) {
const isLast = fmt.endsWith('.');
fmt = fmt.substr(0, fmt.length - 1);
if (isLast) {
break;
}
}
return fmt;
}
return formatBalance(value, { forceUnit: '-', withSi: false }).replace(',', isDisabled ? ',' : '');
}
Example #16
Source File: InputValidationUnstakeThreshold.tsx From crust-apps with Apache License 2.0 | 6 votes |
function InputValidationUnstakeThreshold ({ onError, unstakeThreshold }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const [error, setError] = useState<string | null>(null);
useEffect((): void => {
if (unstakeThreshold) {
let newError: string | null = null;
if (unstakeThreshold.ltn(0)) {
newError = t<string>('The Threshold must be a positive number');
} else if (unstakeThreshold.gt(BN_TEN)) {
newError = t<string>('The Threshold must lower than 11');
}
onError(newError);
setError((error) => error !== newError ? newError : error);
}
}, [onError, t, unstakeThreshold]);
if (!error) {
return null;
}
return (
<MarkWarning content={error} />
);
}
Example #17
Source File: InputValidateAmount.tsx From crust-apps with Apache License 2.0 | 6 votes |
function formatExistential (value: BN): string {
let fmt = (value.mul(BN_THOUSAND).div(BN_TEN.pow(new BN(formatBalance.getDefaults().decimals))).toNumber() / 1000).toFixed(3);
while (fmt.length !== 1 && ['.', '0'].includes(fmt[fmt.length - 1])) {
const isLast = fmt.endsWith('.');
fmt = fmt.substr(0, fmt.length - 1);
if (isLast) {
break;
}
}
return fmt;
}
Example #18
Source File: useWeight.ts From crust-apps with Apache License 2.0 | 5 votes |
export default function useWeight (): UseWeight {
const { api } = useApi();
const [blockTime] = useBlockTime();
const [megaGas, _setMegaGas] = useState<BN>(
(api.consts.system.blockWeights
? api.consts.system.blockWeights.maxBlock
: api.consts.system.maximumBlockWeight as Weight
).div(BN_MILLION).div(BN_TEN)
);
const [isEmpty, setIsEmpty] = useState(false);
const setMegaGas = useCallback(
(value?: BN | undefined) => _setMegaGas(value || (
(api.consts.system.blockWeights
? api.consts.system.blockWeights.maxBlock
: api.consts.system.maximumBlockWeight as Weight
).div(BN_MILLION).div(BN_TEN)
)),
[api]
);
return useMemo((): UseWeight => {
let executionTime = 0;
let percentage = 0;
let weight = BN_ZERO;
let isValid = false;
if (megaGas) {
weight = megaGas.mul(BN_MILLION);
executionTime = weight.muln(blockTime).div(
api.consts.system.blockWeights
? api.consts.system.blockWeights.maxBlock
: api.consts.system.maximumBlockWeight as Weight
).toNumber();
percentage = (executionTime / blockTime) * 100;
// execution is 2s of 6s blocks, i.e. 1/3
executionTime = executionTime / 3000;
isValid = !megaGas.isZero() && percentage < 65;
}
return {
executionTime,
isEmpty,
isValid: isEmpty || isValid,
megaGas: megaGas || BN_ZERO,
percentage,
setIsEmpty,
setMegaGas,
weight
};
}, [api, blockTime, isEmpty, megaGas, setIsEmpty, setMegaGas]);
}
Example #19
Source File: index.ts From contracts-ui with GNU General Public License v3.0 | 5 votes |
export function fromSats(api: ApiPromise, sats: BN): string {
const pow = BN_TEN.pow(new BN(api.registry.chainDecimals[0]));
const [div, mod] = [sats.div(pow), sats.mod(pow)];
return `${div.toString()}${!mod.eqn(0) ? `.${mod.toString()}` : ''}`;
}
Example #20
Source File: useWeight.ts From contracts-ui with GNU General Public License v3.0 | 5 votes |
function getDefaultMegaGas(api: OrFalsy<ApiPromise>, estimatedWeight?: OrFalsy<BN>): BN {
if (api && estimatedWeight) {
return getEstimatedMegaGas(api, estimatedWeight);
}
return maximumBlockWeight(api).div(BN_MILLION).div(BN_TEN);
}
Example #21
Source File: ReferendumVotes.tsx From crust-apps with Apache License 2.0 | 5 votes |
function ReferendumVotes ({ change, className, count, isAye, isWinning, total, votes }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const sorted = useMemo(
() => votes.sort((a, b) => {
const ta = a.balance.muln(LOCKS[a.vote.conviction.toNumber()]).div(BN_TEN);
const tb = b.balance.muln(LOCKS[b.vote.conviction.toNumber()]).div(BN_TEN);
return tb.cmp(ta);
}),
[votes]
);
return (
<Expander
className={className}
help={change.gtn(0) && (
<>
<FormatBalance value={change} />
<p>{isWinning
? t<string>('The amount this total can be reduced by to change the referendum outcome. This assumes changes to the convictions of the existing votes, with no additional turnout.')
: t<string>('The amount this total should be increased by to change the referendum outcome. This assumes additional turnout with new votes at 1x conviction.')
}</p>
</>
)}
helpIcon={isWinning ? 'arrow-circle-down' : 'arrow-circle-up'}
summary={
<>
{isAye
? t<string>('Aye {{count}}', { replace: { count: count ? ` (${formatNumber(count)})` : '' } })
: t<string>('Nay {{count}}', { replace: { count: count ? ` (${formatNumber(count)})` : '' } })
}
<div><FormatBalance value={total} /></div>
</>
}
>
{sorted.map((vote) =>
<ReferendumVote
key={vote.accountId.toString()}
vote={vote}
/>
)}
</Expander>
);
}
Example #22
Source File: Propose.tsx From crust-apps with Apache License 2.0 | 4 votes |
function Propose ({ className, onClose }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const [accountId, setAccountId] = useState<string | null>(null);
const [name, setName] = useState('');
const [paraId, setParaId] = useState<BN | undefined>();
const [balance, setBalance] = useState(() => BN_THOUSAND.mul(BN_TEN.pow(new BN(api.registry.chainDecimals[0]))));
const [validators, setValidators] = useState<string[]>(['']);
const [{ isWasmValid, wasm }, setWasm] = useState<CodeState>({ isWasmValid: false, wasm: null });
const [genesisState, setGenesisState] = useState<Uint8Array | null>(null);
const _setGenesisState = useCallback(
(data: Uint8Array) => setGenesisState(compactAddLength(data)),
[]
);
const _setWasm = useCallback(
(wasm: Uint8Array, isWasmValid: boolean) => setWasm({ isWasmValid, wasm }),
[]
);
const _setAddress = useCallback(
(index: number, address: string) =>
setValidators((v) => v.map((v, i) => i === index ? address : v)),
[]
);
const _addValidator = useCallback(
() => setValidators((v) => [...v, '']),
[]
);
const _delValidator = useCallback(
() => setValidators((v) => [...v.slice(0, v.length - 1)]),
[]
);
const isNameValid = name.length >= 3;
const isValDuplicate = validators.some((a, ai) => validators.some((b, bi) => ai !== bi && a === b));
return (
<Modal
className={className}
header={t<string>('Propose parachain')}
size='large'
>
<Modal.Content>
<Modal.Columns hint={t<string>('This account will be associated with the parachain and pay the deposit.')}>
<InputAddress
label={t<string>('propose from')}
onChange={setAccountId}
type='account'
value={accountId}
/>
</Modal.Columns>
<Modal.Columns hint={t<string>('The name for this parachain, the id and the allocated/requested balance.')}>
<Input
autoFocus
isError={!isNameValid}
label={t<string>('parachain name')}
onChange={setName}
/>
<InputNumber
isZeroable={false}
label={t<string>('requested id')}
onChange={setParaId}
/>
<InputBalance
defaultValue={balance}
label={t<string>('initial balance')}
onChange={setBalance}
/>
</Modal.Columns>
<Modal.Columns hint={t<string>('The WASM validation function as well as the genesis state for this parachain.')}>
<InputWasm
help={t<string>('The compiled runtime WASM for the parachain you wish to register.')}
isError={!isWasmValid}
label={t<string>('validation code')}
onChange={_setWasm}
placeholder={wasm && !isWasmValid && t<string>('The code is not recognized as being in valid WASM format')}
/>
<InputFile
help={t<string>('The genesis state for the parachain.')}
isError={!genesisState}
label={t<string>('genesis state')}
onChange={_setGenesisState}
/>
</Modal.Columns>
<Modal.Columns hint={t<string>('The validators for this parachain. At least one is required and where multiple is supplied, they need to be unique.')}>
{validators.map((address, index) => (
<Validator
address={address}
index={index}
key={index}
setAddress={_setAddress}
t={t}
/>
))}
{!validators.length && (
<MarkWarning content={t<string>('You need to supply at last one running validator for your parachain alongside this request.')} />
)}
{isValDuplicate && (
<MarkWarning content={t<string>('You have duplicated validator entries, ensure each is unique.')} />
)}
<Button.Group>
<Button
icon='plus'
label={t<string>('Add validator')}
onClick={_addValidator}
/>
<Button
icon='minus'
isDisabled={validators.length === 0}
label={t<string>('Remove validator')}
onClick={_delValidator}
/>
</Button.Group>
</Modal.Columns>
</Modal.Content>
<Modal.Actions onCancel={onClose}>
<TxButton
accountId={accountId}
icon='plus'
isDisabled={!isWasmValid || !genesisState || !isNameValid || !validators.length || !paraId?.gt(BN_ZERO)}
onStart={onClose}
params={[paraId, name, wasm, genesisState, validators, balance]}
tx={api.tx.proposeParachain?.proposeParachain}
/>
</Modal.Actions>
</Modal>
);
}