Skip to content

Commit 2730a39

Browse files
committed
fix: use first constructor if it not exist in kind
(cherry picked from commit 1f822430b70765faf1909ee8fe0a2f4f2c473468)
1 parent bec1243 commit 2730a39

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

src/tlb-runtime/TLBRuntime.ts

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -148,20 +148,20 @@ export class TLBRuntime<T extends ParsedCell = ParsedCell> {
148148
}
149149

150150
serialize(data: T): Result<Builder> {
151-
const kind = (data as TypedCell).kind;
152-
if (!kind) {
151+
const typeKind = (data as TypedCell).kind;
152+
if (!typeKind) {
153153
return {
154154
ok: false,
155155
error: new TLBDataError('Data must by typed'),
156156
};
157157
}
158-
const sep = kind.indexOf('_');
159-
const typeName = kind.slice(0, sep);
160-
return this.serializeByTypeName(typeName, data);
158+
return this.serializeByTypeName(typeKind, data);
161159
}
162160

163161
// Serialize data to a Builder based on a TL-B type name
164-
serializeByTypeName(typeName: string, data: T): Result<Builder> {
162+
serializeByTypeName(typeKind: string, data: T): Result<Builder> {
163+
const sep = typeKind.indexOf('_');
164+
const typeName = sep === -1 ? typeKind : typeKind.slice(0, sep);
165165
const type = this.types.get(typeName);
166166
if (!type) {
167167
return {
@@ -423,11 +423,20 @@ export class TLBRuntime<T extends ParsedCell = ParsedCell> {
423423
// eslint-disable-next-line @typescript-eslint/no-explicit-any
424424
private serializeType(type: TLBType, data: any, builder: Builder): void {
425425
// Find matching constructor by kind
426-
const constructorName = (data as TypedCell).kind.substring(type.name.length + 1); // Remove TypeName_ prefix
426+
const typeKind = (data as TypedCell).kind;
427+
if (!typeKind) {
428+
throw new TLBDataError('Data must by typed');
429+
}
427430

428-
const constructor = type.constructors.find((c) => c.name === constructorName);
431+
const constructorName = typeKind.substring(type.name.length + 1); // Remove TypeName_ prefix
432+
let constructor: TLBConstructor | undefined;
433+
if (constructorName) {
434+
constructor = type.constructors.find((c) => c.name === constructorName);
435+
} else if (type.constructors.length > 0) {
436+
constructor = type.constructors[0];
437+
}
429438
if (!constructor) {
430-
throw new TLBDataError(`Constructor ${constructorName} not found for type ${type.name}`);
439+
throw new TLBDataError(`Constructor not found for type ${typeKind}`);
431440
}
432441

433442
// Store tag if present

0 commit comments

Comments
 (0)