Skip to content

TS-SDK: add deriveDynamicFieldId() #7496

@Thoralf-M

Description

@Thoralf-M

Description

Add a function like this:

import { type BcsType } from '@iota/bcs';
import { bcs } from '@iota/iota-sdk/bcs';
import { blake2b } from '@noble/hashes/blake2';
import { bytesToHex } from '@noble/hashes/utils';

export function deriveDynamicFieldId<T>(
    parentObjectId: string,
    tag: string,
    valueType: BcsType<T>,
    value: T,
): string {
    const typeTagBytes = bcs.TypeTag.serialize(tag).toBytes();
    const valueBcsBytes = valueType.serialize(value).toBytes();

    const valueBcsBytesLen = new Uint8Array(8);
    const view = new DataView(valueBcsBytesLen.buffer);
    view.setUint32(0, valueBcsBytes.length, true); // little-endian

    const input = new Uint8Array([
        // HashingIntentScope::ChildObjectId
        0xf0,
        ...bcs.Address.serialize(parentObjectId).toBytes(),
        ...valueBcsBytesLen,
        ...valueBcsBytes,
        ...typeTagBytes,
    ]);

    const hash = blake2b(input, { dkLen: 32 });

    return `0x${bytesToHex(hash)}`;
}

inspired by https://github.com/iotaledger/iota-names/blob/0ee79191cd2527d9b0b424b05443467b2fc30a0c/dapp/src/lib/auction/utils.ts#L18

Motivation

Useful function when working with dynamic fields

Are you planning to do it yourself in a pull request?

No.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesttoolingIssues related to the Tooling teamts-sdkIssues related to the TS SDK

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions