Skip to content

Instantly share code, notes, and snippets.

@0x62
Created September 4, 2021 13:42
Show Gist options
  • Save 0x62/39150fd2f92ee44860f5e0f754e9e1bd to your computer and use it in GitHub Desktop.
Save 0x62/39150fd2f92ee44860f5e0f754e9e1bd to your computer and use it in GitHub Desktop.
Hacky workaround
import { ethers } from 'ethers'
class RpcApi {
constructor({ endpoint, address, abi }) {
this._endpoint = endpoint
this._address = null
this._abi = null
this._id = 0
if (abi && address) this.setContract({ address, abi })
}
get _nextId() {
return ++this._id
}
setContract({ address, abi }) {
this._address = address
this._abi = abi
this._iface = new ethers.utils.Interface(abi)
}
async balanceOf(address) {
const balance = await this._call('balanceOf', [address])
return parseInt(balance)
}
async _call(fn, params) {
return this._fetch('eth_call', [{
to: this._address,
data: this._iface.encodeFunctionData(fn, params)
}])
}
async _fetch(method, params = []) {
const res = await fetch(this._endpoint, {
method: 'POST',
body: JSON.stringify({
jsonrpc: '2.0',
id: this._nextId,
method,
params,
})
})
const { result, error } = await res.json()
if (error) {
throw new Error(`RPC error: ${error}`)
}
return result
}
}
export default RpcApi
const api = new RpcApi({
endpoint: `https://eth-rinkeby.alchemyapi.io/v2/${ALCHEMY_KEY}`,
address: contractAddress,
abi,
})
const balance = await api.balanceOf(address)
@stevenpack
Copy link

Hey @0x62, this didn't work for me calling any other methods, unless I included the block, like this:

async _call(fn, params) {
      return await this._fetch('eth_call', [
         {
            to: this._address,
            data: this._iface.encodeFunctionData(fn, params),
         },
         "latest"
      ]);
    }

Just adding latest

@stevenpack
Copy link

That got me going though, thanks for posting!

@nwhite89
Copy link

nwhite89 commented Feb 4, 2022

Trying to use this with BSC and just continually get a 403 forbidden :( any change you've tried with BSC?

@0x62
Copy link
Author

0x62 commented Feb 4, 2022

@nwhite89 403 probably means your API key is wrong, or you've used the quota of your RPC provider

@nwhite89
Copy link

nwhite89 commented Feb 5, 2022

Thanks @0x62 yeah I was using the BSC open data seed which requires cors. Which from what I can see you can't apply with cloudflare workers 😢

@nwhite89
Copy link

nwhite89 commented Feb 5, 2022

Just incase anyone else comes here trying to do it with BSC I switched to use https://moralis.io/ for now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment