Programmatically staking neurons

Im trying to programmatically create neurons as Im trying to better understand how the NNS works.

My Current Issue is below:

Account does not have enough funds to stake a neuron. Please make sure that account has at least 100000000 e8s (was 0 e8s)

Ive been transferring small amounts to the Minting Account and Im using this code here: nns-dapp/createNeuron.ts at 55a89a9b5d5d4241277822197efc62f3d3e8d6ce · dfinity/nns-dapp · GitHub

I can see my transactions on chain:

With ICP going to the Minting Account

Snippet of my code:

  var principal = ledger.identity.getPrincipal();
  var aid = principalToAccountIdentifier(principal.toText(), 0);
  console.log("My AID:", aid)
  console.log("My current tokens:", await{ account: toAccountIdVec(aid) }))

  var nonceBytes = crypto.randomBytes(8);
  var nonce = uint8ArrayToBigInt(nonceBytes);
  const toSubAccount = buildSubAccount(nonceBytes, principal);

  const governance_aid = principalToAccountIdentifier(

  console.log("governance_aid aid", governance_aid)
  console.log("To balance:", await{ account: toAccountIdVec(governance_aid) }))

    'to': toAccountIdVec(governance_aid),
    'fee': { e8s: 0 },
    'memo': nonce,
    'from_subaccount': [],
    'created_at_time': [],
    'amount': { 'e8s': 100000 },

  let createResult = await{
    controller: [principal],
    memo: nonce

SubAccount creation

function buildSubAccount(nonce, principal) {
  const padding = asciiStringToByteArray("neuron-stake");
  const shaObj = sha256.create();
  shaObj.update([0x0c, ...padding, ...principal.toUint8Array(), ...nonce]);
  return new Uint8Array(shaObj.array());

Should the balance of the Governance account I transfer to always be 0? Im open to share whatever else would help. Ive been using this code to transfer ICP between my Stoic wallet and the App as a test and everything worked fine.

I believe its my SubAccount or Memo field is incorrect, but I checked the repo

Thank you,

Resovled: principalToAccountIdentifier was not doing sub accounts correctly.

1 Like

as an alternative this is also discussed here