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

Fix fee calculation #30

Merged
merged 7 commits into from
May 9, 2023
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
2 changes: 2 additions & 0 deletions src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,5 @@ export const GERALD_CONTRACT_ADDRESSES = [
// Token is KSM, DOT, UNIT (depending what relaychain is connected)
export const RELAY_ASSET_ID = "42259045809535163221576417993425387648";
export const USDT_ASSET_ID = "311091173110107856861649819128533077277";

export const EXTRINSIC_BASE_WEIGHT = 250_000_000;
23 changes: 6 additions & 17 deletions src/utils/monitoring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,10 +206,10 @@ export const getAccountFromNimbusKey = async (
!authorMappingCache[nmbsKey] ||
authorMappingCache[nmbsKey].lastUpdate < Date.now() - 3600 * 1000
) {
const mappingData = (await api.query.authorMapping.mappingWithDeposit(nmbsKey)) as Option<any>;
const mappingData = (await api.query.authorMapping.mapping(nmbsKey)) as Option<any>;
crystalin marked this conversation as resolved.
Show resolved Hide resolved
authorMappingCache[nmbsKey] = {
lastUpdate: Date.now(),
account: mappingData.isEmpty ? null : ethereumEncode(mappingData.unwrap().account.toString()),
account: mappingData.isEmpty ? null : ethereumEncode(mappingData.unwrap().toString()),
};
}
const { account } = authorMappingCache[nmbsKey];
Expand Down Expand Up @@ -284,27 +284,16 @@ export const getBlockDetails = async (api: ApiPromise, blockHash: BlockHash) =>
]);

const feeMultiplier = await getFeeMultiplier(api, block.header.parentHash.toString());
const txWithEvents = mapExtrinsics(
const txWithEvents = await mapExtrinsics(
api,
block.extrinsics,
records,
fees.map((fee) => fee.inclusionFee.unwrapOrDefault()),
feeMultiplier,
apiAt.consts.transactionPayment?.weightToFee ||
([
{
coeffInteger: new u128(
api.registry,
api.runtimeVersion.specName.toString() == "moonbeam" ? 1_000_000 : 10_000
).muln(apiAt.consts.transactionPayment.operationalFeeMultiplier.toNumber() || 5),
coeffFrac: api.registry.createType("Perbill", 0),
negative: new bool(api.registry, false),
degree: new u8(api.registry, 1),
},
] as any)
feeMultiplier
);
const blockWeight = txWithEvents.reduce((totalWeight, tx, index) => {
// TODO: support weight v1/2
return totalWeight + (tx.dispatchInfo && (tx.dispatchInfo.weight as any).refTime.toBigInt());
return totalWeight + (tx.dispatchInfo && (tx.dispatchInfo.weight as any).toBigInt());
}, 0n);
return {
block,
Expand Down
88 changes: 52 additions & 36 deletions src/utils/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import type { u128 } from "@polkadot/types";
import { BN } from "@polkadot/util";

import type { TxWithEvent } from "@polkadot/api-derive/types";
import { ApiPromise } from "@polkadot/api";
import { toPairsIn } from "lodash";
import { EXTRINSIC_BASE_WEIGHT } from "./constants";

export interface ComputedFees {
baseFee: bigint;
Expand All @@ -20,50 +23,63 @@ export interface TxWithEventAndFee extends TxWithEvent {
fees: ComputedFees;
}

export function mapExtrinsics(
export const mapExtrinsics = async (
api: ApiPromise,
extrinsics: Extrinsic[],
records: EventRecord[],
fees: InclusionFee[],
feeMultiplier: u128,
weightToFees: any[]
): TxWithEventAndFee[] {
return extrinsics.map((extrinsic, index): TxWithEventAndFee => {
let dispatchError: DispatchError | undefined;
let dispatchInfo: DispatchInfo | undefined;
feeMultiplier: u128
) => {
return Promise.all(
extrinsics.map(async (extrinsic, index) => {
let dispatchError: DispatchError | undefined;
let dispatchInfo: DispatchInfo | undefined;

const events = records
.filter(({ phase }) => phase.isApplyExtrinsic && phase.asApplyExtrinsic.eq(index))
.map(({ event }) => {
if (event.section === "system") {
if (event.method === "ExtrinsicSuccess") {
dispatchInfo = event.data[0] as DispatchInfo;
} else if (event.method === "ExtrinsicFailed") {
dispatchError = event.data[0] as DispatchError;
dispatchInfo = event.data[1] as DispatchInfo;
const events = records
.filter(({ phase }) => phase.isApplyExtrinsic && phase.asApplyExtrinsic.eq(index))
.map(({ event }) => {
if (event.section === "system") {
if (event.method === "ExtrinsicSuccess") {
dispatchInfo = event.data[0] as DispatchInfo;
} else if (event.method === "ExtrinsicFailed") {
dispatchError = event.data[0] as DispatchError;
dispatchInfo = event.data[1] as DispatchInfo;
}
}
}

return event;
});
return event;
});

let computedFees: ComputedFees;
const feeDetails = fees[index];
const unadjustedWeightFee = (
(await api.call.transactionPaymentApi.queryWeightToFee(dispatchInfo.weight)) as any
).toBigInt();
const lengthFee = (
(await api.call.transactionPaymentApi.queryLengthToFee(extrinsic.encodedLength)) as any
).toBigInt();

const frac = weightToFees[0].coeffFrac.mul((dispatchInfo.weight as any).refTime?.toBn());
const integer = weightToFees[0].coeffInteger.mul((dispatchInfo.weight as any).refTime?.toBn());
// TODO: should be doing this at api.at() the original block
const feeMultiplier = await api.query.transactionPayment.nextFeeMultiplier();
const weightFee =
(unadjustedWeightFee * feeMultiplier.toBigInt()) / 1_000_000_000_000_000_000n;

const unadjustedFee = frac.add(integer);
const baseFee = (
(await api.call.transactionPaymentApi.queryWeightToFee({
refTime: EXTRINSIC_BASE_WEIGHT,
proofSize: 0n,
})) as any
).toBigInt();

const adjustedFee = BigInt(
unadjustedFee.mul(feeMultiplier.toBn()).div(new BN("1000000000000000000")).toString()
);
const tip = extrinsic.tip.toBigInt();

computedFees = {
baseFee: feeDetails.baseFee.toBigInt(),
lenFee: feeDetails.lenFee.toBigInt(),
weightFee: adjustedFee,
totalFees: adjustedFee + feeDetails.baseFee.toBigInt() + feeDetails.lenFee.toBigInt(),
};
return { dispatchError, dispatchInfo, events, extrinsic, fees: computedFees };
});
}
const totalFees = lengthFee + weightFee + baseFee + tip;

const computedFees: ComputedFees = {
baseFee,
lenFee: lengthFee,
weightFee,
totalFees,
};
return { dispatchError, dispatchInfo, events, extrinsic, fees: computedFees };
})
);
};