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 ledger.actor.account_balance({ account: toAccountIdVec(aid) }))

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

  const governance_aid = principalToAccountIdentifier(
    "rrkah-fqaaa-aaaaa-aaaaq-cai",
    toSubAccount
  );

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

  console.log(await ledger.actor.transfer({
    'to': toAccountIdVec(governance_aid),
    'fee': { e8s: 0 },
    'memo': nonce,
    'from_subaccount': [],
    'created_at_time': [],
    'amount': { 'e8s': 100000 },
  }))

  let createResult = await nns.actor.claim_or_refresh_neuron_from_account({
    controller: [principal],
    memo: nonce
  })
  console.log(JSON.stringify(createResult))

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,
Rick

Resovled: principalToAccountIdentifier was not doing sub accounts correctly.

1 Like

as an alternative this is also discussed here