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: multi-call contract operations in tx summary #3710

Draft
wants to merge 10 commits into
base: master
Choose a base branch
from
Draft
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
5 changes: 5 additions & 0 deletions .changeset/odd-news-smile.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@fuel-ts/account": patch
---

fix: multi-call contract operations in tx summary
39 changes: 28 additions & 11 deletions packages/account/src/providers/transaction-summary/call.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type JsonAbi, decodeScriptData } from '@fuel-ts/abi-coder';
import { BigNumberCoder, type JsonAbi, StdStringCoder } from '@fuel-ts/abi-coder';
import { Interface } from '@fuel-ts/abi-coder';
import { FuelError, ErrorCode } from '@fuel-ts/errors';
import type { BN } from '@fuel-ts/math';
Expand All @@ -11,6 +11,7 @@ type GetFunctionCallProps = {
receipt: ReceiptCall;
rawPayload: string;
maxInputs: BN;
callScriptOffset: number;
};

export interface FunctionCall {
Expand All @@ -25,6 +26,7 @@ export const getFunctionCall = ({
abi,
receipt,
rawPayload,
callScriptOffset,
}: GetFunctionCallProps): FunctionCall => {
const [transaction] = new TransactionCoder().decode(arrayify(rawPayload), 0);

Expand All @@ -35,21 +37,36 @@ export const getFunctionCall = ({
);
}

const { functionArgs, functionSelector } = decodeScriptData(
arrayify(transaction.scriptData),
abi
const scriptData = arrayify(transaction.scriptData);

// Decode the function selector offset
const fnSelectorOffsetBytes = receipt.param1.toBytes(8);
const [fnSelectorOffset] = new BigNumberCoder('u64').decode(fnSelectorOffsetBytes, 0);

// Decode the function selector
const [fnSelector] = new StdStringCoder().decode(
scriptData,
fnSelectorOffset.toNumber() - callScriptOffset
);

// Decode the function arguments offset
const fnArgumentOffsetBytes = receipt.param2.toBytes(8);
const [fnArgumentOffset] = new BigNumberCoder('u64').decode(fnArgumentOffsetBytes, 0);

// Decode the function arguments
const abiInterface = new Interface(abi);
const functionFragment = abiInterface.getFunction(functionSelector);
const inputs = functionFragment.jsonFn.inputs;
const fnArgumentsSlice = scriptData.slice(fnArgumentOffset.toNumber() - callScriptOffset);
const fnFragment = abiInterface.getFunction(fnSelector);
const fnArgs = fnFragment.decodeArguments(fnArgumentsSlice);

let argumentsProvided: Record<string, unknown> | undefined;

let argumentsProvided;
if (fnArgs) {
const inputs = fnFragment.jsonFn.inputs;

if (functionArgs) {
// put together decoded data with input names from abi
argumentsProvided = inputs.reduce((prev, input, index) => {
const value = functionArgs[index];
const value = fnArgs[index];
const name = input.name;

if (name) {
Expand All @@ -65,8 +82,8 @@ export const getFunctionCall = ({
}

return {
functionSignature: functionFragment.signature,
functionName: functionFragment.name,
functionSignature: fnFragment.signature,
functionName: fnFragment.name,
argumentsProvided,
...(receipt.amount?.isZero() ? {} : { amount: receipt.amount, assetId: receipt.assetId }),
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { getRandomB256 } from '@fuel-ts/address';
import { ZeroBytes32 } from '@fuel-ts/address/configs';
import { bn } from '@fuel-ts/math';
import type { ReceiptCall } from '@fuel-ts/transactions';
import { ReceiptType, TransactionType } from '@fuel-ts/transactions';
import { ASSET_A, ASSET_B } from '@fuel-ts/utils/test-utils';
import * as asm from '@fuels/vm-asm';

import {
CONTRACT_CALL_ABI,
Expand Down Expand Up @@ -46,6 +48,7 @@ import {
isTypeCreate,
isTypeMint,
isTypeScript,
calculateScriptVariableSize,
} from './operations';
import type { Operation } from './types';
import { AddressType, OperationName, TransactionTypeName, ChainName } from './types';
Expand Down Expand Up @@ -1045,4 +1048,64 @@ describe('operations', () => {
'Unsupported transaction type: '
);
});

/**
* This test is to validate the implementation of calculateScriptVariableSize against the actual ASM.
* This is because the implementation I opted for uses hardcoded bytes to calculate the size, so that
* we do not have to init asm and make the tx summary assembly async. These values should only change
* if the VM updates their asm implementation of the opcodes. Should this test fail,
* we must update the hardcoded bytes in `calculateScriptVariableSize` to match the ASM.
*/
it('checks calculateScriptVariableSize against actual ASM', async () => {
// @ts-expect-error fn does exist
await asm.initWasm();

const calls: ReceiptCall[] = [
{
type: ReceiptType.Call,
id: '0x1',
to: '0x1',
amount: bn(0),
assetId: '0x1',
gas: bn(0),
param1: bn(0),
param2: bn(0),
pc: bn(0),
is: bn(0),
},
];

// Call Data Offset
const callDataOffset = asm.movi(0x10, 0).to_bytes();
// Amount Offset
const amountOffset = asm.movi(0x11, 0).to_bytes();
// Load Asset ID
const assetIdOffset = asm.lw(0x11, 0x11, 0).to_bytes();
// Asset ID
const loadBytes = asm.movi(0x12, 0).to_bytes();
// Gas Offset
const gasOffset = asm.call(0x10, 0x11, 0x12, asm.RegId.cgas().to_u8()).to_bytes();
// RET instruction size
const retSize = asm.Instruction.size();

const calculateScriptVariableSizeAsm = (recs: ReceiptCall[]) =>
recs.reduce(
(acc) =>
acc +
callDataOffset.byteLength +
amountOffset.byteLength +
assetIdOffset.byteLength +
loadBytes.byteLength +
gasOffset.byteLength,
retSize
);

const scriptVariableSize = calculateScriptVariableSize(calls);
expect(scriptVariableSize).toEqual(24);

const scriptVariableSizeAsm = calculateScriptVariableSizeAsm(calls);
expect(scriptVariableSizeAsm).toEqual(24);

expect(scriptVariableSize).toEqual(scriptVariableSizeAsm);
});
});
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import { calculateVmTxMemory, SCRIPT_FIXED_SIZE, WORD_SIZE } from '@fuel-ts/abi-coder';
import { ZeroBytes32 } from '@fuel-ts/address/configs';
import { ErrorCode, FuelError } from '@fuel-ts/errors';
import type { BN } from '@fuel-ts/math';
import { bn } from '@fuel-ts/math';
import { ReceiptType, TransactionType } from '@fuel-ts/transactions';
import type { InputContract, Output, OutputChange, Input } from '@fuel-ts/transactions';
import type {
InputContract,
Output,
OutputChange,
Input,
ReceiptCall,
} from '@fuel-ts/transactions';

import type {
TransactionResultReceipt,
Expand Down Expand Up @@ -276,7 +283,8 @@ function getContractCalls(
abiMap: AbiMap | undefined,
receipt: TransactionResultCallReceipt,
rawPayload: string,
maxInputs: BN
maxInputs: BN,
callScriptOffset: number
): FunctionCall[] {
const abi = abiMap?.[contractInput.contractID];
if (!abi) {
Expand All @@ -289,6 +297,7 @@ function getContractCalls(
receipt,
rawPayload,
maxInputs,
callScriptOffset,
}),
];
}
Expand All @@ -313,7 +322,8 @@ function processCallReceipt(
abiMap: AbiMap | undefined,
rawPayload: string,
maxInputs: BN,
baseAssetId: string
baseAssetId: string,
callScriptOffset: number
): Operation[] {
const assetId = receipt.assetId === ZeroBytes32 ? baseAssetId : receipt.assetId;
const input = getInputFromAssetId(inputs, assetId, assetId === baseAssetId);
Expand All @@ -322,7 +332,14 @@ function processCallReceipt(
}

const inputAddress = getInputAccountAddress(input);
const calls = getContractCalls(contractInput, abiMap, receipt, rawPayload, maxInputs);
const calls = getContractCalls(
contractInput,
abiMap,
receipt,
rawPayload,
maxInputs,
callScriptOffset
);

return [
{
Expand All @@ -342,6 +359,49 @@ function processCallReceipt(
];
}

/**
* Calculates the size of the contract call script based off.
*
* This is a hardcoded implementation of the contract call script size calculation, validated
* by an ASM implemenation of the same logic in `operations.test.ts`.
*
* @param calls - The contract call receipts to calculate the size of.
* @returns The size of the contract call script.
*/
export const calculateScriptVariableSize = (calls: ReceiptCall[]): number => {
// Calculate the length of the call script for each call and sum
const offset = calls.reduce(
(total) => {
let callOffset = total;
// Call Data Offset - asm.movi(0x10, 0)
const callDataOffset = new Uint8Array([114, 64, 0, 0]);
callOffset += callDataOffset.byteLength;
// Amount Offset - asm.movi(0x11, 0)
const amountOffset = new Uint8Array([114, 68, 0, 0]);
callOffset += amountOffset.byteLength;
// Load Asset ID- asm.lw(0x11, 0x11, 0)
const assetIdOffset = new Uint8Array([93, 69, 16, 0]);
callOffset += assetIdOffset.byteLength;
// Asset ID - asm.movi(0x12, 0)
const loadBytes = new Uint8Array([114, 72, 0, 0]);
callOffset += loadBytes.byteLength;
// Gas Offset - asm.call(0x10, 0x11, 0x12, asm.RegId.cgas().to_u8())
const gasOffset = new Uint8Array([45, 65, 20, 138]);
callOffset += gasOffset.byteLength;

return callOffset;
},
// RET instruction size
4
);

// Add padding
const paddingLength = (WORD_SIZE - (offset % WORD_SIZE)) % WORD_SIZE;
const paddedInstructionsLength = offset + paddingLength;

return paddedInstructionsLength;
};

/** @hidden */
export function getContractCallOperations({
inputs,
Expand All @@ -364,19 +424,36 @@ export function getContractCallOperations({
return [];
}

return contractCallReceipts
.filter((receipt) => receipt.to === contractInput.contractID)
.flatMap((receipt) =>
const callReceiptsForContract = contractCallReceipts.filter(
(receipt) => receipt.to === contractInput.contractID
);

// Potential weakness here for legacy transactions, if the script data was generated
// with a different max inputs value, the offset will be incorrect and therefore decoding
// will fail. In this scenario we won't return the operations.
try {
const callScriptBaseOffset =
SCRIPT_FIXED_SIZE +
calculateScriptVariableSize(callReceiptsForContract) +
calculateVmTxMemory({ maxInputs: maxInputs.toNumber() });
Copy link
Member

@arboleya arboleya Feb 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, judging by the answers to your questions, we can't rely on max inputs, can't we?

Copy link
Member Author

@danielbate danielbate Feb 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No we can't. But I think there is value as for a tx summary created from a tx response, where it is likely that the max inputs is the same, we will get a more complete summary. It is also failing gracefully (empty array for operations) should the offset be incorrect.

For legacy transactions where it is possible that submitted max inputs != current max inputs, I've got an idea whereby we could query the block header that the tx was included in, and get the consensus param version and check that against the one we want to use for the calculation. This would need another request though. Or we ask them to include that in the transaction status that we have already, that gives us the block ID.

Additionally, there is the tracer but that will also require an additional request.

Going to dump these thoughts on a follow-up issue.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we postpone this feature until it is 100% reliable (via the tracer or similar)?

IIRC, one of the use cases for this was to show stuff on the Explorer, correct?

Which, given the circumstances, will not happen anyway.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Max inputs has not changed since we launched main-net. Right now, if we merged this feature, the explorer could display all contract operations for all transactions without making any additional requests.

Right now, we don't have any call operations in the tx summary. If max inputs changes, this feature mirrors that outcome for legacy txs. So IMO there is little downside vs where we are right now.

I'll leave it at that, I think there's value, but I'll leave it to you and the team if there isn't agreement and I'll convert to draft 👍🏻

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My point is that there's no guarantee it won't change, right? This is the same caveat from @Torres-ssf's presentation on why we can't hardcode the maxInputs value and save one extra request. The same rationale was applied to the RPC Consistency pull request, accounting for variations and "what if it changes" cases.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no guarantee.

I'll get an issue written up to investigate/introduce tracing as that'll likely be the most robust, and will close this PR with that issue.


const operations = callReceiptsForContract.flatMap((receipt) =>
processCallReceipt(
receipt,
contractInput,
inputs,
abiMap,
rawPayload as string,
maxInputs,
baseAssetId
baseAssetId,
callScriptBaseOffset
)
);

return operations;
} catch (error) {
return [];
}
});
}

Expand Down
Loading
Loading