[chore] testGanache and testWallet

@types
neeboo 6 years ago
parent 2a81da71f6
commit 05cb4df930
  1. 41
      examples/testGanache.js
  2. 2
      examples/testWallet.js
  3. 3
      packages/harmony-account/src/account.ts
  4. 48
      packages/harmony-account/src/wallet.ts
  5. 4
      packages/harmony-core/src/blockchain.ts
  6. 11
      packages/harmony-utils/src/transformers.ts

@ -17,9 +17,17 @@ console.log('-------------------------------------');
// here 1 is used, which means we use ethereum-node.
const harmony = new Harmony(url, 1);
async function createAndEncrypt(words, index, password) {
for (let i = 0; i < index; i++) {
const newAcc = harmony.wallet.addByMnemonic(words, i);
await harmony.wallet.encryptAccount(newAcc.address, password);
}
}
const acc = harmony.wallet.addByMnemonic(mne, 0);
console.log('--- hint: we use this private key to as default account to test');
console.log('--- hint: we use this private key to test with ganache');
console.log('-------------------------------------');
console.log(`${acc.privateKey}`);
console.log('-------------------------------------');
@ -32,6 +40,10 @@ const server = ganache.server({
// now it is async time
async function main() {
const password = '1234567890123';
await createAndEncrypt(mne, 10, password);
const latestBalance = await harmony.blockchain.getBalance({
address: acc.address,
blockNumber: 'latest',
@ -42,7 +54,7 @@ async function main() {
console.log('-------------------------------------');
const nonce = await harmony.blockchain.getTransactionCount({
address: acc.address,
address: harmony.wallet.signer.address,
blockNumber: 'latest',
});
console.log('--- testing: hmy_getTransactionCount');
@ -50,7 +62,7 @@ async function main() {
console.log({ nonce: Number.parseInt(harmony.utils.hexToNumber(nonce), 10) });
console.log('-------------------------------------');
const balanceOfAccount = await acc.getBalance();
const balanceOfAccount = await harmony.wallet.signer.getBalance();
console.log('--- testing: Account.getBalance');
console.log('-------------------------------------');
console.log(balanceOfAccount);
@ -67,7 +79,7 @@ async function main() {
// now we sign and send a transaction
const signed = await acc.signTransaction(txn, true);
const signed = await harmony.wallet.signTransaction(txn, undefined, password);
console.log('--- testing: Account.signTransaction');
console.log('-------------------------------------');
@ -149,9 +161,28 @@ async function main() {
const sameTransaction2 = await harmony.blockchain.getTransactionByHash({
txnHash: transaction.hash,
});
const { gas, gasPrice, value } = sameTransaction2;
const valueBN = harmony.utils.hexToBN(value);
const gasBN = harmony.utils.hexToBN(gas);
const gasPriceBN = harmony.utils.hexToBN(gasPrice);
const actualCost = new harmony.utils.Unit(gasBN.mul(gasPriceBN).add(valueBN))
.asWei()
.toWei();
console.log('--- testing: hmy_getTransactionByHash');
console.log('-------------------------------------');
console.log({ gas: sameTransaction2.gas });
console.log({
actualCost: actualCost.toString(),
gas: harmony.utils.hexToNumber(gas),
gasPrice: gasPriceBN.toString(),
value: valueBN.toString(),
comment: 'actualCost= gas * gasPrice + value',
});
console.log('-------------------------------------');
const getBalanceAgainObject = await harmony.wallet.signer.getBalance();
console.log('--- testing: get balance again');
console.log('-------------------------------------');
console.log(getBalanceAgainObject);
console.log('-------------------------------------');
}

@ -24,6 +24,8 @@ async function main() {
console.log('---hint:we added 10 accounts for you');
console.log(harmony.wallet.accounts);
console.log(harmony.wallet.signer);
}
main();

@ -42,6 +42,7 @@ class Account {
nonce?: number = 0;
shards: Shards = new Map().set('default', '');
messenger?: Messenger;
encrypted: boolean = false;
/**
* @function checksumAddress checsumAddress getter
@ -72,6 +73,7 @@ class Account {
if (this.privateKey && isPrivateKey(this.privateKey)) {
const file = await encrypt(this.privateKey, password, options);
this.privateKey = file;
this.encrypted = true;
return file;
} else {
throw new Error('Encryption failed because PrivateKey is not correct');
@ -187,6 +189,7 @@ class Account {
this.publicKey = getPubkeyFromPrivateKey(this.privateKey);
this.address = getAddressFromPrivateKey(this.privateKey);
this.shards = new Map().set('default', '');
this.encrypted = false;
return this;
}

@ -2,6 +2,7 @@ import { bip39, hdkey, EncryptOptions } from '@harmony/crypto';
import { Messenger } from '@harmony/network';
import { isPrivateKey, isAddress } from '@harmony/utils';
import { Account } from './account';
import { Transaction } from '@harmony/transaction';
class Wallet {
messenger?: Messenger;
@ -169,6 +170,7 @@ class Wallet {
foundAcc.privateKey &&
isPrivateKey(foundAcc.privateKey)
) {
foundAcc.encrypted = false;
return foundAcc;
} else {
throw new Error('decrypt account failed');
@ -202,7 +204,7 @@ class Wallet {
}
}
setMessenger(messenger: Messenger) {
setMessenger(messenger: Messenger): void {
this.messenger = messenger;
}
@ -212,6 +214,50 @@ class Wallet {
}
this.defaultSigner = address;
}
async signTransaction(
transaction: Transaction,
account?: Account,
password?: string,
): Promise<Transaction> {
const toSignWith = account || this.signer;
if (!toSignWith) {
throw new Error('no signer found or did not provide correct account');
}
if (
toSignWith instanceof Account &&
toSignWith.encrypted &&
toSignWith.address
) {
if (!password) {
throw new Error('must provide password to further execution');
}
try {
const decrypted = await this.decryptAccount(
toSignWith.address,
password,
);
const signed = await decrypted.signTransaction(transaction, true);
await this.encryptAccount(toSignWith.address, password);
return signed;
} catch (error) {
throw error;
}
} else if (
toSignWith instanceof Account &&
!toSignWith.encrypted &&
toSignWith.address
) {
try {
const signed = await toSignWith.signTransaction(transaction, true);
return signed;
} catch (error) {
throw error;
}
} else {
throw new Error('sign transaction failed');
}
}
/**
* @function isValidMnemonic
* @memberof Wallet

@ -268,7 +268,7 @@ class Blockchain extends HarmonyCore {
}
async sendTransaction(transaction: Transaction) {
if (!transaction.isSigned || !transaction) {
if (!transaction.isSigned() || !transaction) {
throw new Error('transaction is not signed or not exist');
}
const result = await this.messenger.send(
@ -280,7 +280,7 @@ class Blockchain extends HarmonyCore {
}
async sendRawTransaction(transaction: Transaction) {
if (!transaction.isSigned || !transaction) {
if (!transaction.isSigned() || !transaction) {
throw new Error('transaction is not signed or not exist');
}
const [txn, result] = await transaction.sendTransaction();

@ -100,6 +100,17 @@ export const hexToNumber = (hex: string): string => {
}
};
export const hexToBN = (hex: string): BN => {
if (isHex(hex) && hex[0] !== '-') {
return new BN(strip0x(hex), 'hex');
} else if (isHex(hex) && hex[0] === '-') {
const result: BN = new BN(hex.substring(3), 16);
return result.mul(new BN(-1));
} else {
throw new Error(`${hex} is not hex number`);
}
};
export const toWei = (input: BN | string, unit: Units): BN => {
try {
let inputStr = numToStr(input);

Loading…
Cancel
Save