Skip to content

Instantly share code, notes, and snippets.

@fipso
Created November 14, 2022 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fipso/ce85a9a9cc9b533447c35c7c90b955a9 to your computer and use it in GitHub Desktop.
Save fipso/ce85a9a9cc9b533447c35c7c90b955a9 to your computer and use it in GitHub Desktop.
import * as web3 from "@solana/web3.js";
import crypto from "crypto";
const MIN_OFFSET = 5;
const httpsRPC =
"";
const wssRPC =
"";
let currentBet = 0;
let solanaConnection;
// Returns true(heads)/false(tail)
async function coinflip() {
const betId = currentBet + 1;
const privateSeed = crypto.randomBytes(32);
const privateHash = crypto
.createHash("sha256")
.update(privateSeed)
.digest("hex");
const targetOffset = MIN_OFFSET + Math.floor(Math.random() * 10);
const currentSlot = await solanaConnection.getSlot("confirmed");
const targetSlot = currentSlot + targetOffset;
console.log("Waiting for", targetSlot);
const actualSlot = await new Promise((resolve, reject) => {
const sub = solanaConnection.onSlotChange((slot) => {
console.log("Found", slot.slot);
if (slot.slot >= targetSlot) {
solanaConnection.removeSlotChangeListener(sub);
resolve(slot.slot);
}
});
});
console.log("Found targetSlot", actualSlot, "waiting for block...");
let block;
while (true) {
await new Promise((resolve) => setTimeout(resolve, 10 * 1000));
try {
block = await solanaConnection.getBlock(actualSlot);
break;
} catch (err) {
if (!err.toString().includes("Block not available")) {
console.log(err);
}
}
}
const publicSeed = `${privateSeed}.${block.blockhash}.${betId}`;
const publicSeedHash = crypto
.createHash("sha256")
.update(publicSeed)
.digest("hex");
const hex = publicSeedHash.slice(0, 2);
const flip = parseInt(hex, 16);
return (flip % 2) + 1 === 1;
}
solanaConnection = new web3.Connection(httpsRPC, {
wsEndpoint: wssRPC,
});
coinflip().then((c) => console.log(c));
coinflip().then((c) => console.log(c));
coinflip().then((c) => console.log(c));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment