forked from tkhq/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreateNewEthereumPrivateKey.ts
80 lines (70 loc) · 2.34 KB
/
createNewEthereumPrivateKey.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { TurnkeyClient, createActivityPoller } from "@turnkey/http";
import { ApiKeyStamper } from "@turnkey/api-key-stamper";
import { TurnkeyActivityError } from "@turnkey/ethers";
import * as crypto from "crypto";
export async function createNewEthereumPrivateKey() {
console.log("creating a new Ethereum private key on Turnkey...\n");
const privateKeyName = `ETH Key ${crypto.randomBytes(2).toString("hex")}`;
try {
const turnkeyClient = new TurnkeyClient(
{ baseUrl: process.env.BASE_URL! },
new ApiKeyStamper({
apiPublicKey: process.env.API_PUBLIC_KEY!,
apiPrivateKey: process.env.API_PRIVATE_KEY!,
})
);
const activityPoller = createActivityPoller({
client: turnkeyClient,
requestFn: turnkeyClient.createPrivateKeys,
});
const completedActivity = await activityPoller({
type: "ACTIVITY_TYPE_CREATE_PRIVATE_KEYS_V2",
timestampMs: String(Date.now()),
organizationId: process.env.ORGANIZATION_ID!,
parameters: {
privateKeys: [
{
privateKeyName,
curve: "CURVE_SECP256K1",
addressFormats: ["ADDRESS_FORMAT_ETHEREUM"],
privateKeyTags: [],
},
],
},
});
const privateKey = refineNonNull(
completedActivity.result.createPrivateKeysResultV2?.privateKeys?.[0]
);
const privateKeyId = refineNonNull(privateKey.privateKeyId);
const address = refineNonNull(privateKey.addresses?.[0]?.address);
// Success!
console.log(
[
`New Ethereum private key created!`,
`- Name: ${privateKeyName}`,
`- Private key ID: ${privateKeyId}`,
`- Address: ${address}`,
``,
"Now you can take the private key ID, put it in `.env.local`, then re-run the script.",
].join("\n")
);
} catch (error) {
// If needed, you can read from `TurnkeyActivityError` to find out why the activity didn't succeed
if (error instanceof TurnkeyActivityError) {
throw error;
}
throw new TurnkeyActivityError({
message: "Failed to create a new Ethereum private key",
cause: error as Error,
});
}
}
export function refineNonNull<T>(
input: T | null | undefined,
errorMessage?: string
): T {
if (input == null) {
throw new Error(errorMessage ?? `Unexpected ${JSON.stringify(input)}`);
}
return input;
}