import crypto from 'crypto' ; import nfetch from 'node-fetch' ; const AbiCoder = require ( 'web3-eth-abi' ) ; interface DecodedMessage { key : string ; price : string ; timestamp : string ; } interface LocalSignature { hash : string ; timestamp : string ; } interface CoinbaseReport { message ? : string ; timestamp : string ; messages : string [ ] ; signatures : string [ ] ; prices : { [ i ] : string ; } ; } export default class CoinbaseReporter { private readonly coinbaseEndpoint : string ; private readonly coinbaseKey : string ; private readonly coinbaseSecret : string ; private readonly coinbasePassphrase : string ; constructor ( coinbaseEndpoint , coinbaseKey , coinbaseSecret , coinbasePassphrase ) { this . coinbaseEndpoint = coinbaseEndpoint ; this . coinbaseKey = coinbaseKey ; this . coinbaseSecret = coinbaseSecret ; this . coinbasePassphrase = coinbasePassphrase ; } public static decode ( message ) { const { 1 : timestamp , 2 : key , 3 : price , } = AbiCoder . decodeParameters ( [ 'string' , 'uint64' , 'string' , 'uint64' ] , message ) ; return { key : key , price : price , timestamp : timestamp , } ; } protected async fetchCoinbasePrices ( ) { const path = '/oracle' ; const method = 'GET' ; const sig = this . localSignature ( path , method ) ; const headers = { 'Content-Type' : 'application/json' , Accept : 'application/json' , 'CB-ACCESS-KEY' : this . coinbaseKey , 'CB-ACCESS-SIGN' : sig . hash , 'CB-ACCESS-TIMESTAMP' : sig . timestamp , 'CB-ACCESS-PASSPHRASE' : this . coinbasePassphrase , } ; const res = await nfetch ( this . coinbaseEndpoint + path , { method : method , headers : headers , } ) ; return res . json ( ) ; } private localSignature ( path = '/oracle' , method = 'GET' , body = '' ) { const timestamp = ( Date . now ( ) / 1000 ) . toFixed ( 0 ) ; const prehash = timestamp + method . toUpperCase ( ) + path + body ; const hash = crypto . createHmac ( 'sha256' , Buffer . from ( this . coinbaseSecret , 'base64' ) ) . update ( prehash ) . digest ( 'base64' ) ; return { hash : hash , timestamp : timestamp , } ; } }