Skip to content

Commit

Permalink
Fix service calls
Browse files Browse the repository at this point in the history
  • Loading branch information
dansteren committed Oct 1, 2023
1 parent a3fc7a3 commit 8b2d279
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 12 deletions.
34 changes: 34 additions & 0 deletions src/lib_functional/candid/serde.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,44 @@ export function decode(
// Azle-augmented ones
const realIDL = toIDLType(fakeIdl, []);

const idlIsAzleVoid = Array.isArray(realIDL);

if (idlIsAzleVoid) {
return undefined;
}

const candidDecodedValue = IDL.decode([realIDL], data)[0] as any;

return realIDL.accept(new DecodeVisitor(), {
js_class: fakeIdl,
js_data: candidDecodedValue
});
}

export function encodeMultiple(
data: any[],
fakeIdls: (IDL.Type<any> | CandidType)[]
): Uint8Array {
const { values, idls } = data.reduce<{
values: any[];
idls: IDL.Type<any>[];
}>(
(acc, datum, index) => {
const fakeIdl = fakeIdls[index];
const realIDL = toIDLType(fakeIdl, []);

const encodeReadyValue = realIDL.accept(new EncodeVisitor(), {
js_class: fakeIdl,
js_data: datum
});

return {
values: [...acc.values, encodeReadyValue],
idls: [...acc.idls, realIDL]
};
},
{ values: [], idls: [] }
);

return new Uint8Array(IDL.encode(idls, values));
}
10 changes: 3 additions & 7 deletions src/lib_new/service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { decode, encodeMultiple } from '../lib_functional/candid/serde';
import { ic, IDL, Principal } from './index';
import {
CandidClass,
Expand Down Expand Up @@ -108,9 +109,7 @@ export function serviceCall(
cycles: bigint,
...args: any[]
) {
const encodedArgs = new Uint8Array(
IDL.encode(toParamIDLTypes(paramsIdls), args)
);
const encodedArgs = encodeMultiple(args, paramsIdls);

if (notify) {
try {
Expand All @@ -131,10 +130,7 @@ export function serviceCall(
cycles
);

const returnIdls = toReturnIDLType(returnIdl);
const decodedResult = IDL.decode(returnIdls, encodedResult)[0];

return decodedResult;
return decode(encodedResult, returnIdl);
}
};
}
6 changes: 1 addition & 5 deletions src/lib_new/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,7 @@ export function toReturnIDLType(
): IDL.Type<any>[] {
const idlType = toIDLType(returnIdl, parents);

if (Array.isArray(idlType)) {
return [...idlType];
}

return [idlType];
return Array.isArray(idlType) ? idlType : [idlType];
}

export function isAsync(originalFunction: any) {
Expand Down

0 comments on commit 8b2d279

Please sign in to comment.