Skip to content

Commit

Permalink
Add rotate key example (#213)
Browse files Browse the repository at this point in the history
* add rotate key example

* lint
  • Loading branch information
0xmaayan authored Dec 1, 2023
1 parent 0221032 commit b370f6d
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions examples/typescript/rotate_key.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/* eslint-disable no-console */

import { Account, AccountAddress, Aptos, AptosConfig, Network, NetworkToNetworkName } from "@aptos-labs/ts-sdk";

const WIDTH = 16;

// Setup the client
const APTOS_NETWORK: Network = NetworkToNetworkName[process.env.APTOS_NETWORK] || Network.DEVNET;
const config = new AptosConfig({ network: APTOS_NETWORK });
const aptos = new Aptos(config);

function truncate(address: AccountAddress): string {
return `${address.toString().substring(0, 6)}...${address
.toString()
.substring(address.toString().length - 4, address.toString().length)}`;
}

function formatAccountInfo(account: Account): string {
const vals: any[] = [
account.accountAddress,
Account.authKey({ publicKey: account.publicKey }),
account.privateKey,
account.publicKey,
];

return vals.map((v) => truncate(v).padEnd(WIDTH)).join(" ");
}

(async () => {
const alice = Account.generate();
const bob = Account.generate();

await aptos.fundAccount({ accountAddress: alice.accountAddress, amount: 1000000000 });
await aptos.fundAccount({ accountAddress: bob.accountAddress, amount: 1000000000 });

console.log(
`\n${"Account".padEnd(WIDTH)} ${"Address".padEnd(WIDTH)} ${"Auth Key".padEnd(WIDTH)} ${"Private Key".padEnd(
WIDTH,
)} ${"Public Key".padEnd(WIDTH)}`,
);
console.log("---------------------------------------------------------------------------------");
console.log(`${"alice".padEnd(WIDTH)} ${formatAccountInfo(alice)}`);
console.log(`${"bob".padEnd(WIDTH)} ${formatAccountInfo(bob)}`);
console.log("\n...rotating...".padStart(WIDTH));

// Rotate the key!
await aptos.rotateAuthKey({ fromAccount: alice, toNewPrivateKey: bob.privateKey });

const aliceNew = Account.fromPrivateKeyAndAddress({ privateKey: bob.privateKey, address: alice.accountAddress });

console.log(`\n${"alice".padEnd(WIDTH)} ${formatAccountInfo(aliceNew)}`);
console.log(`${"bob".padEnd(WIDTH)} ${formatAccountInfo(bob)}\n`);
})();

0 comments on commit b370f6d

Please sign in to comment.