Skip to content

Commit

Permalink
chore: getting commands working
Browse files Browse the repository at this point in the history
  • Loading branch information
dafuga committed Oct 20, 2023
1 parent 9a3c16e commit b6fd813
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 38 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
},
"dependencies": {
"@wharfkit/antelope": "^0.9.1",
"@wharfkit/common": "^1.1.0",
"@wharfkit/contract": "^0.4.3",
"commander": "^11.0.0",
"prettier": "^2.2.1",
Expand Down
71 changes: 40 additions & 31 deletions src/commands/account/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,28 @@
import { Bytes, KeyType, PrivateKey } from "@wharfkit/antelope";
import { PrivateKey, KeyType } from '@wharfkit/antelope';
import { Chains, type ChainIndices } from '@wharfkit/common';

export async function createAccountFromCommand(options: any) {

interface CommandOptions {
publicKey?: string;
accountName?: string;
chain?: ChainIndices;
}

export async function createAccountFromCommand(options: CommandOptions) {
let publicKey;
let privateKey;

// Generate a random account name if not provided
const accountName = options.accountName || generateRandomAccountName();

if (!accountName.endsWith('.gm')) {
console.error('Account name must end with ".gm"');
return;
}

// Default to "jungle4" if no chain option is provided
const chainUrl = `http://${options.chain?.toLowerCase() || "jungle4"}.greymass.com`;

try {
// Check if a public key is provided in the options
if (options.publicKey) {
Expand All @@ -12,58 +31,48 @@ export async function createAccountFromCommand(options: any) {
// Generate a new private key if none is provided
privateKey = PrivateKey.generate(KeyType.K1);
// Derive the corresponding public key
publicKey = privateKey.toPublicKey().toString();
publicKey = String(privateKey.toPublic());
}

// Prepare the data for the POST request to Sextant
// Prepare the data for the POST request
const data = {
account: 'eosio',
permission: 'active',
public_key: publicKey
accountName: accountName,
activeKey: publicKey,
ownerKey: publicKey,
network: (options.chain && Chains[options.chain]) || "73e4385a2708e6d7048834fbc1079f2fabb17b3c125b146af438971e90716c4d"
};

// Convert the data object to a Buffer
const requestBodyInBytes = Buffer.from(JSON.stringify(data), 'utf8');

// Generate the signature for the request body
const signature = generateSignatureForBody(requestBodyInBytes);

// Make the POST request to Sextant to create the account
const response = await fetch(`${SEXTANT_URL}/v1/chain/account`, {
// Make the POST request to create the account
const response = await fetch(`${chainUrl}/account/create`, {
method: 'POST',
headers: {
'X-Request-Sig': signature,
'Content-Type': 'application/json',
},
body: requestBodyInBytes.toString('utf8'),
body: JSON.stringify(data),
});

const responseData = await response.json();

if (responseData.success) {
if (response.status === 201) {
console.log('Account created successfully!');
console.log(`Account Name: ${accountName}`)
if (privateKey) { // Only print the private key if it was generated
console.log(`Private Key: ${privateKey.toString()}`);
}
console.log(`Public Key: ${publicKey}`);
} else {
const responseData = await response.json();
console.error('Failed to create account:', responseData.message || responseData.reason);
}
} catch (error: unknown) {
console.error('Error during account creation:', (error as { message: string }).message);
}
}

function generateSignatureForBody(bodyBytes) {
if (!SEXTANT_KEY_PADDING) {
throw Error('Missing Sextant API key.');
function generateRandomAccountName(): string {
// Generate a random 12-character account name using the allowed characters for EOSIO
const characters = 'abcdefghijklmnopqrstuvwxyz12345';
let result = '';
for (let i = 0; i < 9; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}

const deobfuscated = SEXTANT_KEY_PADDING.split(', ')
.slice(4)
.map((b, i) => b ^ (42 * i));

const privateKey = new PrivateKey(KeyType.K1, Bytes.from(deobfuscated));

return privateKey.signMessage(bodyBytes).toString();
return `${result}.gm`;
}
14 changes: 8 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { Command } from 'commander';

import { version } from '../package.json';
import { generateContractFromCommand } from './commands/contract';
import { generateKeysFromCommand } from './commands/keys';
import { createAccountFromCommand } from './commands/account';
import { generateKeysFromCommand } from './commands/keys/index';
import { createAccountFromCommand } from './commands/account/index';

const program = new Command();

Expand All @@ -14,16 +14,18 @@ program

// 1. Command to generate keys
program
.command('generate keys')
.command('generate-keys')
.description('Generate a new set of public and private keys')
.action(createAccountFromCommand);
.action(generateKeysFromCommand);

// 2. Command to create an account
program
.command('create account')
.command('make-account')
.description('Create a new account with an optional public key')
.option('--chain <chain>', 'The chain to create the account on. Defaults to "jungle4".')
.option('--account-name <accountName>', 'Account name for the new account. Must end with ".gm". If not provided, a random name is generated.')
.option('--public-key <publicKey>', 'Public key for the new account. If not provided, keys are generated.')
.action(generateKeysFromCommand);
.action(createAccountFromCommand);

// 3. Existing command to generate a contract
program
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@

"@wharfkit/common@^1.1.0":
version "1.1.0"
resolved "https://registry.npmjs.org/@wharfkit/common/-/common-1.1.0.tgz"
resolved "https://registry.yarnpkg.com/@wharfkit/common/-/common-1.1.0.tgz#1ee9dd1ba9e202002fadd20593f5f42a3e67c827"
integrity sha512-A1Ta8zrEXkuEQcEiEexG0BVrYOxqm75qbLYU9tGNhyw4z/vQiF6rzmCOqhmWGg6nE2J2GYPvrPZPZzDmRGtG+w==
dependencies:
tslib "^2.1.0"
Expand Down

0 comments on commit b6fd813

Please sign in to comment.