Skip to content

Commit

Permalink
Merge pull request #28 from MystenLabs/mh--bcs-allow-asymetrical-tran…
Browse files Browse the repository at this point in the history
…sform

[bcs] allow type transforms to omit input or output transforms
  • Loading branch information
hayes-mysten authored Jan 27, 2025
2 parents aafc5f5 + 10e2724 commit a08b58e
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/slimy-lobsters-live.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@mysten/bcs': minor
---

Allow BcsType.transform to omit input or output transform
17 changes: 9 additions & 8 deletions packages/bcs/src/bcs-type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,24 +79,25 @@ export class BcsType<T, Input = T> {
return this.parse(fromBase64(b64));
}

transform<T2, Input2>({
transform<T2 = T, Input2 = Input>({
name,
input,
output,
validate,
}: {
input: (val: Input2) => Input;
output: (value: T) => T2;
input?: (val: Input2) => Input;
output?: (value: T) => T2;
} & BcsTypeOptions<T2, Input2>) {
return new BcsType<T2, Input2>({
name: name ?? this.name,
read: (reader) => output(this.read(reader)),
write: (value, writer) => this.#write(input(value), writer),
serializedSize: (value) => this.serializedSize(input(value)),
serialize: (value, options) => this.#serialize(input(value), options),
read: (reader) => (output ? output(this.read(reader)) : (this.read(reader) as never)),
write: (value, writer) => this.#write(input ? input(value) : (value as never), writer),
serializedSize: (value) => this.serializedSize(input ? input(value) : (value as never)),
serialize: (value, options) =>
this.#serialize(input ? input(value) : (value as never), options),
validate: (value) => {
validate?.(value);
this.validate(input(value));
this.validate(input ? input(value) : (value as never));
},
});
}
Expand Down
25 changes: 25 additions & 0 deletions packages/bcs/tests/builder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,31 @@ describe('bcs', () => {
Variant2: 'hello',
});
});

describe('transform', () => {
const stringU8 = bcs.u8().transform({
input: (val: string) => parseInt(val),
output: (val) => val.toString(),
});

testType('transform', stringU8, '1', '01', '1');

// Output only
const bigIntu64 = bcs.u64().transform({
output: (val) => BigInt(val),
});

testType('transform', bigIntu64, '1', '0100000000000000', 1n);
testType('transform', bigIntu64, 1, '0100000000000000', 1n);
testType('transform', bigIntu64, 1n, '0100000000000000', 1n);

// Input only
const hexU8 = bcs.u8().transform({
input: (val: string) => Number.parseInt(val, 16),
});

testType('transform', hexU8, 'ff', 'ff', 255);
});
});

function testType<T, Input>(
Expand Down

0 comments on commit a08b58e

Please sign in to comment.