Motoko implementation of compute_neuron_staking_subaccount_bytes?

I am working on a Motoko implementation of the computeNeuronStakingSubaccount function the code for the rust version is here:

Rust has some handy tools, particularly the .to_be_bytes on the nonce - I am stuck on this, the rest of the function should be ok - but Is there a motoko version of .to_be_bytes ?

See if a number library i wrote can help

https://mops.one/xtended-numbers

There should be some encoding to bytes methods for numbers

1 Like

does it have big endian conversions?

Ya, there is msb/lsb variant for encoding

1 Like

Thanks @Gekctek for your response and pointing me to that package, I got it working, I’ll post the solution for others who may need to convert their nonces / numbers to big endian byte arrays.

The problem was that I needed to convert a nonce (which is just a Nat64 number) to a Blob / byte array in big endian format so I could hash it - I’m not a low level guy but I believe big endian is the arrangement of the bytes from highest to lowest. For example the number 7306897292049529674 would become a Nat8 (Blob) array of something like: [84, 94, 247, 19, 76, 96, 87, 92] - (this is just a visual example and not exact).

The Rust language (also used in ICP) has a handy tool that simply let’s you call .to_be_bytes on the nonce see: u64 - Rust

In Motoko, I have found two packages that let you do this, one is @Gekctek 's package
xtended-numbers, the Motoko code I got working for converting my nonce in this package looks something like:

import NatX "mo:xtended-numbers/NatX";
import Buffer "mo:base/Buffer;

....

let nonce: Nat64 = 7306897292049529674;
let buf = Buffer.Buffer<Nat8>(0);

NatX.encodeNat64(buffer, nonce, #msb)

// and then convert buffer:
Buffer.toArray(buffer);

....

The second package I found is: GitHub - aviate-labs/encoding.mo: Encoding Package for Motoko, the Motoko code for this one looks something like:

import Binary "mo:encoding/Binary"

....

let nonce: Nat64 = 7306897292049529674;

Binary.BigEndian.fromNat64(nonce)

Both of these packages gave me the same output on the nonce!

I opted for the second one because I already had it installed and prefer the simplicity. However, it looks like the xtended-numbers package has more useful tools that I may need in the future - I shall see…anyway hope this helps someone in the future avoid the long search I went through figuring this out :slight_smile:

2 Likes