encode method
Step 1: Encode the blob and compute metadata.
If pre-computed metadata was provided, this is a no-op. If an encoder is available, it computes the metadata. In direct mode with a WalrusBlobEncoder, also produces encoded slivers for distribution to storage nodes.
Implementation
Future<void> encode() async {
if (_step != _FlowStep.initial) {
throw StateError('encode() already called');
}
if (_precomputedMetadata != null) {
_metadata = _precomputedMetadata;
} else if (_relayClient != null) {
// Relay mode: use computeMetadata() which generates a random nonce
// and SHA-256 blobDigest. The relay verifies the auth payload in
// the register transaction against these values.
//
// Mirrors TS SDK's writeBlobFlow:
// const metadata = this.#uploadRelayClient
// ? await this.computeBlobMetadata({ bytes: blob })
// : await this.encodeBlob(blob);
final walrusEncoder = _encoder is WalrusBlobEncoder
? _encoder
: WalrusBlobEncoder();
int effectiveShards = _committee?.numShards ?? _numShards ?? 0;
if (effectiveShards == 0 && _stateReader != null) {
final state = await _stateReader.systemState();
effectiveShards = state.nShards;
}
if (effectiveShards == 0) effectiveShards = 1000;
_metadata = await walrusEncoder.computeMetadata(_blob, effectiveShards);
} else if (_encoder != null) {
// Direct mode: if encoder is WalrusBlobEncoder, do full encode
// and produce slivers for storage node distribution.
final effectiveShards = _committee?.numShards ?? _numShards ?? 1000;
if (_encoder is WalrusBlobEncoder) {
final walrusEncoder = _encoder;
final encoded = walrusEncoder.encodeBlob(_blob, effectiveShards);
_encodedBlob = encoded;
_metadata = await walrusEncoder.computeMetadata(_blob, effectiveShards);
} else {
_metadata = await _encoder.computeMetadata(_blob, effectiveShards);
}
} else if (_directClient != null && _committee != null) {
// Direct mode with default encoder.
final walrusEncoder = WalrusBlobEncoder();
final encoded = walrusEncoder.encodeBlob(_blob, _committee.numShards);
_encodedBlob = encoded;
_metadata = await walrusEncoder.computeMetadata(
_blob,
_committee.numShards,
);
} else {
throw StateError(
'No encoder, relay client, or pre-computed metadata available.',
);
}
_step = _FlowStep.encoded;
}