Skip to content

Instantly share code, notes, and snippets.

@mgild
Created January 23, 2024 13:12
Show Gist options
  • Save mgild/c407743fcc26a5ec2c8620e281926647 to your computer and use it in GitHub Desktop.
Save mgild/c407743fcc26a5ec2c8620e281926647 to your computer and use it in GitHub Desktop.
import type { AccountInfo } from "@solana/web3.js";
import { Connection, PublicKey } from "@solana/web3.js";
import { Big, BigUtils, bs58 } from "@switchboard-xyz/common";
import { OracleJob } from "@switchboard-xyz/common";
async function fetchLatestSlotHash(
connection: Connection
): Promise<[bigint, string]> {
const slotHashesSysvarKey = new PublicKey(
"SysvarS1otHashes111111111111111111111111111"
);
const accountInfo = await connection.getAccountInfo(slotHashesSysvarKey, {
commitment: "confirmed",
dataSlice: { length: 40, offset: 8 },
});
let buffer = accountInfo!.data;
const slotNumber = buffer.readBigUInt64LE();
buffer = buffer.slice(8);
return [slotNumber, bs58.encode(buffer)];
}
function buildBinanceComJob(pair: String): OracleJob {
let tasks = [
OracleJob.Task.create({
httpTask: OracleJob.HttpTask.create({
url: `https://www.binance.com/api/v3/ticker/price?symbol=${pair}`,
}),
}),
OracleJob.Task.create({
jsonParseTask: OracleJob.JsonParseTask.create({ path: "$.price" }),
}),
];
return OracleJob.create({
tasks,
});
}
function encodeJobs(jobArray: OracleJob[][]): string[][] {
return jobArray.map((innerArray) => {
return innerArray.map((job) =>
Buffer.from(OracleJob.encodeDelimited(job).finish()).toString("base64")
);
});
}
(async () => {
const connection = new Connection(
"https://api.mainnet-beta.solana.com",
"confirmed"
);
const [slotNumber, slotHash] = await fetchLatestSlotHash(connection);
const encodedJobs = encodeJobs([[buildBinanceComJob("BTCUSDT")]]);
const requestBody = {
api_version: "1.0", // Example API version
jobs_b64_encoded: encodedJobs, // Example job clusters
chain_metadata: {
SolanaChainMeta: {
cluster: "devnet", // Example cluster
slot: Number(slotNumber),
recent_slothash: slotHash,
},
},
signature_scheme: "Ed25519",
hash_scheme: "Sha256",
};
let apiUrl = "http://127.0.0.1:8080/feed_request";
const resp = await fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
}).then((response) => response.json());
console.log(resp);
return;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment