@polkadot/util-crypto#cryptoWaitReady TypeScript Examples

The following examples show how to use @polkadot/util-crypto#cryptoWaitReady. 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: account.ts    From metamask-snap-polkadot with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #2
Source File: bipWorker.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
ctx.onmessage = async ({ data: { pairType } }): Promise<void> => {
  await cryptoWaitReady();

  const seed = mnemonicGenerate();
  const miniSecret = mnemonicToMiniSecret(seed);
  const { publicKey } = pairType === 'sr25519'
    ? schnorrkelKeypairFromSeed(miniSecret)
    : naclKeypairFromSeed(miniSecret);

  ctx.postMessage({
    publicKey,
    seed
  });
};
Example #3
Source File: democracy.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
async function main(): Promise<void> {
    const rawData = require("fs").readFileSync("testnet_runtime_parachain.compact.compressed.wasm");
    const data = "0x" + rawData.toString("hex");
    await cryptoWaitReady();
    const keyring = new Keyring({ type: "sr25519" });
    const userKeyring = keyring.addFromUri(ACCOUNT_URI);
    const api = await createSubstrateAPI(PARACHAIN_ENDPOINT);

    const transactionAPI = new DefaultTransactionAPI(api, userKeyring);
    
    const proposal = api.tx.parachainSystem.authorizeUpgrade("0x72e1663c5c98310ff9654700738b4f2987a7d8d9d4ccbfd39babe98517ddd7eb");
    const proposalData = proposal.method.toHex();
    const proposalHash = proposal.method.hash.toHex();


    // // sudo-upgrade using set-code
    // await transactionAPI.sendLogged(api.tx.sudo.sudoUncheckedWeight(api.tx.system.setCode(data), 0), undefined);

    console.log("Locking KINT...");
    await transactionAPI.sendLogged(api.tx.escrow.createLock(10000000000000, 2628000), undefined);

    console.log("Submitting preimage...");
    await transactionAPI.sendLogged(api.tx.democracy.notePreimage(proposalData), undefined);

    console.log("Submitting proposal...");
    await transactionAPI.sendLogged(api.tx.democracy.propose(proposalHash, 5000000000000), undefined);

    console.log("Fastracking proposal...");
    await transactionAPI.sendLogged(api.tx.sudo.sudo(api.tx.democracy.fastTrack(0, 3)), undefined);

    console.log("Voting on proposal...");
    await transactionAPI.sendLogged(api.tx.democracy.vote(0, api.createType<DemocracyVote>("DemocracyVote", {
        aye: true,
        balance: 1000000000000
    })), undefined);

    api.disconnect();
}
Example #4
Source File: keyring.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Add user's accounts to keyring incedence,
 * so user can use them to sign txs with password.
 * We use a list of ss58Formats to encode the accounts
 * into different address formats for different networks.
 */
async function initKeys(accounts: KeyringPair$Json[], ss58Formats: number[]) {
  await cryptoWaitReady();
  const res = {};
  ss58Formats.forEach((ss58) => {
    (<any>res)[ss58] = {};
  });

  accounts.forEach((i) => {
    // import account to keyring
    const keyPair = keyring.addFromJson(i);
    // then encode address into different ss58 formats
    ss58Formats.forEach((ss58) => {
      const pubKey = u8aToHex(keyPair.publicKey);
      (<any>res)[ss58][pubKey] = keyring.encodeAddress(keyPair.publicKey, ss58);
    });
  });
  return res;
}
Example #5
Source File: account.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * encode pubKey to addresses with different prefixes
 */
async function encodeAddress(pubKeys: string[], ss58Formats: number[]) {
  await cryptoWaitReady();
  const res = {};
  ss58Formats.forEach((ss58) => {
    (<any>res)[ss58] = {};
    pubKeys.forEach((i) => {
      (<any>res)[ss58][i] = keyring.encodeAddress(hexToU8a(i), ss58);
    });
  });
  return res;
}
Example #6
Source File: account.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * decode address and check it's ss58Format
 */
async function checkAddressFormat(address: string, ss58: number) {
  await cryptoWaitReady();
  try {
    const formated = keyring.encodeAddress(keyring.decodeAddress(address), ss58);
    return formated.toUpperCase() == address.toUpperCase();
  } catch (err) {
    (<any>window).send("log", { error: err.message });
    return false;
  }
}
Example #7
Source File: account.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * decode address to it's publicKey
 */
