Skip to content

Commit

Permalink
feat: Update selector computation
Browse files Browse the repository at this point in the history
  • Loading branch information
LHerskind committed Sep 5, 2023
1 parent bc8bc7d commit 6dfee50
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
43 changes: 42 additions & 1 deletion yarn-project/foundation/src/abi/decoder.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ABIType, FunctionAbi } from '@aztec/foundation/abi';
import { ABIParameter, ABIType, FunctionAbi } from '@aztec/foundation/abi';
import { Fr } from '@aztec/foundation/fields';

/**
Expand Down Expand Up @@ -86,3 +86,44 @@ class ReturnValuesDecoder {
export function decodeReturnValues(abi: FunctionAbi, returnValues: Fr[]) {
return new ReturnValuesDecoder(abi, returnValues.slice()).decode();
}

/**
* Decodes the signature of a function from the name and parameters.
*/
export class FunctionSignatureDecoder {
constructor(private name: string, private parameters: ABIParameter[]) {}

/**
* Decodes a single function parameter for the function signature.
* @param param - The parameter to decode.
* @returns A string representing the parameter type.
*/
private decodeParameter(param: ABIType): string {
switch (param.kind) {
case 'field':
return 'Field';
case 'integer':
if (param.sign === 'signed') {
throw new Error('Unsupported type: signed integer');
}
return `u${param.width}`;
case 'boolean':
return 'bool';
case 'array':
return `[${this.decodeParameter(param.type)};${param.length}]`;
case 'struct':
return `(${param.fields.map(field => `${this.decodeParameter(field.type)}`).join(',')})`;
default:
throw new Error(`Unsupported type: ${param.kind}`);
}
}

/**
* Decodes all the parameters and build the function signature
* @returns The function signature.
*/
public decode(): string {
const hmm = this.parameters.map(param => this.decodeParameter(param.type));
return `${this.name}(${hmm.join(',')})`;
}
}
4 changes: 2 additions & 2 deletions yarn-project/foundation/src/abi/function_selector.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ABIParameter } from '@aztec/foundation/abi';
import { ABIParameter, FunctionSignatureDecoder } from '@aztec/foundation/abi';
import { toBigIntBE, toBufferBE } from '@aztec/foundation/bigint-buffer';
import { keccak } from '@aztec/foundation/crypto';
import { Fr } from '@aztec/foundation/fields';
Expand Down Expand Up @@ -97,7 +97,7 @@ export class FunctionSelector {
* @returns A Buffer containing the 4-byte function selector.
*/
static fromNameAndParameters(name: string, parameters: ABIParameter[]) {
const signature = name === 'constructor' ? name : `${name}(${parameters.map(p => p.type.kind).join(',')})`;
const signature = new FunctionSignatureDecoder(name, parameters).decode();
return FunctionSelector.fromSignature(signature);
}

Expand Down

0 comments on commit 6dfee50

Please sign in to comment.