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

Support testing contract private functions in integration tests #420

Merged
merged 4 commits into from
Sep 10, 2024
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
18 changes: 18 additions & 0 deletions artifacts/ts/Add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ export namespace AddTypes {
}>;
result: CallContractResult<[bigint, bigint]>;
};
addPrivate: {
params: CallContractParams<{ array: [bigint, bigint] }>;
result: CallContractResult<[bigint, bigint]>;
};
createSubContract: {
params: CallContractParams<{
a: bigint;
Expand Down Expand Up @@ -122,6 +126,10 @@ export namespace AddTypes {
}>;
result: SignExecuteScriptTxResult;
};
addPrivate: {
params: SignExecuteContractMethodParams<{ array: [bigint, bigint] }>;
result: SignExecuteScriptTxResult;
};
createSubContract: {
params: SignExecuteContractMethodParams<{
a: bigint;
Expand Down Expand Up @@ -316,6 +324,11 @@ export class AddInstance extends ContractInstance {
): Promise<AddTypes.CallMethodResult<"add2">> => {
return callMethod(Add, this, "add2", params, getContractByCodeHash);
},
addPrivate: async (
params: AddTypes.CallMethodParams<"addPrivate">
): Promise<AddTypes.CallMethodResult<"addPrivate">> => {
return callMethod(Add, this, "addPrivate", params, getContractByCodeHash);
},
createSubContract: async (
params: AddTypes.CallMethodParams<"createSubContract">
): Promise<AddTypes.CallMethodResult<"createSubContract">> => {
Expand Down Expand Up @@ -356,6 +369,11 @@ export class AddInstance extends ContractInstance {
): Promise<AddTypes.SignExecuteMethodResult<"add2">> => {
return signExecuteMethod(Add, this, "add2", params);
},
addPrivate: async (
params: AddTypes.SignExecuteMethodParams<"addPrivate">
): Promise<AddTypes.SignExecuteMethodResult<"addPrivate">> => {
return signExecuteMethod(Add, this, "addPrivate", params);
},
createSubContract: async (
params: AddTypes.SignExecuteMethodParams<"createSubContract">
): Promise<AddTypes.SignExecuteMethodResult<"createSubContract">> => {
Expand Down
48 changes: 48 additions & 0 deletions artifacts/ts/MetaData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ export namespace MetaDataTypes {
params: Omit<CallContractParams<{}>, "args">;
result: CallContractResult<null>;
};
bar: {
params: Omit<CallContractParams<{}>, "args">;
result: CallContractResult<null>;
};
baz: {
params: Omit<CallContractParams<{}>, "args">;
result: CallContractResult<null>;
};
}
export type CallMethodParams<T extends keyof CallMethodTable> =
CallMethodTable[T]["params"];
Expand All @@ -73,6 +81,14 @@ export namespace MetaDataTypes {
params: Omit<SignExecuteContractMethodParams<{}>, "args">;
result: SignExecuteScriptTxResult;
};
bar: {
params: Omit<SignExecuteContractMethodParams<{}>, "args">;
result: SignExecuteScriptTxResult;
};
baz: {
params: Omit<SignExecuteContractMethodParams<{}>, "args">;
result: SignExecuteScriptTxResult;
};
}
export type SignExecuteMethodParams<T extends keyof SignExecuteMethodTable> =
SignExecuteMethodTable[T]["params"];
Expand Down Expand Up @@ -164,6 +180,28 @@ export class MetaDataInstance extends ContractInstance {
getContractByCodeHash
);
},
bar: async (
params?: MetaDataTypes.CallMethodParams<"bar">
): Promise<MetaDataTypes.CallMethodResult<"bar">> => {
return callMethod(
MetaData,
this,
"bar",
params === undefined ? {} : params,
getContractByCodeHash
);
},
baz: async (
params?: MetaDataTypes.CallMethodParams<"baz">
): Promise<MetaDataTypes.CallMethodResult<"baz">> => {
return callMethod(
MetaData,
this,
"baz",
params === undefined ? {} : params,
getContractByCodeHash
);
},
};

transact = {
Expand All @@ -172,5 +210,15 @@ export class MetaDataInstance extends ContractInstance {
): Promise<MetaDataTypes.SignExecuteMethodResult<"foo">> => {
return signExecuteMethod(MetaData, this, "foo", params);
},
bar: async (
params: MetaDataTypes.SignExecuteMethodParams<"bar">
): Promise<MetaDataTypes.SignExecuteMethodResult<"bar">> => {
return signExecuteMethod(MetaData, this, "bar", params);
},
baz: async (
params: MetaDataTypes.SignExecuteMethodParams<"baz">
): Promise<MetaDataTypes.SignExecuteMethodResult<"baz">> => {
return signExecuteMethod(MetaData, this, "baz", params);
},
};
}
5 changes: 1 addition & 4 deletions artifacts/ts/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,7 @@ export function getContractByCodeHash(codeHash: string): Contract {
WrongNFTTest,
];
}
const c = contracts.find(
(c) =>
c.contract.codeHash === codeHash || c.contract.codeHashDebug === codeHash
);
const c = contracts.find((c) => c.contract.hasCodeHash(codeHash));
if (c === undefined) {
throw new Error("Unknown code with code hash: " + codeHash);
}
Expand Down
13 changes: 6 additions & 7 deletions packages/cli/src/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ function genCallMethod(contractName: string, functionSig: FunctionSig): string {
}

