diff --git a/packages/web3/src/contract/contract.ts b/packages/web3/src/contract/contract.ts index f429a2cd0..8421e9e96 100644 --- a/packages/web3/src/contract/contract.ts +++ b/packages/web3/src/contract/contract.ts @@ -54,7 +54,9 @@ import { WebCrypto, hexToBinUnsafe, isDevnet, - HexString + HexString, + isHexString, + hexToString } from '../utils' import { contractIdFromAddress, groupOfAddress, addressFromContractId, subContractId } from '../address' import { getCurrentNodeProvider } from '../global' @@ -405,7 +407,7 @@ export class Contract extends Artifact { printDebugMessages(funcName: string, messages: DebugMessage[]) { if (isContractDebugMessageEnabled() && messages.length != 0) { console.log(`Testing ${this.name}.${funcName}:`) - messages.forEach((m) => console.log(`> Contract @ ${m.contractAddress} - ${m.message}`)) + messages.forEach((m) => printDebugMessage(m)) } } @@ -503,6 +505,7 @@ export class Contract extends Artifact { fieldNames: ['address'], fieldTypes: ['Address'] } + static DebugEventIndex = -3 static fromApiEvent( event: node.ContractEventByTxId, @@ -1494,6 +1497,38 @@ export async function testMethod< } as TestContractResult } +function printDebugMessage(m: node.DebugMessage) { + console.log(`> Contract @ ${m.contractAddress} - ${m.message}`) +} + +export async function getDebugMessagesFromTx(txId: HexString, provider?: NodeProvider) { + if (isHexString(txId) && txId.length === 64) { + const nodeProvider = provider ?? getCurrentNodeProvider() + const events = await nodeProvider.events.getEventsTxIdTxid(txId) + return events.events + .filter((e) => e.eventIndex === Contract.DebugEventIndex) + .map((e) => { + if (e.fields.length === 1 && e.fields[0].type === 'ByteVec') { + return { + contractAddress: e.contractAddress, + message: hexToString(e.fields[0].value as string) + } + } else { + throw new Error(`Invalid debug log: ${JSON.stringify(e.fields)}`) + } + }) + } else { + throw new Error(`Invalid tx id: ${txId}`) + } +} + +export async function printDebugMessagesFromTx(txId: HexString, provider?: NodeProvider) { + const messages = await getDebugMessagesFromTx(txId, provider) + if (messages.length > 0) { + messages.forEach((m) => printDebugMessage(m)) + } +} + export class RalphMap { private readonly groupIndex: number constructor( @@ -1841,7 +1876,11 @@ export async function signExecuteMethod { + const deployResult = await Debug.deploy(signer, { initialFields: {} }) + const txResult = await deployResult.contractInstance.transact.debug({ signer }) + const messages = await getDebugMessagesFromTx(txResult.txId) + expect(messages).toEqual([ + { contractAddress: deployResult.contractInstance.address, message: `Hello, ${ZERO_ADDRESS}!` } + ]) + }) + it('should test assert!', async () => { expect(Numbers.C).toEqual((1n << 256n) - 1n)