Got a cool example to share? Get listed here! Submit it now.

useChainlinkFunctions()

Collection of community submitted examples for Chainlink Functions

Get inspired from quick examples

Chainlink Functions, a new self-service platform that allows anyone to write serverless code to fetch any data from any API and run custom compute on Chainlink's network. Learn from examples created by the community or contribute your own!
Learn more about Chainlink Functions

Get US Treasury Yield of specified maturity and interval

Submitted by:
Justin Gnoh
This example shows how to return the daily, weekly, and monthly US treasury yield of a given maturity timeline from the Alphavantage API. Result is expected to be in percentage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 // This function retrieves the latest released yield of the US X Year Treasury from the AlphaVantage API given a specific interval or maturity. // Maturity timelines: 3month, 2year, 5year, 7year, 10year, 30year // Interval options: daily, weekly, monthly const maturity = args[0] const interval = args[1] if (!secrets.apiKey) { throw Error("Need to set Alpha Vantage API key"); } // make HTTP request const url = `https://www.alphavantage.co/query?function=TREASURY_YIELD` console.log(`HTTP GET Request to ${url}&interval=${interval}&maturity=${maturity}`) // construct the HTTP Request object. See: https://github.com/smartcontractkit/functions-hardhat-starter-kit#javascript-code // params used for URL query parameters const alphavantageRequest = Functions.makeHttpRequest({ url: url, params: { interval: interval, maturity: maturity, apikey: secrets.apiKey }, }) // Execute the API request (Promise) const alphavantageResponse = await alphavantageRequest if (alphavantageResponse.error) { console.error(alphavantageResponse.error) throw Error("Request failed") } const data = alphavantageResponse["data"] console.log(data); // Gets the latest yield rate in the array of returned data values const floatingRate = data.data[0].value; if (data.Response === "Error") { console.error(data.Message) throw Error(`Functional error. Read message: ${data.Message}`) } // Solidity doesn't support decimals so multiply by 100 and round to the nearest integer // Use Functions.encodeUint256 to encode an unsigned integer to a Buffer return Functions.encodeUint256(Math.round(floatingRate * 100))