Create ICP Account from within a smart contract for each user

First have a way to create new users, e.g. with:

thread_local! {
    static NEXT_ID: std::cell::RefCell<u64> = std::cell::RefCell::new(0);
}

fn next_user_id() -> u64 {
    NEXT_ID.with(|cell| {
        let next_id = *cell.borrow();
        cell.replace(next_id+1);
        next_id
    })
}

then you can create the account of a user like this

fn id_to_account(id: u64) -> AccountIdentifier {
    let mut subaccount = [0u8;32];
    subaccount.split_at_mut(8).0.copy_from_slice(id.to_le_bytes().as_slice());
    let subaccount = Subaccount(subaccount);
    let account_id = AccountIdentifier::new(&caller(), &subaccount);
    account_id
}

I didn’t test this code so take it as an example to adapt :slight_smile: .

3 Likes