Unable to create AptosAccount using Typescript (INVALID_AUTH_KEY)

753 Views Asked by At

I am trying to create a token collection using the Aptos Typescript SDK.

const account = new AptosAccount(Uint8Array.from(Buffer.from(PRIVATE_KEY)), ACCOUNT_ADDR);

await tokenClient.createCollection(
        account,
        "A test collection 1",
        "A test collection",
        "https://google.com",
    );

But I get the following error:

ApiError2: {"message":"Invalid transaction: Type: Validation Code: INVALID_AUTH_KEY","error_code":"vm_error","vm_error_code":2}

What am I doing wrong?

Tried replicating the Aptos official example but instead of creating a new account, I want to use an existing funded account.

4

There are 4 best solutions below

0
On

Let's say you have a private key as a hex string, you can do it like this:

import { AptosAccount, HexString } from "aptos";

const privateKeyHex = "0xdcaf65ead38f7cf0eb4f81961f8fc7f9b7f1e2f45e2d4a6da0dbef85f46f6057";
const privateKeyBytes = HexString.ensure(privateKeyHex).toUint8Array();
const account = new AptosAccount(privateKeyBytes);
0
On

I had the same issue. I Finally found out that the problem is the address that is not match with private_key, and the private_key was not in ed25519 format. Your keys must be generated with ed25519 curve, then you should create your address from that key. I used bip_utils library to create bip_private_key (with Near protocol which is also ed25519)then:

private_key = ed25519.PrivateKey.from_hex(bip_private_key)
0
On

I just want to add details to Daniel's answer about how you can get private key after creating wallet and then use it:

import { AptosAccount } from "aptos";

const wallet = new AptosAccount();
const privateKeyHex = wallet.toPrivateKeyObject().privateKeyHex;

// ...

const privateKeyBytes = HexString.ensure(privateKeyHex).toUint8Array();
const account = new AptosAccount(privateKeyBytes);
0
On

Here is how you do it with TS SDK v2:

// Create a private key instance for the Ed25519 scheme.
const privateKey = new Ed25519PrivateKey("0xdcaf65ead38f7cf0eb4f81961f8fc7f9b7f1e2f45e2d4a6da0dbef85f46f6057");
// Or for the Secp256k1 scheme
const privateKey = new Secp256k1PrivateKey("0xdcaf65ead38f7cf0eb4f81961f8fc7f9b7f1e2f45e2d4a6da0dbef85f46f6057");

// Create the account. Note, this only works for accounts that haven't had their authentication key rotated.
const account = await Account.fromPrivateKey({ privateKey });