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

Guard functions #1855

Merged
merged 3 commits into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
3 changes: 2 additions & 1 deletion examples/composite_queries/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions examples/composite_queries/package.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"name": "composite_queries_end_to_end_test_functional_syntax",
"scripts": {
"pre_tests": "ts-node --transpile-only --ignore=false test/pretest.ts",
"tests": "npm run pre_tests && jest",
Expand Down
3 changes: 2 additions & 1 deletion examples/cross_canister_calls/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions examples/cross_canister_calls/package.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"name": "cross_canister_calls_end_to_end_test_functional_syntax",
"scripts": {
"pre_tests": "ts-node --transpile-only --ignore=false test/pretest.ts",
"tests": "npm run pre_tests && jest",
Expand Down
2 changes: 1 addition & 1 deletion examples/cross_canister_calls/test/tests.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ActorSubclass } from '@dfinity/agent';
import { getCanisterId } from 'azle/dfx';
import { expect, it, Test } from 'azle/test/jest';

import { getCanisterId } from '../../../dfx';
import { _SERVICE as CANISTER1_SERVICE } from './dfx_generated/canister1/canister1.did';
import { _SERVICE as CANISTER2_SERVICE } from './dfx_generated/canister2/canister2.did';

Expand Down
3 changes: 2 additions & 1 deletion examples/guard_functions/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions examples/guard_functions/package.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"name": "guard_functions_end_to_end_test_functional_syntax",
"scripts": {
"pretest": "ts-node --transpile-only --ignore=false test/pretest.ts",
"test": "jest"
Expand Down
3 changes: 2 additions & 1 deletion examples/manual_reply/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions examples/manual_reply/package.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"name": "manual_reply_end_to_end_test_functional_syntax",
"scripts": {
"pretest": "ts-node --transpile-only --ignore=false test/pretest.ts",
"test": "ts-node --transpile-only --ignore=false test/test.ts"
Expand Down
2 changes: 1 addition & 1 deletion src/compiler/generate_candid_and_canister_methods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export function generateCandidAndCanisterMethods(wasmFilePath: string): {

const memory = new Uint8Array((wasmInstance.exports.memory as any).buffer);

let candidBytes = [];
let candidBytes: number[] = [];
let i = candidPointer;
while (memory[i] !== 0) {
candidBytes.push(memory[i]);
Expand Down
2 changes: 1 addition & 1 deletion src/compiler/utils/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export type CanisterMethods = {
export type CanisterMethod = {
name: string;
composite?: boolean;
guard?: () => void;
guard_name?: string;
};

export type Plugin = {
Expand Down
2 changes: 1 addition & 1 deletion src/lib/globals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ type CanisterMethods = {
type CanisterMethod = {
name: string;
composite?: boolean;
guard?: () => void;
guard_name?: string;
};

declare global {
Expand Down
2 changes: 2 additions & 0 deletions src/lib/stable/execute_with_candid_serde.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export function executeWithCandidSerde(
new Uint8Array(IDL.encode([returnIdl], [result]))
);
} else {
// TODO is void best represented as IDL.encode([], [])?
ic.replyRaw(new Uint8Array(IDL.encode([], [])));
}
}
Expand All @@ -53,6 +54,7 @@ export function executeWithCandidSerde(
if (returnIdl !== undefined) {
ic.replyRaw(new Uint8Array(IDL.encode([returnIdl], [result])));
} else {
// TODO is void best represented as IDL.encode([], [])?
ic.replyRaw(new Uint8Array(IDL.encode([], [])));
}
}
Expand Down
26 changes: 26 additions & 0 deletions src/lib/stable/guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { handleUncaughtError } from './error';

// TODO guards can be asynchronous right? At least update guards
// TODO query guards should be able to be composite as well
// TODO seems like in ic-cdk they cannot be asynchronous
// TODO but seems like ICP would allow them to be
export function createGlobalGuard(
guard: (() => any) | undefined,
guardedMethodName: string
): string | undefined {
if (guard === undefined) {
return undefined;
}

const guardName = `_azleGuard_${guardedMethodName}`;

globalThis._azleGuardFunctions[guardName] = () => {
try {
guard();
} catch (error) {
handleUncaughtError(error);
}
};

return guardName;
}
8 changes: 4 additions & 4 deletions src/lib/stable/ic_apis/call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { v4 } from 'uuid'; // TODO is uuid experimental?

import { IDL, Principal } from '../';

export async function call(
export async function call<T>(
canisterId: Principal | string,
method: string,
options?: {
Expand All @@ -11,7 +11,7 @@ export async function call(
args?: any[];
payment?: bigint;
}
): Promise<any> {
): Promise<T> {
// TODO this should use a Result remember
return new Promise((resolve, reject) => {
if (globalThis._azleIc === undefined) {
Expand All @@ -29,9 +29,9 @@ export async function call(
// TODO if they are over a certain amount old we can delete them
globalThis._azleResolveIds[globalResolveId] = (result: ArrayBuffer) => {
if (returnIdl === undefined) {
resolve(undefined);
resolve(undefined as T);
} else {
resolve(IDL.decode([returnIdl], result)[0]);
resolve(IDL.decode([returnIdl], result)[0] as T);
}

delete globalThis._azleResolveIds[globalResolveId];
Expand Down
12 changes: 12 additions & 0 deletions src/lib/stable/ic_apis/candid_encode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Converts a Candid string into bytes
* @param candidString a valid Candid string
* @returns the candid value as bytes
*/
export function candidEncode(candidString: string): Uint8Array {
if (globalThis._azleIc === undefined) {
return undefined as any;
}

return new Uint8Array(globalThis._azleIc.candidEncode(candidString));
}
15 changes: 15 additions & 0 deletions src/lib/stable/ic_apis/id.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Principal } from '..';

/**
* Gets the id of this canister
* @returns the canister id
*/
export function id(): Principal {
if (globalThis._azleIc === undefined) {
return undefined as any;
}

// TODO consider bytes instead of string, just like with caller
const idString = globalThis._azleIc.id();
return Principal.fromText(idString);
}
7 changes: 7 additions & 0 deletions src/lib/stable/ic_apis/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
export { call } from './call';
export { candidEncode } from './candid_encode';
export { id } from './id';
export { notify } from './notify';
export { reject } from './reject';
export { reply } from './reply';
export { replyRaw } from './reply_raw';
export { trap } from './trap';
42 changes: 42 additions & 0 deletions src/lib/stable/ic_apis/notify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { IDL, Principal } from '../';

/**
* Performs a cross-canister call without awaiting the result
* @param canisterId
* @param method
* @param argsRaw
* @param payment
* @returns
*/
export function notify(
canisterId: Principal | string,
method: string,
options?: {
paramIdls?: IDL.Type[];
args?: any[];
payment?: bigint;
}
): void {
if (globalThis._azleIc === undefined) {
return undefined as any;
}

const paramIdls = options?.paramIdls ?? [];
const args = options?.args ?? [];
const payment = options?.payment ?? 0n;

const canisterIdPrincipal =
typeof canisterId === 'string'
? Principal.fromText(canisterId)
: canisterId;
const canisterIdBytes = canisterIdPrincipal.toUint8Array().buffer;
const argsRawBuffer = new Uint8Array(IDL.encode(paramIdls, args)).buffer;
const paymentString = payment.toString();

return globalThis._azleIc.notifyRaw(
canisterIdBytes,
method,
argsRawBuffer,
paymentString
);
}
7 changes: 7 additions & 0 deletions src/lib/stable/ic_apis/reject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* Rejects the current call with the provided message
* @param message the rejection message
*/
export function reject(message: string): void {
return globalThis._azleIc ? globalThis._azleIc.reject(message) : undefined;
}
22 changes: 22 additions & 0 deletions src/lib/stable/ic_apis/reply.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { IDL } from '..';

/**
* Used to manually reply to an ingress message. Intended to be used in
* canister methods with a {@link Manual} return type.
* @param reply the value with which to reply. Must be of type `T` where `T`
* is the generic type supplied to `Manual<T>`. Otherwise will result in an
* uncaught `TypeError`.
*/
export function reply<T>(data: T, type?: IDL.Type): void {
if (globalThis._azleIc === undefined) {
return undefined as any;
}

// TODO is void best represented as IDL.encode([], [])?
const encoded =
type === undefined
? new Uint8Array(IDL.encode([], [])).buffer
: new Uint8Array(IDL.encode([type], [data])).buffer;

return globalThis._azleIc.replyRaw(encoded);
}
22 changes: 22 additions & 0 deletions src/lib/stable/ic_apis/reply_raw.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* Used to manually reply to an ingress message. Intended to be used in
* canister methods with a {@link Manual} return type.
* @param buf the value with which to reply. Intended to be used in conjunction with
* {@link ic.candidEncode}.
* @example
* ```ts
* $update;
* export function replyRaw(): Manual<RawReply> {
* ic.replyRaw(
* ic.candidEncode(
* '(record { "int" = 42; "text" = "text"; "bool" = true; "blob" = blob "raw bytes"; "variant" = variant { Medium } })'
* )
* );
* }
* ```
*/
export function replyRaw(replyBuffer: Uint8Array): void {
return globalThis._azleIc
? globalThis._azleIc.replyRaw(replyBuffer.buffer)
: undefined;
}
12 changes: 12 additions & 0 deletions src/lib/stable/ic_apis/trap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Stops execution and rejects the current request with a `CANISTER_ERROR`
* (5) rejection code and the provided message
* @param message the rejection message
*/
export function trap(message: string): never {
if (globalThis._azleIc === undefined) {
return undefined as never;
}

return globalThis._azleIc.trap(message);
}
1 change: 0 additions & 1 deletion src/lib/stable/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export * from '../ic';
export * from '../stable_structures/stable_b_tree_map';
export * from '../stable_structures/stable_json';
export { heartbeat } from './heartbeat';
Expand Down
18 changes: 13 additions & 5 deletions src/lib/stable/query.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { IDL } from '@dfinity/candid';

import { isAsync } from '../canister_methods/is_async';
import { executeWithCandidSerde } from './execute_with_candid_serde';
import { createGlobalGuard } from './guard';

export function query(
paramIdls: IDL.Type[],
returnIdl?: IDL.Type
returnIdl?: IDL.Type,
options?: {
composite?: boolean;
manual?: boolean;
guard?: () => void; // TODO can guard functions be async?
}
): MethodDecorator {
return <T>(
target: object,
Expand All @@ -21,16 +26,19 @@ export function query(
originalMethod,
paramIdls,
returnIdl,
false // TODO implement manual check
options?.manual ?? false
);
};

descriptor.value = methodCallback as any;

globalThis._azleCanisterMethods.queries.push({
name: propertyKey as string,
composite: isAsync(originalMethod)
// TODO implement guard
composite: options?.composite ?? false,
guard_name:
options?.guard === undefined
? undefined
: createGlobalGuard(options?.guard, propertyKey as string)
});

globalThis._azleCanisterMethods.callbacks[propertyKey as string] =
Expand Down
Loading
Loading