import {
createWalletClient,
custom,
recoverPublicKey,
hashMessage,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { mainnet } from "viem/chains";
import { WalletStamper, EthereumWallet } from "@turnkey/wallet-stamper";
// Instantiate the WalletStamper with the EthereumWallet
const walletStamper = new WalletStamper(new EthereumWallet());
// Instantiate the TurnkeyClient with the WalletStamper
const client = new TurnkeyClient({ baseUrl: BASE_URL }, walletStamper);
// Call getWhoami to get the sub-org's organizationId and userId passing in the parent org id
// whoami { organizationId: string; organizationName: string; userId: string; username: string; }
const whoami = await client.getWhoami({
organizationId: process.env.ORGANIZATION_ID,
});
let subOrganizationId = whoami?.organizationId;
// User does not yet have a sub-organization, so we need to create one
if (!subOrganizationId) {
// We'll need to use the parent org's API keys to create the sub-org on behalf of the user
const { ApiKeyStamper } = await import("@turnkey/api-key-stamper");
// Instantiate the TurnkeyClient with the ApiKeyStamper
const parentOrgClient = new TurnkeyClient(
{ baseUrl: BASE_URL },
new ApiKeyStamper({
// In practice we'll want to ensure these keys do not get exposed to the client
apiPublicKey: process.env.API_PUBLIC_KEY ?? "",
apiPrivateKey: process.env.API_PRIVATE_KEY ?? "",
}),
);
const apiKeys = [
{
apiKeyName: "Wallet Auth - Embedded Wallet",
// The public key of the wallet that will be added as an API key and used to stamp future requests
publicKey,
// We set the curve type to 'API_KEY_CURVE_ED25519' for solana wallets
// If using an Ethereum wallet, set the curve type to 'API_KEY_CURVE_SECP256K1'
curveType,
},
];
const subOrg = await parentOrgClient.createSubOrganization({
organizationId: process.env.ORGANIZATION_ID,
subOrganizationName: `Sub Org - ${publicKey}`,
rootUsers: [
{
// Replace with user provided values
userName: "New User",
userEmail: "wallet@domain.com",
apiKeys,
},
],
rootQuorumThreshold: 1,
wallet: {
walletName: "Default Wallet",
accounts: DEFAULT_ETHEREUM_ACCOUNTS,
},
});
subOrganizationId = subOrg.subOrganizationId;
}
// Get the wallets for this sub-organization
const wallets = await client.getWallets({
organizationId: subOrganizationId,
});