Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import { KeyringPair } from "@polkadot/keyring/types";
import { Address, ContractInfo, Balance, Hash } from "@polkadot/types/interfaces";
import BN from "bn.js";
import { ALICE, BOB, CREATION_FEE, WSURL } from "./consts";
import {
callContract,
instantiate,
getContractStorage,
putCode
} from "./utils";
// This is a test account that is going to be created and funded each test.
const keyring = testKeyring({ type: "sr25519" });
const bobPair = keyring.getPair(BOB);
const randomSeed = randomAsU8a(32);
let testAccount: KeyringPair;
let api: ApiPromise;
beforeAll((): void => {
jest.setTimeout(30000);
});
beforeEach(
async (done): Promise<() => void> => {
api = await ApiPromise.create({ provider: new WsProvider(WSURL) });
testAccount = keyring.addFromSeed(randomSeed);
return api.tx.balances
.transfer(testAccount.address, CREATION_FEE.muln(3))
.signAndSend(bobPair, (result: SubmittableResult): void => {
if (
async function main () {
// Create account seed for Alice as fallback if generated mnemonic not valid
const seedAlice = 'Alice'.padEnd(32, ' ');
// Generate new public/secret keypair for Alice from the supplied seed
const { secretKey, publicKey } = naclKeypairFromSeed(stringToU8a(seedAlice));
// Encrypt message. Create Uint8Array's filled with random bytes of specified length
const secret = randomAsU8a(32);
const messagePreEncryption = stringToU8a('please send me DOTs');
const noncePreEncryption = randomAsU8a(24);
const { encrypted } = naclEncrypt(messagePreEncryption, secret, noncePreEncryption);
// Sign the message with a valid signature
const messageSignature = naclSign(encrypted, secretKey);
console.log(`Message signature: ${u8aToHex(messageSignature)}`);
// Validate that the message was correctly signed
const isValidSignature = naclVerify(encrypted, messageSignature, publicKey);
console.log(`Was the message correctly signed? ${isValidSignature}`);
}
// Create the API and wait until ready
const api = await ApiPromise.create();
// Create an instance of our testing keyring
// If you're using ES6 module imports instead of require, just change this line to:
// const keyring = testKeyring();
const keyring = testKeyring.default();
// Get the nonce for the admin key
const nonce = await api.query.system.accountNonce(ALICE);
// Find the actual keypair in the keyring
const alicePair = keyring.getPair(ALICE);
// Create a new random recipient
const recipient = keyring.addFromSeed(randomAsU8a(32)).address;
console.log('Sending', AMOUNT, 'from', alicePair.address, 'to', recipient, 'with nonce', nonce.toString());
// Do the transfer and track the actual status
api.tx.balances
.transfer(recipient, AMOUNT)
.signAndSend(alicePair, { nonce }, ({ events = [], status }) => {
console.log('Transaction status:', status.type);
if (status.isFinalized) {
console.log('Completed at block hash', status.asFinalized.toHex());
console.log('Events:');
events.forEach(({ phase, event: { data, method, section } }) => {
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
});
// Create mnemonic string for Alice using BIP39
const mnemonicAlice = mnemonicGenerate();
console.log(`Generated mnemonic: ${mnemonicAlice}`);
// Validate the mnemic string that was generated
const isValidMnemonic = mnemonicValidate(mnemonicAlice);
console.log(`isValidMnemonic: ${isValidMnemonic}`);
// Create valid seed from mnemonic as u8a and convert it to a string
// FIXME - Replace with mnemonicToSeed once exposed
const seedAlice = mnemonicToSeed(mnemonicAlice);
// Generate new public/secret keypair for Alice from the supplied seed
const { secretKey, publicKey } = naclKeypairFromSeed(seedAlice);
// Encrypt, Sign and Validate the message. See Example 'Sign & Verify Message'
}
async function main () {
// Create account seed for Alice as fallback if generated mnemonic not valid
const seedAlice = 'Alice'.padEnd(32, ' ');
// Generate new public/secret keypair for Alice from the supplied seed
const { secretKey, publicKey } = naclKeypairFromSeed(stringToU8a(seedAlice));
// Encrypt message. Create Uint8Array's filled with random bytes of specified length
const secret = randomAsU8a(32);
const messagePreEncryption = stringToU8a('please send me DOTs');
const noncePreEncryption = randomAsU8a(24);
const { encrypted } = naclEncrypt(messagePreEncryption, secret, noncePreEncryption);
// Sign the message with a valid signature
const messageSignature = naclSign(encrypted, secretKey);
console.log(`Message signature: ${u8aToHex(messageSignature)}`);
// Validate that the message was correctly signed
const isValidSignature = naclVerify(encrypted, messageSignature, publicKey);
async function main () {
// Create mnemonic string for Alice using BIP39
const mnemonicAlice = mnemonicGenerate();
console.log(`Generated mnemonic: ${mnemonicAlice}`);
// Validate the mnemic string that was generated
const isValidMnemonic = mnemonicValidate(mnemonicAlice);
console.log(`isValidMnemonic: ${isValidMnemonic}`);
// Create valid seed from mnemonic as u8a and convert it to a string
// FIXME - Replace with mnemonicToSeed once exposed
const seedAlice = mnemonicToSeed(mnemonicAlice);
// Generate new public/secret keypair for Alice from the supplied seed
const { secretKey, publicKey } = naclKeypairFromSeed(seedAlice);
// Encrypt, Sign and Validate the message. See Example 'Sign & Verify Message'
}
private seedValidate ({ suri, type }: RequestSeedValidate): ResponseSeedValidate {
const { phrase } = keyExtractSuri(suri);
if (isHex(phrase)) {
assert(isHex(phrase, 256), 'Hex seed needs to be 256-bits');
} else {
// sadly isHex detects as string, so we need a cast here
assert(SEED_LENGTHS.includes((phrase as string).split(' ').length), `Mnemonic needs to contain ${SEED_LENGTHS.join(', ')} words`);
assert(mnemonicValidate(phrase), 'Not a valid mnemonic seed');
}
return {
address: keyring.createFromUri(suri, {}, type).address,
suri
};
}
import Authorize from './Authorize';
import CreateAccount from './CreateAccount';
import Export from './Export';
import Forget from './Forget';
import ImportQr from './ImportQr';
import ImportSeed from './ImportSeed';
import Settings from './Settings';
import Signing from './Signing';
import Welcome from './Welcome';
// load the ui settings, actually only used for address prefix atm
// probably overkill (however can replace once we have actual others)
const { prefix } = settings.get();
// FIXME Duplicated in Settings, horrible...
setSS58Format(prefix === -1 ? 42 : prefix);
// Request permission for video, based on access we can hide/show import
async function requestMediaAccess (cameraOn: boolean): Promise {
if (!cameraOn) {
return false;
}
try {
await navigator.mediaDevices.getUserMedia({ video: true });
return true;
} catch (error) {
console.error('Permission for video declined', error.message);
}
return false;
private seedValidate ({ suri, type }: RequestSeedValidate): ResponseSeedValidate {
const { phrase } = keyExtractSuri(suri);
if (isHex(phrase)) {
assert(isHex(phrase, 256), 'Hex seed needs to be 256-bits');
} else {
// sadly isHex detects as string, so we need a cast here
assert(SEED_LENGTHS.includes((phrase as string).split(' ').length), `Mnemonic needs to contain ${SEED_LENGTHS.join(', ')} words`);
assert(mnemonicValidate(phrase), 'Not a valid mnemonic seed');
}
return {
address: keyring.createFromUri(suri, {}, type).address,
suri
};
}
public createFromUri (_suri: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair {
// here we only aut-add the dev phrase if we have a hard-derived path
const suri = _suri.startsWith('//')
? `${DEV_PHRASE}${_suri}`
: _suri;
const { password, phrase, path } = keyExtractSuri(suri);
let seed;
if (isHex(phrase, 256)) {
seed = hexToU8a(phrase);
} else {
const str = phrase as string;
const parts = str.split(' ');
if ([12, 15, 18, 21, 24].includes(parts.length)) {
// FIXME This keeps compat with older versions, but breaks compat with subkey
// seed = type === 'sr25519'
// ? mnemonicToMiniSecret(phrase, password)
// : mnemonicToSeed(phrase, password);
seed = mnemonicToMiniSecret(phrase, password);
} else {
assert(str.length <= 32, 'specified phrase is not a valid mnemonic and is invalid as a raw seed at > 32 bytes');