Skip to content

Instantly share code, notes, and snippets.

@alwaysAn0n
Created November 30, 2018 16:02
Show Gist options
  • Save alwaysAn0n/d51a8ce5ac67fa2551483ecf76835954 to your computer and use it in GitHub Desktop.
Save alwaysAn0n/d51a8ce5ac67fa2551483ecf76835954 to your computer and use it in GitHub Desktop.
Async-await for sending many datacash transactions
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button onclick="send();" size=10>Send Many Txs in sequence</button><br>
</body>
<script>
// Enter a compressed private key here.
let pkey = '';
// Payment address that the payments will be sent to. I used the one
// associated with the above private key.
let cashAddress = '';
// Messages you want to include in your transactions.
let allMessagesToSend = ['cats are great', 'i hate pirates', 'wheres satoshi?'];
// Async-await compatible timeout function
let delay = ms => new Promise(resolve => setTimeout(resolve, ms));
// An async-await style function that makes a single
// datasend.call for the message supplied as the argument
let sendOneTransaction = async function(oneMessage) {
// Returns a "promise" function that will pass
// the results of datacash.send back to the
// function that called sendOneTransaction.
// In this case it's the send function
// that gets executed when the button is pressed.
return new Promise(function(resolve, reject) {
console.log('Now sending message:', oneMessage);
datacash.send({
data: ["0x9902", oneMessage],
cash: {
key: pkey,
fee: 250,
to: [{
address: cashAddress,
value: 500
}]
}
}, function(errorMessage, transactionId) {
if (errorMessage) {
console.log('Error sending message', oneMessage, ':', errorMessage);
return reject(errorMessage);
}
else {
console.log('Sent message', oneMessage, 'and got txid:', transactionId)
return resolve(transactionId);
}
});
})
};
async function send() {
// Loops over the array of messages and calls the
// function that sends each message one after the
// other, leaving 3 seconds in between each call.
for (oneMessage of allMessagesToSend) {
let txId;
try {
txId = await sendOneTransaction(oneMessage);
}
catch(error) {
console.log('There was an error in sending',oneMessage,':',error);
}
// Wait three seconds in between messages
await delay(3000);
}
}
</script>
<script src='https://unpkg.com/datacash'></script>
</html>
@alwaysAn0n
Copy link
Author

This sends one message for each entry in the allMessagesToSend array (one after the other). If you want more control over the individual datacash transactions, you can simply make allMessagesToSend an array of datacash config objects rather than strings then modify send() accordingly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment