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

fix: optional fields not populated if wire type has additional fields #627

Merged
merged 7 commits into from Sep 20, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/candid/src/idl.test.ts
Expand Up @@ -660,3 +660,20 @@ test('should correctly decode expected optional fields with lower hash than requ
upgrade: [true],
});
});

test('should decode matching optional fields if input type contains more fields than output type', () => {
const InputType = IDL.Record({
latest_message: IDL.Opt(IDL.Text),
name: IDL.Text,
});
const OutputType = IDL.Record({
latest_message: IDL.Opt(IDL.Text),
});

const encoded = IDL.encode([InputType], [{ name: 'abc', latest_message: ['123'] }]);
const decoded = IDL.decode([OutputType], encoded)[0];

expect(decoded).toEqual({
latest_message: ['123'],
});
});
25 changes: 13 additions & 12 deletions packages/candid/src/idl.ts
Expand Up @@ -991,25 +991,26 @@ export class RecordClass extends ConstructType<Record<string, any>> {
}

const [expectKey, expectType] = this._fields[expectedRecordIdx];
if (idlLabelToId(this._fields[expectedRecordIdx][0]) !== idlLabelToId(hash)) {
// the current field on the wire does not match the expected field

// skip expected optional fields that are not present on the wire
const expectedId = idlLabelToId(this._fields[expectedRecordIdx][0]);
const actualId = idlLabelToId(hash);
if (expectedId === actualId) {
// the current field on the wire matches the expected field
x[expectKey] = expectType.decodeValue(b, type);
expectedRecordIdx++;
actualRecordIdx++;
} else if (actualId > expectedId) {
// The expected field does not exist on the wire
if (expectType instanceof OptClass || expectType instanceof ReservedClass) {
x[expectKey] = [];
expectedRecordIdx++;
continue;
} else {
throw new Error('Cannot find required field ' + expectKey);
}

// skip unexpected interspersed fields present on the wire
} else {
// The field on the wire does not exist in the output type, so we can skip it
type.decodeValue(b, type);
actualRecordIdx++;
continue;
}

x[expectKey] = expectType.decodeValue(b, type);
expectedRecordIdx++;
actualRecordIdx++;
}

// initialize left over expected optional fields
Expand Down