async function decodeAddress(addresses: string[]) {
  await cryptoWaitReady();
  try {
    const res = {};
    addresses.forEach((i) => {
      const pubKey = u8aToHex(keyring.decodeAddress(i));
      (<any>res)[pubKey] = i;
    });
    return res;
  } catch (err) {
    (<any>window).send("log", { error: err.message });
    return null;
  }
}
Example #8
Source File: spec.ts    From polkadot-launch with MIT License 6 votes vote down vote up
// Add additional authorities to chain spec in `session.keys`
export async function addAuthority(spec: string, name: string) {
	await cryptoWaitReady();

	const sr_keyring = new Keyring({ type: "sr25519" });
	const sr_account = sr_keyring.createFromUri(`//${nameCase(name)}`);
	const sr_stash = sr_keyring.createFromUri(`//${nameCase(name)}//stash`);

	const ed_keyring = new Keyring({ type: "ed25519" });
	const ed_account = ed_keyring.createFromUri(`//${nameCase(name)}`);

	const ec_keyring = new Keyring({ type: "ecdsa" });
	const ec_account = ec_keyring.createFromUri(`//${nameCase(name)}`);

	let key = [
		sr_stash.address,
		sr_stash.address,
		{
			grandpa: ed_account.address,
			babe: sr_account.address,
			im_online: sr_account.address,
			parachain_validator: sr_account.address,
			authority_discovery: sr_account.address,
			para_validator: sr_account.address,
			para_assignment: sr_account.address,
			beefy: encodeAddress(ec_account.publicKey),
		},
	];

	let rawdata = fs.readFileSync(spec);
	let chainSpec = JSON.parse(rawdata);

	let keys = getAuthorityKeys(chainSpec);
	keys.push(key);

	let data = JSON.stringify(chainSpec, null, 2);
	fs.writeFileSync(spec, data);
	console.log(`  ? Added Genesis Authority ${name}`);
}
Example #9
Source File: bipWorker.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
cryptoWaitReady().catch((): void => {
  // ignore
});
Example #10
Source File: rpc.ts    From polkadot-launch with MIT License 5 votes vote down vote up
export async function sendHrmpMessage(
	api: ApiPromise,
	recipient: string,
	data: string,
	finalization: boolean = false
) {
	return new Promise<void>(async (resolvePromise, reject) => {
		await cryptoWaitReady();

		const keyring = new Keyring({ type: "sr25519" });
		const alice = keyring.addFromUri("//Alice");

		const nonce = Number((await api.query.system.account(alice.address)).nonce);

		let hrmpMessage = {
			recipient: recipient,
			data: data,
		};
		let message = api.createType("OutboundHrmpMessage", hrmpMessage);

		console.log(`--- Sending a message to ${recipient}. (nonce: ${nonce}) ---`);
		const unsub = await api.tx.sudo
			.sudo(api.tx.messageBroker.sudoSendHrmpMessage(message))
			.signAndSend(alice, { nonce: nonce, era: 0 }, (result) => {
				console.log(`Current status is ${result.status}`);
				if (result.status.isInBlock) {
					console.log(
						`Transaction included at blockHash ${result.status.asInBlock}`
					);
					if (finalization) {
						console.log("Waiting for finalization...");
					} else {
						unsub();
						resolvePromise();
					}
				} else if (result.status.isFinalized) {
					console.log(
						`Transaction finalized at blockHash ${result.status.asFinalized}`
					);
					unsub();
					resolvePromise();
				} else if (result.isError) {
					console.log(`Transaction Error`);
					reject(`Transaction Error`);
				}
			});
	});
}
Example #11
Source File: rpc.ts    From polkadot-launch with MIT License 5 votes vote down vote up
// Set the balance of an account on the relay chain.
export async function setBalance(
	api: ApiPromise,
	who: string,
	value: string,
	finalization: boolean = false
) {
	return new Promise<void>(async (resolvePromise, reject) => {
		await cryptoWaitReady();

		const keyring = new Keyring({ type: "sr25519" });
		const alice = keyring.addFromUri("//Alice");

		const nonce = Number((await api.query.system.account(alice.address)).nonce);

		console.log(
			`--- Submitting extrinsic to set balance of ${who} to ${value}. (nonce: ${nonce}) ---`
		);
		const unsub = await api.tx.sudo
			.sudo(api.tx.balances.setBalance(who, value, 0))
			.signAndSend(alice, { nonce: nonce, era: 0 }, (result) => {
				console.log(`Current status is ${result.status}`);
				if (result.status.isInBlock) {
					console.log(
						`Transaction included at blockHash ${result.status.asInBlock}`
					);
					if (finalization) {
						console.log("Waiting for finalization...");
					} else {
						unsub();
						resolvePromise();
					}
				} else if (result.status.isFinalized) {
					console.log(
						`Transaction finalized at blockHash ${result.status.asFinalized}`
					);
					unsub();
					resolvePromise();
				} else if (result.isError) {
					console.log(`Transaction Error`);
					reject(`Transaction Error`);
				}
			});
	});
}
Example #12
Source File: rpc.ts    From polkadot-launch with MIT License 5 votes vote down vote up
// Submit an extrinsic to the relay chain to register a parachain.
// Uses the Alice account which is known to be Sudo for the relay chain.
export async function registerParachain(
	api: ApiPromise,
	id: string,
	wasm: string,
	header: string,
	finalization: boolean = false
) {
	return new Promise<void>(async (resolvePromise, reject) => {
		await cryptoWaitReady();

		const keyring = new Keyring({ type: "sr25519" });
		const alice = keyring.addFromUri("//Alice");

		let paraGenesisArgs = {
			genesis_head: header,
			validation_code: wasm,
			parachain: true,
		};
		let genesis = api.createType("ParaGenesisArgs", paraGenesisArgs);

		const nonce = Number((await api.query.system.account(alice.address)).nonce);

		console.log(
			`--- Submitting extrinsic to register parachain ${id}. (nonce: ${nonce}) ---`
		);
		const unsub = await api.tx.sudo
			.sudo(api.tx.parasSudoWrapper.sudoScheduleParaInitialize(id, genesis))
			.signAndSend(alice, { nonce: nonce, era: 0 }, (result) => {
				console.log(`Current status is ${result.status}`);
				if (result.status.isInBlock) {
					console.log(
						`Transaction included at blockHash ${result.status.asInBlock}`
					);
					if (finalization) {
						console.log("Waiting for finalization...");
					} else {
						unsub();
						resolvePromise();
					}
				} else if (result.status.isFinalized) {
					console.log(
						`Transaction finalized at blockHash ${result.status.asFinalized}`
					);
					unsub();
					resolvePromise();
				} else if (result.isError) {
					console.log(`Transaction Error`);
					reject(`Transaction Error`);
				}
			});
	});
}
Example #13
Source File: xcm-return-unknown-tokens.ts    From interbtc-api with Apache License 2.0 5 votes vote down vote up
async function main(): Promise<void> {
    await cryptoWaitReady();
    console.log("Running xcm script...");
    const keyring = new Keyring({ type: "sr25519" });
    const userKeyring = keyring.addFromUri(ACCOUNT_URI);
    const api = await createSubstrateAPI(PARACHAIN_ENDPOINT);

    const transactionAPI = new DefaultTransactionAPI(api, userKeyring);

    const asset = api.createType<XcmVersionedMultiAsset>("XcmVersionedMultiAsset", {
        v1: api.createType("XcmV1MultiAsset", {
            id: api.createType("XcmV1MultiassetAssetId", {
                concrete: api.createType("XcmV1MultiLocation", {
                    parents: 1,
                    interior: api.createType("XcmV1MultilocationJunctions", {
                        x2: [
                            api.createType("XcmV1Junction", { 
                                parachain: 2000 
                            }), api.createType("XcmV1Junction", { 
                                generalKey: [0, 12] // kint
                            })]
                    })
                })
            }),
            fun: api.createType("XcmV1MultiassetFungibility", {
                fungible: 10000000000
            })
        })}
    );

    const dest = api.createType<XcmVersionedMultiLocation>("XcmVersionedMultiLocation", {
        v1: api.createType("XcmV1MultiLocation", {
            parents: 1,
            interior: api.createType("XcmV1MultilocationJunctions", {
                x2: [
                    api.createType("XcmV1Junction", { 
                        parachain: 2000 
                    }), api.createType("XcmV1Junction", { 
                        accountId32: {
                            network: api.createType("XcmV0JunctionNetworkId", { any: true }),
                            id: "0x8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48" // bob 
                        }
                    })]
            })
        })
    });

    
    const sibling = api.createType<XcmV1MultiLocation>("XcmV1MultiLocation", {
        parents: 1,
        interior: api.createType("XcmV1MultilocationJunctions", {
            x1: api.createType("XcmV1Junction", { parachain: 2000 })
        })
    });

    const setupTx = api.tx.sudo.sudo(api.tx.polkadotXcm.forceXcmVersion(sibling, 2));
    const xcmTx = api.tx.xTokens.transferMultiasset(asset, dest, 1000000001);

    console.log("Constructed the tx, broadcasting first...");
    await transactionAPI.sendLogged(setupTx, undefined);
    console.log("broadcasting second...");
    await transactionAPI.sendLogged(xcmTx, undefined);

    api.disconnect();
}
Example #14
Source File: xcm-cross-chain-transfer.ts    From interbtc-api with Apache License 2.0 5 votes vote down vote up
async function main(): Promise<void> {
    await cryptoWaitReady();
    console.log("Running xcm script...");
    const keyring = new Keyring({ type: "sr25519" });
    const userKeyring = keyring.addFromUri(ACCOUNT_URI);
    const api = await createSubstrateAPI(PARACHAIN_ENDPOINT);

    const transactionAPI = new DefaultTransactionAPI(api, userKeyring);

    const currencyId = api.createType("InterbtcPrimitivesCurrencyId", { 
        token: api.createType("InterbtcPrimitivesTokenSymbol", {
            kint: true,
        }) 
    });

    const dest = api.createType<XcmVersionedMultiLocation>("XcmVersionedMultiLocation", {
        v1: api.createType("XcmV1MultiLocation", {
            parents: 1,
            interior: api.createType("XcmV1MultilocationJunctions", {
                x2: [
                    api.createType("XcmV1Junction", { 
                        parachain: 3000 
                    }), api.createType("XcmV1Junction", { 
                        accountId32: {
                            network: api.createType("XcmV0JunctionNetworkId", { any: true }),
                            id: "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d" // alice 
                        }
                    })]
            })
        })
    });

    
    const sibling = api.createType<XcmV1MultiLocation>("XcmV1MultiLocation", {
        parents: 1,
        interior: api.createType("XcmV1MultilocationJunctions", {
            x1: api.createType("XcmV1Junction", { parachain: 3000 })
        })
    });

    const setupTx = api.tx.sudo.sudo(api.tx.polkadotXcm.forceXcmVersion(sibling, 2));
    const xcmTx = api.tx.xTokens.transfer(currencyId, 100000000000, dest, 400000000000);
    // send back 10000000000, 1000000001

    console.log("Constructed the tx, broadcasting first...");
    await transactionAPI.sendLogged(setupTx, undefined);
    console.log("broadcasting second...");
    await transactionAPI.sendLogged(xcmTx, undefined);

    api.disconnect();
}
Example #15
Source File: hrmp-setup.ts    From interbtc-api with Apache License 2.0 5 votes vote down vote up
async function main(): Promise<void> {
    await cryptoWaitReady();
    const keyring = new Keyring({ type: "sr25519" });
    const userKeyring = keyring.addFromUri(ACCOUNT_URI);
    const api = await createSubstrateAPI(PARACHAIN_ENDPOINT);

    const parent = api.createType<XcmV1MultiLocation>("XcmV1MultiLocation", {
        parents: 1,
        interior: api.createType("XcmV1MultilocationJunctions", {
            here: true
        })
    });
    const setupTx = api.tx.sudo.sudo(api.tx.polkadotXcm.forceXcmVersion(parent, 2));

    // transactions used for the purestake alpha test
    const westendRequestXcmTx = construct_xcm(api, 1002, "0x3300e80300000800000000040000");
    const westendCancelXcmTx = construct_xcm(api, 1002, "0x3306ea030000e9030000");
    const westendAcceptXcmTx = construct_xcm(api, 1002, "0x3301e8030000");
    
    // transactions used for rococo-local test
    const rococoRequestXcmTx = construct_xcm(api, 2000, "0x1700b80b00000800000000900100");
    const rococoAcceptXcmTx = construct_xcm(api, 2000, "0x1701d0070000");

    // transactions to be used on kintsugi
    const kinstugiRequestXcmTx = construct_xcm(api, 2092, "0x3c00d0070000e803000000900100");

    // note: very important to use `.method`, otherwise it includes signing info. The polkadot.js
    // app strips the signing info when you try to decode it, but if you use the call data in
    // an extrinsic (e.g. in democracy), it will fail.
    console.log("Call data: " + rococoRequestXcmTx.method.toHex());
    console.log("Call hash: " + rococoRequestXcmTx.method.hash.toHex());

    const transactionAPI = new DefaultTransactionAPI(api, userKeyring);

    console.log("Constructed the tx, broadcasting first...");
    await transactionAPI.sendLogged(setupTx, undefined);
    console.log("broadcasting second...");
    await transactionAPI.sendLogged(api.tx.sudo.sudo(rococoAcceptXcmTx), undefined);

    api.disconnect();
}
Example #16
Source File: index.ts    From parachain-launch with Apache License 2.0 4 votes vote down vote up
generate = async (config: Config, { output, yes }: { output: string; yes: boolean }) => {
  await cryptoWaitReady();

  if (!config?.relaychain?.chain) {
    return fatal('Missing relaychain.chain');
  }
  if (!config?.relaychain?.image) {
    return fatal('Missing relaychain.image');
  }

  const relaychainGenesisFilePath = path.join(output, `${config.relaychain.chain}.json`);
  checkOverrideFile(relaychainGenesisFilePath, yes);

  const dockerComposePath = path.join(output, 'docker-compose.yml');
  checkOverrideFile(dockerComposePath, yes);

  fs.mkdirSync(output, { recursive: true });

  for (const parachain of config.parachains) {
    generateParachainGenesisFile(parachain.id, parachain.image, parachain.chain, output, yes);
  }

  generateRelaychainGenesisFile(config, relaychainGenesisFilePath, output);
  generateDockerfiles(config, output, yes);

  const dockerCompose: DockerConfig = {
    version: '3.7',
    services: {},
    volumes: {},
  };

  const ulimits = {
    nofile: {
      soft: 65536,
      hard: 65536,
    },
  };

  let idx = 0;
  for (const node of config.relaychain.nodes) {
    const name = `relaychain-${_.kebabCase(node.name)}`;
    const nodeConfig: DockerNode = {
      ports: [
        ...(node.wsPort === false ? [] : [`${node.wsPort || 9944 + idx}:9944`]),
        ...(node.rpcPort === false ? [] : [`${node.rpcPort || 9933 + idx}:9933`]),
        ...(node.port === false ? [] : [`${node.port || 30333 + idx}:30333`]),
      ],
      volumes: [`${name}:/data`],
      build: {
        context: '.',
        dockerfile: 'relaychain.Dockerfile',
      },
      command: [
        '--base-path=/data',
        `--chain=/app/${config.relaychain.chain}.json`,
        '--validator',
        '--ws-external',
        '--rpc-external',
        '--rpc-cors=all',
        `--name=${node.name}`,
        `--${node.name.toLowerCase()}`,
        ...(config.relaychain.flags || []),
        ...(node.flags || []),
      ],
      environment: _.assign({}, config.relaychain.env, node.env),
      ulimits,
    };

    dockerCompose.services[name] = nodeConfig;
    dockerCompose.volumes[name] = null;

    ++idx;
  }

  for (const parachain of config.parachains) {
    let nodeIdx = 0;

    const { key: nodeKey, address: nodeAddress } = generateNodeKey(config.relaychain.image);
    const volumePath = parachain.volumePath || '/data';

    for (const parachainNode of parachain.nodes) {
      const name = `parachain-${parachain.id}-${nodeIdx}`;

      const nodeConfig: DockerNode = {
        ports: [
          `${parachainNode.wsPort || 9944 + idx}:9944`,
          `${parachainNode.rpcPort || 9933 + idx}:9933`,
          `${parachainNode.port || 30333 + idx}:30333`,
        ],
        volumes: [`${name}:${volumePath}`],
        build: {
          context: '.',
          dockerfile: `parachain-${parachain.id}.Dockerfile`,
        },
        command: [
          `--base-path=${volumePath}`,
          `--chain=/app/${getChainspecName(parachain.chain, parachain.id)}`,
          '--ws-external',
          '--rpc-external',
          '--rpc-cors=all',
          `--name=${name}`,
          '--collator',
          ...(parachain.flags || []),
          ...(parachainNode.flags || []),
          nodeIdx === 0
            ? `--node-key=${nodeKey}`
            : `--bootnodes=/dns/parachain-${parachain.id}-0/tcp/30333/p2p/${nodeAddress}`,
          '--listen-addr=/ip4/0.0.0.0/tcp/30333',
          '--',
          `--chain=/app/${config.relaychain.chain}.json`,
          ...(parachain.relaychainFlags || []),
          ...(parachainNode.relaychainFlags || []),
        ],
        environment: _.assign({}, parachain.env, parachainNode.env),
        ulimits,
      };

      dockerCompose.services[name] = nodeConfig;
      dockerCompose.volumes[name] = null;

      ++nodeIdx;
      ++idx;
    }
  }

  fs.writeFileSync(dockerComposePath, YAML.stringify(dockerCompose));

  console.log('docker-compose.yml generated at', dockerComposePath);
}
Example #17
Source File: setup.ts    From interbtc-api with Apache License 2.0 4 votes vote down vote up
async function main<U extends CurrencyUnit>(params: InitializationParams): Promise<void> {
    if (!params.initialize) {
        return Promise.resolve();
    }
    await cryptoWaitReady();
    console.log("Running initialization script...");
    const keyring = new Keyring({ type: "sr25519" });
    const vault_1 = keyring.addFromUri(VAULT_1_URI);

    const api = await createSubstrateAPI(PARACHAIN_ENDPOINT);
    const sudoAccount = keyring.addFromUri(SUDO_URI);
    const oracleAccount = keyring.addFromUri(ORACLE_URI);

    const oracleAccountInterBtcApi = new DefaultInterBtcApi(api, "regtest", oracleAccount, ESPLORA_BASE_PATH);
    const sudoAccountInterBtcApi = new DefaultInterBtcApi(api, "regtest", sudoAccount, ESPLORA_BASE_PATH);

    const wrappedCurrency = sudoAccountInterBtcApi.getWrappedCurrency();
    const collateralCurrency = getCorrespondingCollateralCurrency(
        sudoAccountInterBtcApi.getGovernanceCurrency()
    ) as unknown as Currency<U>;
    const defaultInitializationParams = getDefaultInitializationParams<U>(
        keyring,
        vault_1.address,
        wrappedCurrency,
        collateralCurrency
    );
    const bitcoinCoreClient = new BitcoinCoreClient(
        BITCOIN_CORE_NETWORK,
        BITCOIN_CORE_HOST,
        BITCOIN_CORE_USERNAME,
        BITCOIN_CORE_PASSWORD,
        BITCOIN_CORE_PORT,
        BITCOIN_CORE_WALLET
    );

    if (params.setStableConfirmations !== undefined) {
        const stableConfirmationsToSet =
            params.setStableConfirmations === true
                ? (defaultInitializationParams.setStableConfirmations as ChainConfirmations)
                : params.setStableConfirmations;
        await initializeStableConfirmations(api, stableConfirmationsToSet, sudoAccount, bitcoinCoreClient);
    }

    if (params.setExchangeRate !== undefined) {
        const exchangeRateToSet =
            params.setExchangeRate === true
                ? (defaultInitializationParams.setExchangeRate as unknown as ExchangeRate<
                      Bitcoin,
                      BitcoinUnit,
                      Currency<CollateralUnit>,
                      CollateralUnit
                  >)
                : params.setExchangeRate;
        await initializeExchangeRate(exchangeRateToSet, oracleAccountInterBtcApi.oracle);
    }

    if (params.btcTxFees !== undefined) {
        const btcTxFees = params.btcTxFees === true ? (defaultInitializationParams.btcTxFees as Big) : params.btcTxFees;
        await initializeBtcTxFees(btcTxFees, oracleAccountInterBtcApi.oracle);
    }

    if (params.enableNomination === true) {
        initializeVaultNomination(params.enableNomination, sudoAccountInterBtcApi.nomination);
    }

    if (params.issue !== undefined) {
        const issueParams =
            params.issue === true
                ? (defaultInitializationParams.issue as InitializeIssue)
                : (params.issue as InitializeIssue);
        const vaultId = newVaultId(
            api,
            issueParams.vaultAddress,
            collateralCurrency as unknown as CollateralCurrency,
            wrappedCurrency
        );
        await initializeIssue(
            sudoAccountInterBtcApi,
            bitcoinCoreClient,
            issueParams.issuingAccount,
            issueParams.amount,
            vaultId
        );
    }

    if (params.redeem !== undefined) {
        const redeemParams =
            params.redeem === true
                ? (defaultInitializationParams.redeem as InitializeRedeem)
                : (params.redeem as InitializeRedeem);
        const redeemingAccountInterBtcApi = new DefaultInterBtcApi(api, "regtest", sudoAccount);
        await initializeRedeem(
            redeemingAccountInterBtcApi.redeem,
            redeemParams.amount,
            redeemParams.redeemingBTCAddress
        );
    }
    api.disconnect();
}