Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'promptly' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
currency: choice.currency,
unsignedTransactions: [{
tx: fundedTx,
// `vsize` for bitcoin core w/ segwit support, `size` for other clients
weightedSize: decodedTx.vsize || decodedTx.size
}]
});
} catch (e) {
console.log('Error verifying payment');
throw e;
}
// Display tx to user for confirmation
console.log(JSON.stringify(decodedTx, null, 2));
const signPayment = await promptly.confirm('Send this payment? (y/n)');
if (!signPayment) {
throw new Error('User aborted');
}
/**
* Send signed transaction to server for actual payment
*/
await sendPayment();
await sendP2pPayment();
async function sendPayment() {
try {
await client.sendSignedPayment({
paymentUrl: paymentOptions.requestUrl,
chain: choice.chain,
async function sendPayment() {
try {
await client.sendSignedPayment({
paymentUrl: paymentOptions.requestUrl,
chain: choice.chain,
currency: choice.currency,
signedTransactions: [{
tx: signedTx,
// `vsize` for bitcoin core w/ segwit support, `size` for other clients
weightedSize: decodedTx.vsize || decodedTx.size
}]
});
console.log('Payment successfully sent via payment protocol');
} catch (e) {
console.log('Error sending payment', e);
let confirm = promptly.confirm('Retry payment?', { default: false });
if (confirm) {
return await sendPayment();
} else {
throw e;
}
}
}
processResponse(res, async () => {
const choices: any = {}
// tslint:disable-next-line:forin
for (const i in res.data.data) {
choices[i] = res.data.data[i].id
}
let choiceText = ""
for (const [i, slug] of Object.entries(choices)) {
choiceText += `${i}) ${slug}\n`
}
const chose = await promptly.choose(
`Select organization to move to:
${choiceText}
Enter a number:`,
Object.keys(choices)
)
const orgSlug = choices[chose]
console.log(`Moving app '${appName}' to organization '${orgSlug}'`)
const resUpdate = await API.patch(`/api/v1/apps/${appName}`, {
data: {
attributes: {
org_slug: orgSlug
}
}
})
processResponse(resUpdate, () => {
// Must display network cost if provided, not doing so would be hiding costs
const networkCost = minerFee / Math.pow(10, decimals);
const usdCost = networkCost * getExchangeRate(chain, 'USD');
console.log(`${index++}. ${chain} ${round(estimatedAmount * Math.pow(10, -decimals), decimals)} - (Network Cost: $${round(usdCost, 2)})`);
}
if (unavailable.length) {
console.log(`There are ${unavailable.length} additional options that this wallet does not support or for which you do not have sufficient balance:`);
for (let { chain, estimatedAmount, decimals } of unavailable) {
console.log(`- ${chain} ${estimatedAmount * Math.pow(10, -decimals)}`);
}
}
console.log('---');
choice = await promptly.choose('What payment method would you like to use?', choices);
choice = paymentOptions.responseData.paymentOptions[choice - 1];
}
let rpcConfig = config.rpcServers[choice.chain];
rpcUrl = `http://${rpcConfig.ipAddress}:${rpcConfig.port}`;
rpcUser = rpcConfig.username;
rpcPass = rpcConfig.password;
const { responseData: paymentRequest } = await client.selectPaymentOption(paymentOptions.requestUrl, choice.chain, choice.currency);
/**
* Wallet creates a transaction matching data in the instructions
*/
// Format outputs as expected for bitcoin rpc client
let outputObject = {};
options = {
default: 'frame'
};
const mongodbName = await Promptly.prompt(`MongoDB name: (${options.default})`, options);
// connect to db
const db = await MongoModels.connect({ uri: mongodbUri, db: mongodbName });
if (!db) {
throw Error('Could not connect to MongoDB.');
}
// get root user creds
const rootEmail = await Promptly.prompt('Root user email:');
const rootPassword = await Promptly.password('Root user password:');
// clear tables
await Promise.all([
Account.deleteMany({}),
AdminGroup.deleteMany({}),
Admin.deleteMany({}),
AuthAttempt.deleteMany({}),
Session.deleteMany({}),
Status.deleteMany({}),
User.deleteMany({})
]);
// setup root group
function (cb) {
if (!program.wt.config[options.profile])
return cb();
console.log('You already have the `' + options.profile + '` profile:');
program.wt.print_profile(options.profile, program.wt.config[options.profile]);
promptly.confirm('Do you want to override it? ', function (error, value) {
if (error) return cb(error);
if (!value) process.exit(1);
cb();
});
},
function (cb) {
const createUser = (config: FactoryConfig) => async ({
defaultEmail,
defaultPassword,
rolesIds,
userType,
}: Options) => {
console.log(`--------------------------------------------------------`);
console.log(`Creating ${userType}...`);
const email = await promptly.prompt(
`Choose email [default: ${defaultEmail}]: `,
{ default: defaultEmail }
);
const password = await promptly.password(
`Choose password [default: ${defaultPassword}]: `,
{ default: defaultPassword }
);
const { service } = config;
console.log('Validating input...');
validateData(rules)({ email, password });
console.log('Input validated successfuly!');
console.log(`Creating ${userType}...`);
function signupRequest () {
let msg = 'Would you like to create a new account?';
Promptly.prompt(msg, { default: 'yes' }, (err, value) => {
if (err) {
console.log('Exception prompting input.');
return;
}
if (value === 'yes') {
console.log('Ok, let\'s create an account...');
signup();
} else {
console.log('Ok, please enter your credentials...');
configure();
}
});
}
.action(async (opts, args, rest) => {
const email = await promptly.prompt("Email: ")
const password = await promptly.password("Password: ")
const otp = await promptly.prompt("2FA code (if any): ", { default: "n/a", retry: false })
try {
const res = await axios.post(`${baseURL}/api/v1/sessions`, {
data: { attributes: { email, password, otp } }
})
processResponse(res, () => {
const homepath = homeConfigPath()
const credspath = path.join(homepath, "credentials.yml")
fs.writeFileSync(credspath, YAML.dump({ access_token: res.data.data.attributes.access_token }))
console.log("Wrote credentials at:", credspath)
})
} catch (e) {
if (e.response) {
console.log(e.response.data)
} else {
throw e
}
async function sendP2pPayment() {
try {
await broadcastP2P(signedTx);
} catch (e) {
console.log('Error broadcasting transaction to p2p network', e);
let confirm = promptly.confirm('Retry broadcast?', { default: false });
if (confirm) {
return await sendPayment();
} else {
throw e;
}
}
}
}