Skip to content

Commit

Permalink
Fix unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
limemloh committed Sep 27, 2023
1 parent 8545066 commit 90b3ff7
Show file tree
Hide file tree
Showing 39 changed files with 1,405 additions and 764 deletions.
9 changes: 3 additions & 6 deletions packages/common/src/GenericContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,15 +131,12 @@ export class ContractDryRun<E extends string = string> {
blockHash?: BlockHash.Type
): Promise<InvokeContractResult> {
const parameter = Parameter.fromBuffer(serializer(input));

const method = ReceiveName.create(this.contractName, entrypoint);

return this.grpcClient.invokeContract(
{
contract: this.contractAddress,
parameter,
invoker,
method: ReceiveName.toString(method),
method: ReceiveName.create(this.contractName, entrypoint),
},
blockHash
);
Expand Down Expand Up @@ -471,7 +468,7 @@ class ContractBase<E extends string = string, V extends string = string> {
* @returns {R} The transaction hash of the update transaction
*/
public async invokeView<T, R>(
entrypoint: V,
entrypoint: EntrypointName.Type<V>,
serializeInput: (input: T) => ArrayBuffer,
deserializeResponse: (value: HexString) => R,
input: T,
Expand All @@ -483,7 +480,7 @@ class ContractBase<E extends string = string, V extends string = string> {
{
contract: this.contractAddress,
parameter,
method: `${this.contractName}.${entrypoint}`,
method: ReceiveName.create(this.contractName, entrypoint),
},
blockHash
);
Expand Down
15 changes: 9 additions & 6 deletions packages/common/src/cis0.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import * as Parameter from './types/Parameter.js';
import * as ContractName from './types/ContractName.js';
import * as ReceiveName from './types/ReceiveName.js';
import * as ReturnValue from './types/ReturnValue.js';
import { EntrypointName } from './index.js';

/**
* Namespace with types for CIS-0 standard contracts
Expand Down Expand Up @@ -142,14 +143,16 @@ export async function cis0Supports(
);
});

const contractName = ContractName.toString(
ContractName.fromInitName(instanceInfo.name)
const contractName = ContractName.fromInitName(instanceInfo.name);
const supportReceiveName = ReceiveName.create(
contractName,
EntrypointName.fromStringUnchecked('supports')
);

if (
!instanceInfo.methods
.map(ReceiveName.toString)
.includes(`${contractName}.supports`)
!instanceInfo.methods.some((methods) =>
ReceiveName.equals(methods, supportReceiveName)
)
) {
return undefined;
}
Expand All @@ -162,7 +165,7 @@ export async function cis0Supports(
{
contract: contractAddress,
parameter,
method: `${contractName}.supports`,
method: supportReceiveName,
},
blockHash
);
Expand Down
8 changes: 4 additions & 4 deletions packages/common/src/cis2/CIS2Contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class CIS2DryRun extends ContractDryRun<Updates> {
*
* @param {CIS2.Address} sender - Address of the sender of the transfer.
* @param {CIS2.Transfer | CIS2.Transfer[]} transfer(s) - The transfer object(s).
* @param {HexString} [blockHash] - The hash of the block to perform the invocation of. Defaults to the latest finalized block on chain.
* @param {BlockHash.Type} [blockHash] - The hash of the block to perform the invocation of. Defaults to the latest finalized block on chain.
*
* @returns {InvokeContractResult} the contract invocation result, which includes whether or not the invocation succeeded along with the energy spent.
*/
Expand Down Expand Up @@ -394,7 +394,7 @@ export class CIS2Contract extends CISContract<Updates, Views, CIS2DryRun> {
deserializeCIS2BalanceOfResponse
);
return this.invokeView(
'balanceOf',
EntrypointName.fromStringUnchecked('balanceOf'),
serialize,
deserialize,
queries,
Expand Down Expand Up @@ -441,7 +441,7 @@ export class CIS2Contract extends CISContract<Updates, Views, CIS2DryRun> {
deserializeCIS2OperatorOfResponse
);
return this.invokeView(
'operatorOf',
EntrypointName.fromStringUnchecked('operatorOf'),
serialize,
deserialize,
queries,
Expand Down Expand Up @@ -488,7 +488,7 @@ export class CIS2Contract extends CISContract<Updates, Views, CIS2DryRun> {
deserializeCIS2TokenMetadataResponse
);
return this.invokeView(
'tokenMetadata',
EntrypointName.fromStringUnchecked('tokenMetadata'),
serialize,
deserialize,
tokenIds,
Expand Down
10 changes: 5 additions & 5 deletions packages/common/src/cis4/CIS4Contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ export class CIS4Contract extends CISContract<Updates, Views, CIS4DryRun> {
blockHash?: BlockHash.Type
): Promise<CIS4.CredentialEntry> {
return this.invokeView(
'credentialEntry',
EntrypointName.fromStringUnchecked('credentialEntry'),
(k) => Buffer.from(k, 'hex'),
deserializeCIS4CredentialEntry,
credHolderPubKey,
Expand All @@ -352,7 +352,7 @@ export class CIS4Contract extends CISContract<Updates, Views, CIS4DryRun> {
blockHash?: BlockHash.Type
): Promise<CIS4.CredentialStatus> {
return this.invokeView(
'credentialStatus',
EntrypointName.fromStringUnchecked('credentialStatus'),
(k) => Buffer.from(k, 'hex'),
deserializeCIS4CredentialStatus,
credHolderPubKey,
Expand All @@ -371,7 +371,7 @@ export class CIS4Contract extends CISContract<Updates, Views, CIS4DryRun> {
blockHash?: BlockHash.Type
): Promise<CIS4.RevocationKeyWithNonce[]> {
return this.invokeView(
'revocationKeys',
EntrypointName.fromStringUnchecked('revocationKeys'),
() => Buffer.alloc(0),
deserializeCIS4RevocationKeys,
undefined,
Expand All @@ -390,7 +390,7 @@ export class CIS4Contract extends CISContract<Updates, Views, CIS4DryRun> {
blockHash?: BlockHash.Type
): Promise<CIS4.MetadataResponse> {
return this.invokeView(
'registryMetadata',
EntrypointName.fromStringUnchecked('registryMetadata'),
() => Buffer.alloc(0),
deserializeCIS4MetadataResponse,
undefined,
Expand All @@ -407,7 +407,7 @@ export class CIS4Contract extends CISContract<Updates, Views, CIS4DryRun> {
*/
public issuer(blockHash?: BlockHash.Type): Promise<HexString> {
return this.invokeView(
'issuer',
EntrypointName.fromStringUnchecked('issuer'),
() => Buffer.alloc(0),
(value) => value,
undefined,
Expand Down
7 changes: 3 additions & 4 deletions packages/common/src/grpc/GRPCClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import * as ContractAddress from '../types/ContractAddress.js';
import * as Parameter from '../types/Parameter.js';
import * as Energy from '../types/Energy.js';
import * as SequenceNumber from '../types/SequenceNumber.js';
import * as ReceiveName from '../types/ReceiveName.js';

/**
* @hidden
Expand Down Expand Up @@ -293,7 +294,7 @@ export class ConcordiumGRPCClient {
invoker: getInvokerInput(context.invoker),
instance: context.contract,
amount: { value: context.amount?.microCcdAmount || 0n },
entrypoint: { value: context.method },
entrypoint: ReceiveName.toProto(context.method),
parameter: Parameter.toProto(
context.parameter ?? Parameter.empty()
),
Expand Down Expand Up @@ -1564,9 +1565,7 @@ export function getAccountIdentifierInput(
if (AccountAddress.isAccountAddress(accountIdentifier)) {
returnIdentifier = {
oneofKind: 'address',
address: {
value: AccountAddress.toBuffer(accountIdentifier),
},
address: AccountAddress.toProto(accountIdentifier),
};
} else if (
CredentialRegistrationId.isCredentialRegistrationId(accountIdentifier)
Expand Down
12 changes: 7 additions & 5 deletions packages/common/src/grpc/translation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,9 @@ function translateChainParametersCommon(
euroPerEnergy: unwrap(params.euroPerEnergy?.value),
microGTUPerEuro: unwrap(params.microCcdPerEuro?.value),
accountCreationLimit: unwrap(params.accountCreationLimit?.value),
foundationAccount: unwrapToBase58(params.foundationAccount),
foundationAccount: AccountAddress.fromProto(
unwrap(params.foundationAccount)
),
level1Keys: trHigherLevelKeysUpdate(unwrap(params.level1Keys)),
rootKeys: trHigherLevelKeysUpdate(unwrap(params.rootKeys)),
};
Expand Down Expand Up @@ -1895,7 +1897,7 @@ function trAccountTransactionSummary(
unwrap(contractInit.address)
),
amount: unwrap(contractInit.amount?.value),
initName: unwrap(contractInit.initName?.value),
initName: InitName.fromProto(unwrap(contractInit.initName)),
events: unwrap(contractInit.events.map(unwrapValToHex)),
contractVersion: unwrap(contractInit.contractVersion),
ref: unwrapValToHex(contractInit.originRef),
Expand Down Expand Up @@ -2387,7 +2389,7 @@ export function delegatorInfo(
delegatorInfo: v2.DelegatorInfo
): v1.DelegatorInfo {
return {
account: unwrapToBase58(delegatorInfo.account),
account: AccountAddress.fromProto(unwrap(delegatorInfo.account)),
stake: unwrap(delegatorInfo.stake?.value),
...(delegatorInfo.pendingChange && {
pendingChange: trPendingChange(delegatorInfo.pendingChange),
Expand All @@ -2397,7 +2399,7 @@ export function delegatorInfo(

export function branch(branchV2: v2.Branch): v1.Branch {
return {
blockHash: unwrapValToHex(branchV2.blockHash),
blockHash: BlockHash.fromProto(unwrap(branchV2.blockHash)),
children: branchV2.children.map(branch),
};
}
Expand All @@ -2407,7 +2409,7 @@ function trBakerElectionInfo(
): v1.BakerElectionInfo {
return {
baker: unwrap(bakerElectionInfo.baker?.value),
account: unwrapToBase58(bakerElectionInfo.account),
account: AccountAddress.fromProto(unwrap(bakerElectionInfo.account)),
lotteryPower: bakerElectionInfo.lotteryPower,
};
}
Expand Down
1 change: 1 addition & 0 deletions packages/common/src/json-rpc/JsonRpcClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,7 @@ export class JsonRpcClient {
const context = {
...contractContext,
invoker,
method: contractContext.method.value,
energy:
contractContext.energy === undefined
? undefined
Expand Down
2 changes: 2 additions & 0 deletions packages/common/src/pub/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ import * as AccountAddress from '../types/AccountAddress.js';
import * as ContractAddress from '../types/ContractAddress.js';
import * as EntrypointName from '../types/EntrypointName.js';
import * as Timestamp from '../types/Timestamp.js';
import * as Duration from '../types/Duration.js';

// These cannot be exported directly as modules because of a bug in an eslint plugin.
// https://github.com/import-js/eslint-plugin-import/issues/2289.
Expand All @@ -83,4 +84,5 @@ export {
ContractAddress,
EntrypointName,
Timestamp,
Duration,
};
10 changes: 5 additions & 5 deletions packages/common/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ export interface ChainParametersCommon {
/** Limit for the number of account creations in a block */
accountCreationLimit: number;
/** The chain foundation account */
foundationAccount: Base58String;
foundationAccount: AccountAddress.Type;
/** The chain foundation account index */
foundationAccountIndex?: bigint;
/** Keys allowed to do level1 updates */
Expand Down Expand Up @@ -1408,7 +1408,7 @@ export interface ArInfo {
}

interface DelegatorInfoCommon {
account: Base58String;
account: AccountAddress.Type;
stake: Amount;
}
export interface DelegatorInfo extends DelegatorInfoCommon {
Expand All @@ -1418,13 +1418,13 @@ export interface DelegatorInfo extends DelegatorInfoCommon {
export type DelegatorRewardPeriodInfo = DelegatorInfoCommon;

export interface Branch {
blockHash: HexString;
blockHash: BlockHash.Type;
children: Branch[];
}

export interface BakerElectionInfo {
baker: BakerId;
account: Base58String;
account: AccountAddress.Type;
lotteryPower: number;
}

Expand Down Expand Up @@ -1842,7 +1842,7 @@ export interface ContractContext {
invoker?: ContractAddress.Type | AccountAddress.Type;
contract: ContractAddress.Type;
amount?: CcdAmount;
method: string;
method: ReceiveName.Type;
parameter?: Parameter.Type;
energy?: Energy.Type;
}
Expand Down
14 changes: 12 additions & 2 deletions packages/common/src/types/AccountAddress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ export function fromBase58(address: string): AccountAddress {
`The provided address '${address}' does not use version byte with value of 1`
);
}
const decodedAddress = buffer.subarray(1);
return new AccountAddress(address, decodedAddress);
const decodedAddress = buffer.subarray(1, 33); // Ensure only the 32 bytes for the address is kept.
return new AccountAddress(address, new Uint8Array(decodedAddress));
}

/**
Expand Down Expand Up @@ -180,3 +180,13 @@ export function toProto(accountAddress: AccountAddress): Proto.AccountAddress {
value: accountAddress.decodedAddress,
};
}

/**
* Check if two account addresses are the exact same. This will not consider different aliases for the same account as equal.
* @param {AccountAddress} left
* @param {AccountAddress} right
* @returns {boolean} True if they are equal.
*/
export function equals(left: AccountAddress, right: AccountAddress): boolean {
return left.address === right.address;
}
22 changes: 21 additions & 1 deletion packages/common/src/types/BlockHash.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import type { HexString } from '../types.js';
import type * as Proto from '../grpc-api/v2/concordium/types.js';

/**
* The number of bytes used to represent a block hash.
*/
const blockHashByteLength = 32;

/**
* Represents a hash of a block in the chain.
*/
Expand All @@ -25,7 +30,7 @@ export type Type = BlockHash;
* @returns {BlockHash}
*/
export function fromBuffer(buffer: ArrayBuffer): BlockHash {
if (buffer.byteLength !== 32) {
if (buffer.byteLength !== blockHashByteLength) {
throw new Error(
`Invalid transaction hash provided: Expected a buffer containing 32 bytes, instead got '${Buffer.from(
buffer
Expand Down Expand Up @@ -93,3 +98,18 @@ export function toBlockHashInput(blockHash: BlockHash): Proto.BlockHashInput {
blockHashInput: { oneofKind: 'given', given: toProto(blockHash) },
};
}

/**
* Check if two transaction hashes are the same.
* @param {BlockHash} left
* @param {BlockHash} right
* @returns {boolean} True if they are equal.
*/
export function equals(left: BlockHash, right: BlockHash): boolean {
for (let i = 0; i < blockHashByteLength; i++) {
if (left.buffer.at(i) !== right.buffer.at(i)) {
return false;
}
}
return true;
}
10 changes: 10 additions & 0 deletions packages/common/src/types/ContractAddress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,13 @@ export function toProto(
subindex: contractAddress.subindex,
};
}

/**
* Check if two contract addresses are the same.
* @param {ContractAddress} left
* @param {ContractAddress} right
* @returns {boolean} True if they are equal.
*/
export function equals(left: ContractAddress, right: ContractAddress): boolean {
return left.index === right.index && left.subindex === right.subindex;
}
2 changes: 1 addition & 1 deletion packages/common/src/types/CredentialRegistrationId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export function isCredentialRegistrationId(
typeof input.credId === 'string' &&
input.credId.length === 96 &&
isHex(input.credId) &&
(parseInt(input.credId.substring(0, 2), 16) & 0b10000000) === 0
(parseInt(input.credId.substring(0, 2), 16) & 0b10000000) !== 0
);
}

Expand Down
10 changes: 10 additions & 0 deletions packages/common/src/types/ReceiveName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,13 @@ export function toProto(receiveName: ReceiveName): Proto.ReceiveName {
value: receiveName.value,
};
}

/**
* Check if two smart contract receive names represent the same.
* @param {ReceiveName} left
* @param {ReceiveName} right
* @returns {boolean} True if they are equal.
*/
export function equals(left: ReceiveName, right: ReceiveName): boolean {
return left.value === right.value;
}
Loading

0 comments on commit 90b3ff7

Please sign in to comment.