Skip to content

Commit

Permalink
hook up query and service for new functional syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
lastmjs committed Sep 20, 2023
1 parent 8d6d858 commit daf32e4
Show file tree
Hide file tree
Showing 16 changed files with 160 additions and 29 deletions.
9 changes: 4 additions & 5 deletions examples/query/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { query, Service, text } from 'azle';

export default class extends Service {
@query([], text)
simpleQuery(): text {
export default Service({
simpleQuery: query([], text, () => {
return 'This is a query function';
}
}
})
});
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"bin": {
"azle": "./bin.js"
},
"main": "./src/lib_new/index.ts",
"main": "./src/lib_functional/index.ts",
"repository": {
"type": "git",
"url": "git+https://github.com/demergent-labs/azle.git"
Expand Down
4 changes: 2 additions & 2 deletions src/compiler/generate_candid_and_canister_methods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function generateCandidAndCanisterMethods(mainJs: string): {
script.runInContext(context);

return {
candid: (sandbox.globalThis as any)._azleCandidService,
canisterMethods: (sandbox.globalThis as any)._azleCanisterMethods
candid: (sandbox.exports as any).canisterMethods.candid,
canisterMethods: (sandbox.exports as any).canisterMethods
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -278,8 +278,9 @@ fn main() -> Result<(), String> {

let global = context.global_object().unwrap();
let exports = global.get_property("exports").unwrap();
let class = exports.get_property("canisterClass").unwrap();
let method = class.get_property(function_name).unwrap();
let canister_methods = exports.get_property("canisterMethods").unwrap();
let callbacks = canister_methods.get_property("callbacks").unwrap();
let method = callbacks.get_property(function_name).unwrap();

let candid_args = if pass_arg_data { ic_cdk::api::call::arg_data_raw() } else { vec![] };

Expand Down
19 changes: 2 additions & 17 deletions src/compiler/typescript_to_rust/typescript_to_javascript/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,34 +33,19 @@ export function compileTypeScriptToJavaScript(
import { ic } from 'azle';
export { Principal } from '@dfinity/principal';
export * from './${tsPath}';
import CanisterClass from './${tsPath}';
`;

const canisterClassInstantiation = `
export const canisterClass = new CanisterClass(ic.id());
`;

const candidGeneration = `
globalThis._azleCandidService = \`\${CanisterClass._azleCandidTypes.length > 0 ? CanisterClass._azleCandidTypes.join(';\\n') + ';\\n' : ''}service: (\${CanisterClass._azleCandidInitParams.join(
', '
)}) -> {
\${CanisterClass._azleCandidMethods.join('\\n ')}
}\n\`
import CanisterMethods from './${tsPath}';
globalThis._azleCanisterMethods = CanisterClass._azleCanisterMethods;
export const canisterMethods = CanisterMethods;
`;

const canisterJavaScript = bundleAndTranspileJs(`
${globalThisProcess}
${imports}
${canisterClassInstantiation}
${candidGeneration}
`);

const candidJavaScript = bundleAndTranspileJs(`
${globalThisProcess}
${imports}
${candidGeneration}
`);

return {
Expand Down
4 changes: 4 additions & 0 deletions src/compiler/utils/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,17 @@ export type CompilerInfo = {
};

export type CanisterMethods = {
candid: string;
queries: CanisterMethod[];
updates: CanisterMethod[];
init?: CanisterMethod;
pre_upgrade?: CanisterMethod;
post_upgrade?: CanisterMethod;
heartbeat?: CanisterMethod;
inspect_message?: CanisterMethod;
callbacks: {
[key: string]: (...args: any) => any;
};
};

export type CanisterMethod = {
Expand Down
1 change: 1 addition & 0 deletions src/lib_functional/candid/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './reference';
Empty file.
1 change: 1 addition & 0 deletions src/lib_functional/candid/reference/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './service';
Empty file.
55 changes: 55 additions & 0 deletions src/lib_functional/candid/reference/service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { CanisterMethods } from '../../../compiler/utils/types';
import { CanisterMethodInfo, query } from '../../canister_methods/query';

// type CanisterMethodType = 'query';
// type CanisterMethods = (typeof query & {
// canisterMethodType: CanisterMethodType;
// })[];

type ServiceOptions = {
[key: string]: CanisterMethodInfo;
};

export function Service(serviceOptions: ServiceOptions): CanisterMethods {
const callbacks = Object.entries(serviceOptions).reduce((acc, entry) => {
const key = entry[0];
const value = entry[1];

return {
...acc,
[key]: value.callback
};
}, {});

const queries = Object.entries(serviceOptions)
.filter((entry) => {
const key = entry[0];
const value = entry[1];

return value.type === 'query';
})
.map((entry) => {
const key = entry[0];
const value = entry[1];

return {
name: key
};
});

// TODO loop through each key and simply grab the candid off
// TODO grab the init/post_upgrade candid as well
return {
candid: `service: () -> {
${Object.entries(serviceOptions)
.map((entry) => {
return `${entry[0]}: ${entry[1].candid}`;
})
.join('')}
}
`,
queries,
updates: [],
callbacks
};
}
49 changes: 49 additions & 0 deletions src/lib_functional/canister_methods/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { IDL } from '../../lib_new/index';
import { ic } from '../../lib_new/ic';

export * from './query';

export function executeMethod(
paramCandid: any,
returnCandid: any,
args: any[],
callback: any
) {
const decoded = IDL.decode(paramCandid[0] as any, args[0]);

const result = callback(decoded);

if (
result !== undefined &&
result !== null &&
typeof result.then === 'function'
) {
result
.then((result: any) => {
// TODO this won't be accurate because we have most likely had
// TODO cross-canister calls
console.log(`final instructions: ${ic.instructionCounter()}`);

// if (!manual) {
const encodeReadyResult = result === undefined ? [] : [result];
const encoded = IDL.encode(
returnCandid[0] as any,
encodeReadyResult
);
ic.replyRaw(new Uint8Array(encoded));
// }
})
.catch((error: any) => {
ic.trap(error.toString());
});
} else {
const encodeReadyResult = result === undefined ? [] : [result];

// if (!manual) {
const encoded = IDL.encode(returnCandid[0] as any, encodeReadyResult);
ic.replyRaw(new Uint8Array(encoded));
// }

console.log(`final instructions: ${ic.instructionCounter()}`);
}
}
31 changes: 31 additions & 0 deletions src/lib_functional/canister_methods/query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {
handleRecursiveParams,
handleRecursiveReturn
} from '../../lib_new/method_decorators';
import { IDL } from '../../lib_new/index';
import { ic } from '../../lib_new/ic';
import { executeMethod } from '.';

export type CanisterMethodInfo = {
type: 'query';
callback: (...args: any) => any;
candid: string;
};

// TODO execute the candid stuff and just store it on the function itself?
export function query(
paramsIdls: any,
returnIdl: any,
callback: any
): CanisterMethodInfo {
const paramCandid = handleRecursiveParams(paramsIdls);
const returnCandid = handleRecursiveReturn(returnIdl, paramCandid[2]);

return {
type: 'query',
callback: (...args) => {
executeMethod(paramCandid, returnCandid, args, callback);
},
candid: `(${paramCandid[1].join(', ')}) -> (${returnCandid[1]}) query;`
};
}
1 change: 1 addition & 0 deletions src/lib_functional/canister_methods/update.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export function update() {}
4 changes: 4 additions & 0 deletions src/lib_functional/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from './canister_methods';
export * from './candid';
export * from '../lib_new/primitives';
export * from '../lib_new/ic';
4 changes: 2 additions & 2 deletions src/lib_new/method_decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,15 +174,15 @@ function newTypesToStingArr(newTypes: CandidTypesDefs): string[] {
);
}

function handleRecursiveParams(
export function handleRecursiveParams(
idls: CandidClass[]
): [CandidClass[], CandidDef[], CandidTypesDefs] {
const paramIdls = toParamCandidClasses(idls);
const paramInfo = paramIdls.map((paramIdl) => display(paramIdl, {}));
return [paramIdls, ...extractCandid(paramInfo, {})];
}

function handleRecursiveReturn(
export function handleRecursiveReturn(
returnIdl: ReturnCandidClass,
paramCandidTypeDefs: CandidTypesDefs
): [CandidClass[], CandidDef[], CandidTypesDefs] {
Expand Down

0 comments on commit daf32e4

Please sign in to comment.