Created
February 6, 2024 16:39
-
-
Save abisuq/c97552f3752d826b6cdd32ef8ad65b45 to your computer and use it in GitHub Desktop.
Nuts LP API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Welcome to Cloudflare Workers! This is your first worker. | |
* | |
* - Run "npm run dev" in your terminal to start a development server | |
* - Open a browser tab at http://localhost:8787/ to see your worker in action | |
* - Run "npm run deploy" to publish your worker | |
* | |
* Learn more at https://developers.cloudflare.com/workers/ | |
*/ | |
export default { | |
async fetch(request, env, ctx) { | |
const price = await calculateTokenAPriceInUSD(); | |
return Response.json(price); | |
}, | |
}; | |
async function fetchJson(url, body) { const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(body), }); | |
return response.json(); | |
} | |
async function getTokenAccountBalance(url, account) { | |
const body = { | |
jsonrpc: "2.0", | |
id: 1, | |
method: "getTokenAccountBalance", | |
params: [account], | |
}; | |
const data = await fetchJson(url, body); | |
return parseFloat(data.result.value.uiAmountString); | |
} | |
async function getSolPrice() { | |
const response = await fetch( | |
"https://api.diadata.org/v1/assetQuotation/Solana/0x0000000000000000000000000000000000000000", | |
); | |
const data = await response.json(); | |
return data.Price; | |
} | |
async function calculateTokenAPriceInUSD() { | |
// 换成自己的 RPC | |
const solanaUrl = | |
"https://palpable-tiniest-mound.solana-mainnet.quiknode.pro/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/"; | |
const tokenAAccount = "CE4thiCZZFpn89x9ziEKPMwwrfnCm6KmDuTwk1EAhXPo"; | |
const solAccount = "BTMLdyviQnHd9gVmgFpNVzcxueQGNMcKcgage3fpvgNi"; | |
try { | |
// Fetch balances | |
const tokenABalance = await getTokenAccountBalance( | |
solanaUrl, | |
tokenAAccount, | |
); | |
const solBalance = await getTokenAccountBalance(solanaUrl, solAccount); | |
const solPriceUSD = await getSolPrice(); | |
// Calculate Token A price in SOL | |
const tokenAPriceInSOL = 1 / (tokenABalance / solBalance); | |
// Calculate Token A price in USD | |
const tokenAPriceInUSD = tokenAPriceInSOL * solPriceUSD; | |
return { | |
tokenAPriceInSOL, | |
solPriceUSD, | |
tokenAPriceInUSD, | |
} | |
} catch (error) { | |
console.error("Error calculating Token A price in USD:", error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment