Deriving a cross rate from two Chainlink feeds with different decimals
An application quotes asset A in units of B using two USD feeds. The result can be wrong by a factor of one hundred if their integer answers have different precision.
Cancel the common quote currency
Suppose A costs 12.50 USD at eight decimals and B costs 2.50 USD at six. Dividing their normalized prices gives five units of B per A. The example returns 5,000,000 millionths of B. Carry the scales through the fraction and divide last to limit truncation. Obtain the actual precisions from the two chosen proxies.
const aUsd = 1250000000n, aScale = 8n;
const bUsd = 2500000n, bScale = 6n;
const microB = aUsd * 10n**(bScale + 6n) / (bUsd * 10n**aScale);
console.log(microB.toString());
Check the two observations before combining them
Read both feeds in one block context and inspect the update timestamp of each: a common block does not mean both prices were observed simultaneously. For positive asset prices, reject zero or negative inputs and specify rounding for the final quote. In a fixed-width implementation consider intermediate overflow even when the final ratio is small. Reversing the pair gives the reciprocal quote, which needs its own unit label.