This code snippet illustrates how we harness the latest block hash from the XRP Ledger to generate a random number. By utilizing this decentralized source, we ensure a transparent and tamper-proof method of randomness, reinforcing the integrity of the game mechanics.
// Function to fetch the latest block hash
async function getLatestBlockHash() {
const client = new xrpl.Client("wss://s.altnet.rippletest.net:51233");
await client.connect();
let latestBlockHash;
try {
// Get the latest ledger
const ledgerResponse = await client.request({
command: "ledger",
ledger_index: "validated",
});
// Extract the latest block hash
latestBlockHash = ledgerResponse.result.ledger_hash;
} catch (error) {
console.error("Error fetching latest block hash:", error);
throw error; // Throw error to handle it in the calling function
} finally {
await client.disconnect();
}
return latestBlockHash; // Return the fetched block hash
}
// Function to generate a random number based on the latest block hash
async function generateRandomNumber(maxNumber) {
if (typeof maxNumber !== "number" || maxNumber < 1) {
throw new Error("maxNumber must be a positive integer.");
}
const latestBlockHash = await getLatestBlockHash(); // Fetch the latest block hash
const hashSegment = parseInt(latestBlockHash.slice(0, 8), 16);
// Use a cryptographic approach to generate a random number
const randomValue = crypto
.createHash("sha256")
.update(hashSegment.toString())
.digest("hex");
// Convert the hash to a number and map it to 1-maxNumber
const randomNum = (parseInt(randomValue, 16) % maxNumber) + 1;
return randomNum;
}
To generate a random number using the XRP Ledger Blockchain-Based Random Number Generator API, make a POST request to the following endpoint:
POST https://xrprandomizer.com/random
Send the following JSON data in the body of your request:
{
"maxNumber": 5
}
fetch('https://xrprandomizer.com/random', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ maxNumber: 5 })
})
.then(response => response.json())
.then(data => console.log('Random Number:', data.randomNumber))
.catch(error => console.error('Error:', error));
axios.post('https://xrprandomizer.com/random', {
maxNumber: 5
})
.then(response => {
console.log('Random Number:', response.data.randomNumber);
})
.catch(error => {
console.error('Error:', error);
});