1

I am integrating payment transaction for two blockchains , ethereum and solana using Web3.js. But how to automatically convert the dollar price to Ethereum and Solana respectively?

    Ethereum payment code
----------------------------------
const amountEth=0.00001
            
                Web3.eth.sendTransaction({
                    to: paymentAddress,
                    value: Web3.toWei(amountEth, 'ether')
                }, (err, transactionId)=>{
                    if(err){
                        
                    }else{
                        
                    }
                })

Solana Payment Code
-------------------------
var transaction = new solanaWeb3.Transaction().add(
                                solanaWeb3.SystemProgram.transfer({
                                    fromPubkey: resp.publicKey, 
                                    toPubkey: recieverWallet, 
                                    lamports: 0.00000000001 * solanaWeb3.LAMPORTS_PER_SOL,
                                }),
                            );

2 Answers2

1

Assets value in dollar are kinda real-world data, you need to go through one of the following options,

1 - Define a state variable to store the current rate (i.e SOL/USD or ETH/USD) in your code and update it periodically by your own, which is not really a good way.

2 - Using Oracles like Chainlink price feed which is available on both Ethereum and Solana

Using either of options, you then need to have a public method in your contract to return the current rate and call it in your frontend UI to set the price before user submits the transaction.

Abi Ji
  • 184
  • 1
  • 4
0

Chainlink price feed is one solution. Another solution is you write code in the front-end. This is a react hook example.

import useSWR from "swr"

const coingeckoURL = "https://api.coingecko.com/api/v3/coins/ethereum?localization=false&tickers=false&community_data=false&developer_data=false&sparkline=false"
export const ITEM_PRICE = 15

const fetcher = async url => {
  const res = await fetch(url)
  const json = await res.json()
  // console.log(json) to see the api result
  return json.market_data.current_price.usd ?? null
}

export const useItemPriceInEth = () => {
  const { data, ...rest } = useSWR(
    coingeckoURL,
    fetcher,
    { refreshInterval: 1000 }
  )
  // The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
  const perItem = (data && (ITEM_PRICE / Number(data)).toFixed(6)) ?? null
  return { eth: { data, perItem, ...rest}}
}
Yilmaz
  • 35,338
  • 10
  • 157
  • 202