function genCallMethods(contract: Contract): string {
const functions = contract.publicFunctions()
const functions = contract.functions
if (functions.length === 0) {
return ''
}
Expand All @@ -123,7 +123,7 @@ function genCallMethods(contract: Contract): string {
}

function genTxCallMethods(contract: Contract): string {
const functions = contract.publicFunctions()
const functions = contract.functions
if (functions.length === 0) {
return ''
}
Expand Down Expand Up @@ -379,7 +379,7 @@ function genTestMethods(contract: Contract): string {
}

function genCallMethodTypes(contract: Contract): string {
const entities = contract.publicFunctions().map((functionSig) => {
const entities = contract.functions.map((functionSig) => {
const funcHasArgs = functionSig.paramNames.length > 0
const params = funcHasArgs
? `CallContractParams<{${formatParameters({
Expand Down Expand Up @@ -416,7 +416,7 @@ function genCallMethodTypes(contract: Contract): string {
}

function genSignExecuteMethodTypes(contract: Contract): string {
const entities = contract.publicFunctions().map((functionSig) => {
const entities = contract.functions.map((functionSig) => {
const funcHasArgs = functionSig.paramNames.length > 0
const params = funcHasArgs
? `SignExecuteContractMethodParams<{${formatParameters({
Expand Down Expand Up @@ -445,8 +445,7 @@ function genSignExecuteMethodTypes(contract: Contract): string {

function genMulticall(contract: Contract): string {
const types = contractTypes(contract.name)
const supportMulticall =
contract.publicFunctions().filter((functionSig) => functionSig.returnTypes.length > 0).length > 0
const supportMulticall = contract.functions.filter((functionSig) => functionSig.returnTypes.length > 0).length > 0
return supportMulticall
? `
async multicall<Callss extends ${types}.MultiCallParams[]>(
Expand Down Expand Up @@ -624,7 +623,7 @@ function genContractByCodeHash(outDir: string, contractNames: string[]) {
if (contracts === undefined) {
contracts = [${contracts}]
}
const c = contracts.find((c) => c.contract.codeHash === codeHash || c.contract.codeHashDebug === codeHash)
const c = contracts.find((c) => c.contract.hasCodeHash(codeHash))
if (c === undefined) {
throw new Error("Unknown code with code hash: " + codeHash)
}
Expand Down
2 changes: 1 addition & 1 deletion packages/web3/src/codec/contract-codec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ describe('Encode & decode contract', function () {

expect(decodedContract.fieldLength).toEqual(getTypesLength(contract.fieldsSig.types))
decodedContract.methods.map((decodedMethod, index) => {
const decoded = contract.decodedMethods[index]
const decoded = contract.getDecodedMethod(index)
const functionSig = contract.functions[index]
expect(decodedMethod.isPublic).toEqual(decoded.isPublic)
expect(decodedMethod.usePreapprovedAssets).toEqual(decoded.usePreapprovedAssets)
Expand Down
76 changes: 60 additions & 16 deletions packages/web3/src/contract/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ export abstract class Artifact {
this.functions = functions
}

abstract buildByteCodeToDeploy(initialFields: Fields, isDevnet: boolean): string
abstract buildByteCodeToDeploy(initialFields: Fields, isDevnet: boolean, exposePrivateFunctions: boolean): string

async isDevnet(signer: SignerProvider): Promise<boolean> {
if (!signer.nodeProvider) {
Expand Down Expand Up @@ -197,7 +197,10 @@ export class Contract extends Artifact {

readonly bytecodeDebug: string
readonly codeHashDebug: string
readonly decodedMethods: Method[]
readonly decodedContract: contract.Contract

private bytecodeForTesting: string | undefined
private codeHashForTesting: string | undefined

constructor(
version: string,
Expand Down Expand Up @@ -230,19 +233,54 @@ export class Contract extends Artifact {
this.bytecodeDebug = ralph.buildDebugBytecode(this.bytecode, this.bytecodeDebugPatch)
this.codeHashDebug = codeHashDebug

this.decodedMethods = contract.contractCodec.decodeContract(hexToBinUnsafe(bytecode)).methods
this.decodedContract = contract.contractCodec.decodeContract(hexToBinUnsafe(this.bytecode))
this.bytecodeForTesting = undefined
this.codeHashForTesting = undefined
}

getByteCodeForTesting(): string {
if (this.bytecodeForTesting !== undefined) return this.bytecodeForTesting

if (this.publicFunctions().length == this.functions.length) {
this.bytecodeForTesting = this.bytecodeDebug
this.codeHashForTesting = this.codeHashDebug
return this.bytecodeForTesting
}

const decodedDebugContract = contract.contractCodec.decodeContract(hexToBinUnsafe(this.bytecodeDebug))
const methods = decodedDebugContract.methods.map((method) => ({ ...method, isPublic: true }))
const bytecodeForTesting = contract.contractCodec.encodeContract({
fieldLength: decodedDebugContract.fieldLength,
methods: methods
})
const codeHashForTesting = blake.blake2b(bytecodeForTesting, undefined, 32)
this.bytecodeForTesting = binToHex(bytecodeForTesting)
this.codeHashForTesting = binToHex(codeHashForTesting)
return this.bytecodeForTesting
}

hasCodeHash(hash: string): boolean {
return this.codeHash === hash || this.codeHashDebug === hash || this.codeHashForTesting === hash
}

getDecodedMethod(methodIndex: number): Method {
return this.decodedContract.methods[`${methodIndex}`]
}

publicFunctions(): FunctionSig[] {
return this.functions.filter((_, index) => this.decodedMethods[`${index}`].isPublic)
return this.functions.filter((_, index) => this.getDecodedMethod(index).isPublic)
}

usingPreapprovedAssetsFunctions(): FunctionSig[] {
return this.functions.filter((_, index) => this.decodedMethods[`${index}`].usePreapprovedAssets)
return this.functions.filter((_, index) => this.getDecodedMethod(index).usePreapprovedAssets)
}

usingAssetsInContractFunctions(): FunctionSig[] {
return this.functions.filter((_, index) => this.decodedMethods[`${index}`].useContractAssets)
return this.functions.filter((_, index) => this.getDecodedMethod(index).useContractAssets)
}

isMethodUsePreapprovedAssets(methodIndex: number): boolean {
return this.getDecodedMethod(methodIndex).usePreapprovedAssets
}

// TODO: safely parse json
Expand Down Expand Up @@ -530,7 +568,11 @@ export class Contract extends Artifact {
): Promise<SignDeployContractTxParams> {
const isDevnet = await this.isDevnet(signer)
const initialFields: Fields = params.initialFields ?? {}
const bytecode = this.buildByteCodeToDeploy(addStdIdToFields(this, initialFields), isDevnet)
const bytecode = this.buildByteCodeToDeploy(
addStdIdToFields(this, initialFields),
isDevnet,
params.exposePrivateFunctions ?? false
)
const selectedAccount = await signer.getSelectedAccount()
const signerParams: SignDeployContractTxParams = {
signerAddress: selectedAccount.address,
Expand All @@ -546,14 +588,15 @@ export class Contract extends Artifact {
return signerParams
}

buildByteCodeToDeploy(initialFields: Fields, isDevnet: boolean): string {
buildByteCodeToDeploy(initialFields: Fields, isDevnet: boolean, exposePrivateFunctions = false): string {
try {
return ralph.buildContractByteCode(
isDevnet ? this.bytecodeDebug : this.bytecode,
initialFields,
this.fieldsSig,
this.structs
)
const bytecode =
exposePrivateFunctions && isDevnet
? this.getByteCodeForTesting()
: isDevnet
? this.bytecodeDebug
: this.bytecode
return ralph.buildContractByteCode(bytecode, initialFields, this.fieldsSig, this.structs)
} catch (error) {
throw new Error(`Failed to build bytecode for contract ${this.name}, error: ${error}`)
}
Expand Down Expand Up @@ -975,10 +1018,11 @@ export interface DeployContractParams<P extends Fields = Fields> {
issueTokenTo?: string
gasAmount?: number
gasPrice?: Number256
exposePrivateFunctions?: boolean
}
assertType<
Eq<
Omit<DeployContractParams<undefined>, 'initialFields'>,
Omit<DeployContractParams<undefined>, 'initialFields' | 'exposePrivateFunctions'>,
Omit<SignDeployContractTxParams, 'signerAddress' | 'signerKeyType' | 'bytecode'>
>
>
Expand Down Expand Up @@ -1687,7 +1731,7 @@ export async function signExecuteMethod<I extends ContractInstance, F extends Fi
): Promise<SignExecuteScriptTxResult> {
const methodIndex = contract.contract.getMethodIndex(methodName)
const functionSig = contract.contract.functions[methodIndex]
const methodUsePreapprovedAssets = contract.contract.decodedMethods[methodIndex].usePreapprovedAssets
const methodUsePreapprovedAssets = contract.contract.isMethodUsePreapprovedAssets(methodIndex)
const bytecodeTemplate = getBytecodeTemplate(
methodIndex,
methodUsePreapprovedAssets,
Expand Down
Loading
Loading