Skip to content
Closed
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
6 changes: 5 additions & 1 deletion chain-api/src/ethers/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,11 @@ export function isError<K extends ErrorCode, T extends CodedEthersError<K>>(erro
* required properties. The error message will also include the %%message%%,
* ethers version, %%code%% and all additional properties, serialized.
*/
export function makeError<K extends ErrorCode, T>(message: string, code: K, info?: ErrorInfo<T>): T {
export function makeError<K extends ErrorCode, T>(
message: string,
code: K,
info?: ErrorInfo<T>
): T {
const shortMessage = message;

{
Expand Down
8 changes: 7 additions & 1 deletion chain-api/src/ethers/signature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,13 @@ export class Signature {
/**
* Returns a representation that is compatible with ``JSON.stringify``.
*/
toJSON(): any {
toJSON(): {
_type: "signature";
networkV: null | string;
r: string;
s: string;
v: 27 | 28;
} {
const networkV = this.networkV;
return {
_type: "signature",
Expand Down
4 changes: 2 additions & 2 deletions chain-api/src/ethers/utils/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export function getBytesCopy(value: BytesLike, name?: string): Uint8Array {
* %%value%% is a valid [[DataHexString]] of %%length%% (if a //number//)
* bytes of data (e.g. ``0x1234`` is 2 bytes).
*/
export function isHexString(value: any, length?: number | boolean): value is `0x${string}` {
export function isHexString(value: unknown, length?: number | boolean): value is `0x${string}` {
if (typeof value !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) {
return false;
}
Expand All @@ -101,7 +101,7 @@ export function isHexString(value: any, length?: number | boolean): value is `0x
* Returns true if %%value%% is a valid representation of arbitrary
* data (i.e. a valid [[DataHexString]] or a Uint8Array).
*/
export function isBytesLike(value: any): value is BytesLike {
export function isBytesLike(value: unknown): value is BytesLike {
return isHexString(value, true) || value instanceof Uint8Array;
}

Expand Down
18 changes: 14 additions & 4 deletions chain-api/src/ethers/utils/maths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,13 @@ export function getBigInt(value: BigNumberish, name?: string): bigint {
return -BigInt(value.substring(1));
}
return BigInt(value);
} catch (e: any) {
assertArgument(false, `invalid BigNumberish string: ${e.message}`, name || "value", value);
} catch (e: unknown) {
assertArgument(
false,
`invalid BigNumberish string: ${e instanceof Error ? e.message : e}`,
name || "value",
value
);
}
}
assertArgument(false, "invalid BigNumberish value", name || "value", value);
Expand Down Expand Up @@ -173,8 +178,13 @@ export function getNumber(value: BigNumberish, name?: string): number {
throw new Error("empty string");
}
return getNumber(BigInt(value), name);
} catch (e: any) {
assertArgument(false, `invalid numeric string: ${e.message}`, name || "value", value);
} catch (e: unknown) {
assertArgument(
false,
`invalid numeric string: ${e instanceof Error ? e.message : e}`,
name || "value",
value
);
}
}
assertArgument(false, "invalid numeric value", name || "value", value);
Expand Down
4 changes: 3 additions & 1 deletion chain-api/src/ethers/utils/utf8.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ function errorFunc(
output: Array<number>,
badCodepoint?: number
): number {
assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes);
// @ts-ignore
return assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes);
}

function ignoreFunc(
Expand All @@ -104,6 +105,7 @@ function ignoreFunc(
output: Array<number>,
badCodepoint?: number
): number {
// @ts-ignore
// If there is an invalid prefix (including stray continuation), skip any additional continuation bytes
if (reason === "BAD_PREFIX" || reason === "UNEXPECTED_CONTINUE") {
let i = 0;
Expand Down
13 changes: 10 additions & 3 deletions chain-api/src/types/TokenBalance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -632,15 +632,22 @@ export class TokenHold {
}

public isVestingStarted(currentTime: number): boolean {
return this.isVestingHold() && currentTime >= this.vestingPeriodStart!;
return this.isVestingHold() && this.vestingPeriodStart !== undefined && currentTime >= this.vestingPeriodStart;
}

public timeSinceStart(currentTime: number): number {
return this.isVestingHold() ? currentTime - this.vestingPeriodStart! : 0;
const start = this.vestingPeriodStart;
if (start === undefined || !this.isVestingStarted(currentTime)) {
return 0;
}
return currentTime - start;
}

public totalTimeOfVestingPeriod(): number {
return this.isVestingHold() ? this.expires - this.vestingPeriodStart! : 0;
if (!this.isVestingHold() || this.vestingPeriodStart === undefined) {
return 0;
}
return this.expires - this.vestingPeriodStart;
}

// For vesting holds, this returns the quantity that is currently locked by vesting
Expand Down
1 change: 0 additions & 1 deletion chain-api/src/types/TokenClass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import { ChainKey } from "../utils";
import { BigNumberIsPositive, BigNumberProperty, IsUserAlias } from "../validators";
import { ChainObject } from "./ChainObject";
import { UserAlias } from "./UserAlias";
import { UserRef } from "./UserRef";
import { GC_NETWORK_ID } from "./contract";
import { ChainCallDTO } from "./dtos";

Expand Down
4 changes: 3 additions & 1 deletion chain-api/src/types/dtos.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ it("should parse TestDtoWithArray", async () => {
expect(await getPlainOrError(TestDtoWithArray, valid)).toEqual({ playerIds: ["123"] });
expect(await getPlainOrError(TestDtoWithArray, invalid1)).toEqual(failedArrayMatcher);
expect(await getPlainOrError(TestDtoWithArray, invalid2)).toEqual(failedArrayMatcher);
expect(await getPlainOrError(TestDtoWithArray, invalid3)).toEqual("Unexpected end of JSON input");
expect(await getPlainOrError(TestDtoWithArray, invalid3)).toEqual(
"Unterminated string in JSON at position 16 (line 1 column 17)"
);
});

it("should parse TestDtoWithBigNumber", async () => {
Expand Down
1 change: 0 additions & 1 deletion chain-api/src/types/dtos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import {
IsOptional,
Max,
Min,
MinLength,
ValidateNested,
ValidationError,
validate
Expand Down
16 changes: 8 additions & 8 deletions chain-api/src/utils/generate-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,20 @@ function customTargetConstructorToSchema(classType: ClassConstructor) {
};
return schemaObj;
},
["IsUserAliasConstraint"]: (meta) => {
return {
["IsUserAliasConstraint"]: (meta) =>
// @ts-ignore
({
type: "string",
description:
"Allowed value is string following the format of 'client|<user-id>', or 'eth|<checksumed-eth-addr>', or valid system-level username."
};
},
["IsUserRefConstraint"]: (meta) => {
return {
}),
["IsUserRefConstraint"]: (meta) =>
// @ts-ignore
({
type: "string",
description:
"Allowed value is a user alias ('client|<user-id>', or 'eth|<checksumed-eth-addr>', or 'ton|<chain:ton-address>', or valid system-level username), or valid Ethereum address."
};
}
})
},
classTransformerMetadataStorage: defaultMetadataStorage
});
Expand Down
8 changes: 5 additions & 3 deletions chain-api/src/utils/signatures/getPayloadToSign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ import { TypedDataEncoder } from "../../ethers/hash/typed-data";
import serialize from "../serialize";

// Type definitions
type EIP712Domain = Record<string, any>;
type EIP712Types = Record<string, any>;
type EIP712Value = Record<string, any>;
import { TypedDataField } from "../../ethers/hash/typed-data";

type EIP712Domain = Record<string, unknown>;
type EIP712Types = Record<string, Array<TypedDataField>>;
type EIP712Value = Record<string, unknown>;

interface EIP712Object {
domain: EIP712Domain;
Expand Down
2 changes: 1 addition & 1 deletion chain-api/src/utils/signatures/ton.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { NotImplementedError, ValidationFailedError } from "../error";
import { ValidationFailedError } from "../error";
import { getPayloadToSign } from "./getPayloadToSign";

// verify if TON is supported
Expand Down
3 changes: 1 addition & 2 deletions chain-cli/src/commands/info/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import { Args, Flags } from "@oclif/core";

import BaseCommand from "../../base-command";
import { ChaincodeInfoDto } from "../../dto";
import { getChaincodeDefinition, getDeploymentResponse, getPrivateKey } from "../../galachain-utils";

export default class Info extends BaseCommand<typeof Info> {
Expand Down Expand Up @@ -46,7 +45,7 @@ export default class Info extends BaseCommand<typeof Info> {
};

async run(): Promise<void> {
const { args, flags } = await this.parse(Info);
const { args } = await this.parse(Info);

const chaincode = await getChaincodeDefinition();
const developerPrivateKey = await getPrivateKey(args.developerPrivateKey, chaincode.name);
Expand Down
34 changes: 19 additions & 15 deletions chain-cli/src/commands/keygen/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,26 @@ import KeyGen from "./index";
jest.setTimeout(10 * 1000);

describe("KeyGen Command", () => {
it("should check KeyGen Command", async () => {
const result: (string | Uint8Array)[] = [];
jest.spyOn(process.stdout, "write").mockImplementation((v) => {
result.push(v);
return true;
});
it(
"should check KeyGen Command",
async () => {
const result: (string | Uint8Array)[] = [];
jest.spyOn(process.stdout, "write").mockImplementation((v) => {
result.push(v);
return true;
});

const target = path.resolve(__dirname, "./test-key");
await KeyGen.run([target]);
const target = path.resolve(__dirname, "./test-key");
await KeyGen.run([target]);

expect(result.join()).toContain(`Writing keys to ${target}`);
expect(result.join()).toContain(`public key... ${target}.pub`);
expect(result.join()).toContain(`private key... ${target}`);
expect(result.join()).toContain(`Writing keys to ${target}`);
expect(result.join()).toContain(`public key... ${target}.pub`);
expect(result.join()).toContain(`private key... ${target}`);

// delete generated files
await fs.unlink(`${target}.pub`);
await fs.unlink(target);
});
// delete generated files
await fs.unlink(`${target}.pub`);
await fs.unlink(target);
},
30000
);
});
16 changes: 10 additions & 6 deletions chain-cli/src/commands/logs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,9 @@ export default class Log extends BaseCommand<typeof Log> {
for (const logEntry of logs) {
this.printLog(logEntry);
}
} catch (error: any) {
throw new FetchLogsError(error.message);
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
throw new FetchLogsError(message);
}
}

Expand All @@ -147,8 +148,9 @@ export default class Log extends BaseCommand<typeof Log> {
this.handleSSEEvent(eventBlock);
});
});
} catch (error: any) {
throw new FetchLogsError(error.message);
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
throw new FetchLogsError(message);
}
}

Expand Down Expand Up @@ -261,15 +263,17 @@ export default class Log extends BaseCommand<typeof Log> {
);
}

handleError(error: any): void {
handleError(error: unknown): void {
if (error instanceof UnauthorizedError) {
this.error(chalk.red(`Unauthorized: ${error.message}`), { exit: 1 });
} else if (error instanceof BadRequestError) {
this.error(chalk.yellow(`Bad Request: ${error.message}`), { exit: 1 });
} else if (error instanceof FetchLogsError) {
this.error(chalk.red(`Failed to fetch logs: ${error.message}`), { exit: 1 });
} else {
} else if (error instanceof Error) {
this.error(chalk.red(`An unexpected error occurred: ${error.message}`), { exit: 1 });
} else {
this.error(chalk.red(`An unexpected error occurred: ${error}`), { exit: 1 });
}
}
}
26 changes: 21 additions & 5 deletions chain-cli/src/commands/network-up/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,16 @@ function updatedFabloConfigWithEntry(
return updated;
}

function customValidation(flags: any): void {
interface CustomValidationFlags {
channel: string[];
channelType: ("curator" | "partner")[];
chaincodeName: string[];
chaincodeDir: string[];
envConfig?: string;
watch: boolean;
}

function customValidation(flags: CustomValidationFlags): void {
const { channel, channelType, chaincodeName, chaincodeDir, envConfig } = flags;

/*
Expand Down Expand Up @@ -372,7 +381,7 @@ function customValidation(flags: any): void {
(channel, chaincodeName) pairs should be unique
*/
channel
.map((ch: any, i: string | number) => `(${ch}, ${chaincodeName[i]})`)
.map((ch: string, i: number) => `(${ch}, ${chaincodeName[i]})`)
.forEach((pair: string, i: number, arr: string[]) => {
if (arr.filter((p) => p === pair).length > 1) {
throw new Error(`Error: Found non-unique channel-chaincode pair: ${pair}`);
Expand All @@ -389,9 +398,16 @@ function customValidation(flags: any): void {
}
}

function reduce(args: any): SingleArg[] {
return args.chaincodeName.map((chaincodeName: unknown, i: number) => ({
chaincodeName,
interface ReduceArgs {
chaincodeName: string[];
chaincodeDir?: string[];
channel: string[];
channelType: ("curator" | "partner")[];
}

function reduce(args: ReduceArgs): SingleArg[] {
return args.chaincodeName.map((chaincodeName: string, i: number) => ({
chaincodeName: chaincodeName,
chaincodeDir: args.chaincodeDir?.[i],
channel: args.channel[i],
channelType: args.channelType[i]
Expand Down
Loading
Loading