From 7ae44dc120a88b9c91a8366a3f665be9f4d5ac18 Mon Sep 17 00:00:00 2001 From: Gregor Date: Thu, 18 Jan 2024 11:22:49 +0100 Subject: [PATCH] simplify, prettify --- src/lib/provable-types/packed.ts | 47 ++++++++++++++++---------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/src/lib/provable-types/packed.ts b/src/lib/provable-types/packed.ts index 52d52604af..2fcb67280d 100644 --- a/src/lib/provable-types/packed.ts +++ b/src/lib/provable-types/packed.ts @@ -49,17 +49,40 @@ class Packed { packed: Field[]; value: Unconstrained; + /** + * Create a packed representation of `type`. You can then use `PackedType.pack(x)` to pack a value. + */ + static create(type: ProvableExtended): typeof Packed { + // compute size of packed representation + let input = type.toInput(type.empty()); + let packedSize = countFields(input); + + return class Packed_ extends Packed { + static _innerProvable = type; + static _provable = provableFromClass(Packed_, { + packed: fields(packedSize), + value: Unconstrained.provable, + }) as ProvableHashable>; + }; + } + constructor(packed: Field[], value: Unconstrained) { this.packed = packed; this.value = value; } + /** + * Pack a value. + */ static pack(x: T): Packed { let input = this.innerProvable.toInput(x); let packed = packToFields(input); return new this(packed, Unconstrained.from(x)); } + /** + * Unpack a value. + */ unpack(): T { let value = Provable.witness(this.Constructor.innerProvable, () => this.value.get() @@ -79,22 +102,7 @@ class Packed { return this.packed; } - hash() { - return Poseidon.hash(this.packed); - } - - static createProvable( - type: ProvableExtended - ): ProvableHashable> { - let input = type.toInput(type.empty()); - let packedSize = countFields(input); - - return provableFromClass(this, { - packed: fields(packedSize), - value: Unconstrained.provable, - }) as ProvableHashable>; - } - + // dynamic subclassing infra static _provable: ProvableHashable> | undefined; static _innerProvable: ProvableExtended | undefined; @@ -110,13 +118,6 @@ class Packed { assert(this._innerProvable !== undefined, 'Packed not initialized'); return this._innerProvable; } - - static create(type: ProvableExtended): typeof Packed { - return class Packed_ extends Packed { - static _provable = Packed_.createProvable(type); - static _innerProvable = type; - }; - } } type ProvableHashable = Provable & { toInput: (x: T) => HashInput };