0

Client App creates an Input as follows using polkadotJS to submit to Substrate Module as follows

import { ApiPromise, WsProvider } from '@polkadot/api';
const { Keyring } = require('@polkadot/keyring');
import { u8aToHex } from '@polkadot/util';


async function objectToByteArray() {
    let attributes = {
        "current_fraction": 1,
    };
    const jsonString = JSON.stringify(attributes);
    const uint8Array = Uint8Array.from(Buffer.from(jsonString));
    console.log('Uint8Array', uint8Array);
    /*
      [
        123,  34,  99, 117, 114, 114,
        101, 110, 116,  95, 102, 114,
        97,  99, 116, 105, 111, 110,
        34,  58,  49, 125
        ]
    */
    const byteArray = u8aToHex(uint8Array);
    console.log('Byte array', byteArray);
    /*
    Byte array 0x7b2263757272656e745f6672616374696f6e223a317d
    */
}

objectToByteArray();

In Substrate Module Inside a function it greeted by the following function the bytearray will accepts by the value parameter in following function


#[pallet::weight(T::WeightInfo::set_attribute())]
pub fn set_attribute(
    origin: OriginFor<T>,
    collection: T::CollectionId,
    maybe_item: Option<T::ItemId>,
    key: BoundedVec<u8, T::KeyLimit>,
    value: BoundedVec<u8, T::ValueLimit>,
) -> DispatchResult {
    let maybe_check_owner = T::ForceOrigin::try_origin(origin)
    // Code here
    Ok(())
}

I need to reconstruct the original object within pallet and I tried the following Approach

// Mapping Object declared on Substrate side

#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, Default, TypeInfo, MaxEncodedLen)]
pub struct SomeName {
    pub current_fraction: u32,
}
let val = SomeName::decode(&mut &value[..]).map_err(|_| Error::<T, I>::Error)?;

Unfortunately the reconstructioned objects value for curent_fraction shows as 1969431163 instead of 1

How to fix this issue?

1 Answer 1

1

JS encode:

const registry = new TypeRegistry();
const someNameInstance = registry.createType('{"current_fraction":"u32"}', { current_fraction: 123 });
const encoded = someNameInstance.toU8a();

console.log('Encoded:', encoded);
// Encoded: Uint8Array(4) [ 123, 0, 0, 0 ]

Rust decode:

#[derive(Debug, Decode)]
pub struct SomeName {
    pub current_fraction: u32,
}

println!("{:?}", SomeName::decode(&mut [123, 0, 0, 0].as_slice()));
// Ok(SomeName { current_fraction: 123 })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.