@polkadot/keyring/types#KeyringPair TypeScript Examples
The following examples show how to use
@polkadot/keyring/types#KeyringPair.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: setup.ts From bodhi.js with Apache License 2.0 | 6 votes |
setup = async () => {
const provider = new Provider({
provider: new WsProvider(WS_URL)
});
await provider.api.isReady;
let pair: KeyringPair;
if (seed) {
const keyring = new Keyring({ type: 'sr25519' });
pair = keyring.addFromUri(seed);
} else {
const testPairs = createTestPairs();
pair = testPairs.alice;
}
const signingKey = new AccountSigningKey(provider.api.registry);
signingKey.addKeyringPair(pair);
const wallet = new Signer(provider, pair.address, signingKey);
return {
wallet,
provider
};
}
Example #2
Source File: account.ts From metamask-snap-polkadot with Apache License 2.0 | 6 votes |
/**
* Returns KeyringPair if one is saved in wallet state, creates new one otherwise
* @param wallet
*/
export async function getKeyPair(wallet: Wallet): Promise<KeyringPair> {
// get app key and wait for api to be ready
const [appKey] = await Promise.all([wallet.getAppKey(), cryptoWaitReady()]);
// generate keys
const seed = appKey.substr(0, 32);
const keyring = new Keyring({ss58Format: getConfiguration(wallet).addressPrefix});
return keyring.addFromSeed(stringToU8a(seed));
}
Example #3
Source File: epics.ts From anthem with Apache License 2.0 | 6 votes |
setBond = async (
account: DotAccount,
stashKey: KeyringPair,
bond: string,
) => {
console.log("Setting bond for account and stashKey:");
console.log(account);
console.log(stashKey);
const { controllerKey } = account;
const WS_PROVIDER_URL: string = "wss://kusama-rpc.polkadot.io/";
const wsProvider = new WsProvider(WS_PROVIDER_URL);
const api: ApiPromise = await ApiPromise.create({ provider: wsProvider });
const result = await api.tx.staking
.bond(controllerKey, bond, "Stash")
.signAndSend(stashKey);
console.log("Set Bond Result:");
console.log(result);
return result;
}
Example #4
Source File: test-xcm-para.ts From moonbeam with GNU General Public License v3.0 | 6 votes |
async function registerAssetToParachain(
parachainApi: ApiPromise,
sudoKeyring: KeyringPair,
assetLocation: SourceLocation = sourceLocationRelay,
assetMetadata: AssetMetadata = relayAssetMetadata
) {
const { events: eventsRegister } = await createBlockWithExtrinsicParachain(
parachainApi,
sudoKeyring,
parachainApi.tx.sudo.sudo(
parachainApi.tx.assetManager.registerAsset(assetLocation, assetMetadata, new BN(1), true)
)
);
let assetId: string;
// Look for assetId in events
eventsRegister.forEach((e) => {
let ev = e.toHuman();
if (ev.section === "assetManager") {
assetId = ev.data[0];
}
});
if (!assetId) {
await new Promise((res) => setTimeout(res, 20000));
}
assetId = assetId.replace(/,/g, "");
// setAssetUnitsPerSecond
const { events } = await createBlockWithExtrinsicParachain(
parachainApi,
sudoKeyring,
parachainApi.tx.sudo.sudo(parachainApi.tx.assetManager.setAssetUnitsPerSecond(assetLocation, 0))
);
return { events, assetId };
}
Example #5
Source File: Derive.tsx From crust-apps with Apache License 2.0 | 6 votes |
function createAccount (source: KeyringPair, suri: string, name: string, password: string, success: string, genesisHash?: string): ActionStatus {
// we will fill in all the details below
const status = { action: 'create' } as ActionStatus;
try {
const derived = source.derive(suri);
derived.setMeta({ ...derived.meta, genesisHash, name, parentAddress: source.address, tags: [] });
const result = keyring.addPair(derived, password || '');
const { address } = result.pair;
status.account = address;
status.status = 'success';
status.message = success;
downloadAccount(result);
InputAddress.setLastValue('account', address);
} catch (error) {
status.status = 'error';
status.message = (error as Error).message;
}
return status;
}
Example #6
Source File: Balance.ts From gear-js with GNU General Public License v3.0 | 6 votes |
transferBalance(
keyring: KeyringPair,
to: string,
value: number | BN,
eventsCallback?: (event: any, data: any) => void,
): Promise<any> {
return new Promise(async (resolve, reject) => {
try {
const unsub = await this.api.tx.balances.transfer(to, value).signAndSend(keyring, ({ events, status }) => {
events.forEach(({ event: { data, method } }) => {
if (eventsCallback) {
eventsCallback(method, data);
}
if (method === 'Transfer') {
unsub();
resolve(0);
}
});
});
} catch (error) {
reject(new TransactionError(error.message));
}
});
}
Example #7
Source File: interbtc-api.ts From interbtc-api with Apache License 2.0 | 6 votes |
setAccount(account: AddressOrPair, signer?: Signer): void {
if (!(account as KeyringPair).sign && !signer) {
throw new Error("signer must be passed if account is not a Keypair");
}
if (signer) {
this.api.setSigner(signer);
}
this.transactionAPI.setAccount(account);
}
Example #8
Source File: formatAccounts.ts From parity-bridges-ui with GNU General Public License v3.0 | 6 votes |
export default function formatAccounts(accounts: Array<KeyringPair>, ss58Format: number) {
// TO-DO: This function lacks the capabillity to filter accounts that exist only on specific chains.
return accounts.map(({ meta, address }) => {
const formatedAddress = encodeAddress(address, ss58Format);
return {
icon: 'user',
key: formatedAddress,
text: (meta.name as string).toLocaleUpperCase(),
value: formatedAddress
};
});
}
Example #9
Source File: keyring.ts From sdk with Apache License 2.0 | 6 votes |
/**
* get address and avatar from mnemonic.
*/
async function addressFromMnemonic(mnemonic: string, ss58Format: number, cryptoType: KeypairType, derivePath: string) {
let keyPair: KeyringPair;
try {
keyPair = keyring.addFromMnemonic(mnemonic + (derivePath || ""), {}, cryptoType);
const address = encodeAddress(keyPair.publicKey, ss58Format);
const icons = await account.genIcons([address]);
return {
address,
svg: icons[0][1],
};
} catch (err) {
return { error: err.message };
}
}
Example #10
Source File: TxSigned.tsx From subscan-multisig-react with Apache License 2.0 | 6 votes |
async function signAndSend(
queueSetTxStatus: QueueTxMessageSetStatus,
currentItem: QueueTx,
tx: SubmittableExtrinsic<'promise'>,
pairOrAddress: KeyringPair | string,
options: Partial<SignerOptions>
): Promise<void> {
currentItem.txStartCb && currentItem.txStartCb();
try {
await tx.signAsync(pairOrAddress, options);
console.info('sending', tx.toHex());
queueSetTxStatus(currentItem.id, 'sending');
const unsubscribe = await tx.send(
handleTxResults('signAndSend', queueSetTxStatus, currentItem, (): void => {
unsubscribe();
})
);
} catch (error: unknown) {
if (error instanceof Error) {
console.error('signAndSend: error:', error);
queueSetTxStatus(currentItem.id, 'error', {}, error);
}
currentItem.txFailedCb && currentItem.txFailedCb(null);
}
}
Example #11
Source File: AccountSigningKey.ts From bodhi.js with Apache License 2.0 | 5 votes |
public addKeyringPair(...keyringPairs: (KeyringPair | ConcatArray<KeyringPair>)[]): void {
this.#keyringPairs = this.#keyringPairs.concat(...keyringPairs);
}
Example #12
Source File: transferTokens.ts From community-repo with GNU General Public License v3.0 | 5 votes |
async estimateFee(
account: KeyringPair,
tx: SubmittableExtrinsic<'promise'>
): Promise<Balance> {
const paymentInfo = await tx.paymentInfo(account);
return paymentInfo.partialFee;
}
Example #13
Source File: test-asset-manager.ts From moonbeam with GNU General Public License v3.0 | 5 votes |
describeDevMoonbeam("XCM - asset manager - Remove asset from supported", (context) => {
let assetId: string;
let alith: KeyringPair;
before("should be able to change existing asset type", async function () {
const keyringEth = new Keyring({ type: "ethereum" });
alith = keyringEth.addFromUri(ALITH_PRIV_KEY, null, "ethereum");
const parachainOne = context.polkadotApi;
// registerForeignAsset
const { events: eventsRegister } = await createBlockWithExtrinsic(
context,
alith,
parachainOne.tx.sudo.sudo(
parachainOne.tx.assetManager.registerForeignAsset(
sourceLocation,
assetMetadata,
new BN(1),
true
)
)
);
eventsRegister.forEach((e) => {
if (e.section.toString() === "assetManager") {
assetId = e.data[0].toHex();
}
});
assetId = assetId.replace(/,/g, "");
// setAssetUnitsPerSecond
const { events } = await createBlockWithExtrinsic(
context,
alith,
parachainOne.tx.sudo.sudo(
parachainOne.tx.assetManager.setAssetUnitsPerSecond(sourceLocation, 1, 0)
)
);
expect(events[1].method.toString()).to.eq("UnitsPerSecondChanged");
expect(events[4].method.toString()).to.eq("ExtrinsicSuccess");
// check asset in storage
const registeredAsset = ((await parachainOne.query.assets.asset(assetId)) as any).unwrap();
expect(registeredAsset.owner.toString()).to.eq(palletId);
await verifyLatestBlockFees(context, expect);
});
it("should remove an asset from our supported fee payments", async function () {
// ChangeAssetType
await createBlockWithExtrinsic(
context,
alith,
context.polkadotApi.tx.sudo.sudo(
context.polkadotApi.tx.assetManager.removeSupportedAsset(sourceLocation, 1)
)
);
// assetId
let id = (
(await context.polkadotApi.query.assetManager.assetTypeId(sourceLocation)) as any
).unwrap();
// asset units per second removed
let assetUnitsPerSecond = (await context.polkadotApi.query.assetManager.assetTypeUnitsPerSecond(
sourceLocation
)) as any;
// Supported assets should be 0
let supportedAssets =
(await context.polkadotApi.query.assetManager.supportedFeePaymentAssets()) as any;
expect(assetUnitsPerSecond.isNone).to.eq(true);
expect(bnToHex(id)).to.eq(assetId);
// the asset should not be supported
expect(supportedAssets.length).to.eq(0);
});
});
Example #14
Source File: Password.tsx From crust-apps with Apache License 2.0 | 5 votes |
function getPair (address: string): KeyringPair | null {
try {
return keyring.getPair(address);
} catch (error) {
return null;
}
}
Example #15
Source File: Keyring.ts From gear-js with GNU General Public License v3.0 | 5 votes |
private static unlock(keyring: KeyringPair, passphrase?: string) {
if (keyring.isLocked) {
keyring.unlock(passphrase);
}
return keyring;
}