2019-05-14 18:48:48 -04:00
"use strict" ;
2019-11-20 18:57:38 +09:00
var _ _awaiter = ( this && this . _ _awaiter ) || function ( thisArg , _arguments , P , generator ) {
function adopt ( value ) { return value instanceof P ? value : new P ( function ( resolve ) { resolve ( value ) ; } ) ; }
return new ( P || ( P = Promise ) ) ( function ( resolve , reject ) {
function fulfilled ( value ) { try { step ( generator . next ( value ) ) ; } catch ( e ) { reject ( e ) ; } }
function rejected ( value ) { try { step ( generator [ "throw" ] ( value ) ) ; } catch ( e ) { reject ( e ) ; } }
function step ( result ) { result . done ? resolve ( result . value ) : adopt ( result . value ) . then ( fulfilled , rejected ) ; }
step ( ( generator = generator . apply ( thisArg , _arguments || [ ] ) ) . next ( ) ) ;
} ) ;
} ;
2020-11-22 22:44:33 -05:00
import { hexlify , hexValue , isHexString } from "@ethersproject/bytes" ;
2019-08-25 02:39:20 -04:00
import { deepCopy , defineReadOnly } from "@ethersproject/properties" ;
2021-04-17 22:41:09 -04:00
import { accessListify } from "@ethersproject/transactions" ;
2019-08-25 02:39:20 -04:00
import { fetchJson } from "@ethersproject/web" ;
2020-07-14 02:33:30 -04:00
import { showThrottleMessage } from "./formatter" ;
2019-08-25 02:39:20 -04:00
import { Logger } from "@ethersproject/logger" ;
import { version } from "./_version" ;
const logger = new Logger ( version ) ;
import { BaseProvider } from "./base-provider" ;
2019-05-14 18:48:48 -04:00
// The transaction has already been sanitized by the calls in Provider
2020-10-22 20:01:18 -04:00
function getTransactionPostData ( transaction ) {
const result = { } ;
2019-08-25 02:39:20 -04:00
for ( let key in transaction ) {
2019-05-14 18:48:48 -04:00
if ( transaction [ key ] == null ) {
continue ;
}
2021-03-30 15:22:45 -04:00
let value = transaction [ key ] ;
2020-10-22 20:01:18 -04:00
// Quantity-types require no leading zero, unless 0
2021-03-30 15:22:45 -04:00
if ( { type : true , gasLimit : true , gasPrice : true , nonce : true , value : true } [ key ] ) {
value = hexValue ( hexlify ( value ) ) ;
}
else if ( key === "accessList" ) {
2021-05-17 16:19:36 -04:00
value = "[" + accessListify ( value ) . map ( ( set ) => {
2021-04-17 22:41:09 -04:00
return ` {address:" ${ set . address } ",storageKeys:[" ${ set . storageKeys . join ( '","' ) } "]} ` ;
} ) . join ( "," ) + "]" ;
2021-03-30 15:22:45 -04:00
}
else {
value = hexlify ( value ) ;
2019-05-14 18:48:48 -04:00
}
2020-10-22 20:01:18 -04:00
result [ key ] = value ;
2019-05-14 18:48:48 -04:00
}
2020-10-22 20:01:18 -04:00
return result ;
2019-05-14 18:48:48 -04:00
}
function getResult ( result ) {
// getLogs, getHistory have weird success responses
if ( result . status == 0 && ( result . message === "No records found" || result . message === "No transactions found" ) ) {
return result . result ;
}
if ( result . status != 1 || result . message != "OK" ) {
2019-11-20 18:57:38 +09:00
const error = new Error ( "invalid response" ) ;
2019-05-14 18:48:48 -04:00
error . result = JSON . stringify ( result ) ;
2020-07-14 02:33:30 -04:00
if ( ( result . result || "" ) . toLowerCase ( ) . indexOf ( "rate limit" ) >= 0 ) {
error . throttleRetry = true ;
}
2019-05-14 18:48:48 -04:00
throw error ;
}
return result . result ;
}
function getJsonResult ( result ) {
2020-07-14 02:33:30 -04:00
// This response indicates we are being throttled
if ( result && result . status == 0 && result . message == "NOTOK" && ( result . result || "" ) . toLowerCase ( ) . indexOf ( "rate limit" ) >= 0 ) {
const error = new Error ( "throttled response" ) ;
error . result = JSON . stringify ( result ) ;
error . throttleRetry = true ;
throw error ;
}
2019-05-14 18:48:48 -04:00
if ( result . jsonrpc != "2.0" ) {
// @TODO: not any
2019-11-20 18:57:38 +09:00
const error = new Error ( "invalid response" ) ;
2019-05-14 18:48:48 -04:00
error . result = JSON . stringify ( result ) ;
throw error ;
}
if ( result . error ) {
// @TODO: not any
2019-11-20 18:57:38 +09:00
const error = new Error ( result . error . message || "unknown error" ) ;
2019-05-14 18:48:48 -04:00
if ( result . error . code ) {
error . code = result . error . code ;
}
if ( result . error . data ) {
error . data = result . error . data ;
}
throw error ;
}
return result . result ;
}
// The blockTag was normalized as a string by the Provider pre-perform operations
function checkLogTag ( blockTag ) {
if ( blockTag === "pending" ) {
throw new Error ( "pending not supported" ) ;
}
if ( blockTag === "latest" ) {
return blockTag ;
}
return parseInt ( blockTag . substring ( 2 ) , 16 ) ;
}
2020-02-17 20:22:33 -05:00
const defaultApiKey = "9D13ZE7XSBTJ94N9BNJ2MA33VMAY2YPIRB" ;
2020-09-16 03:08:36 -04:00
function checkError ( method , error , transaction ) {
2020-11-22 22:44:33 -05:00
// Undo the "convenience" some nodes are attempting to prevent backwards
// incompatibility; maybe for v6 consider forwarding reverts as errors
if ( method === "call" && error . code === Logger . errors . SERVER _ERROR ) {
const e = error . error ;
if ( e && e . message . match ( "reverted" ) && isHexString ( e . data ) ) {
return e . data ;
}
}
2020-09-16 03:08:36 -04:00
// Get the message from any nested error structure
2020-09-11 02:10:58 -04:00
let message = error . message ;
2020-09-16 03:08:36 -04:00
if ( error . code === Logger . errors . SERVER _ERROR ) {
if ( error . error && typeof ( error . error . message ) === "string" ) {
message = error . error . message ;
}
else if ( typeof ( error . body ) === "string" ) {
message = error . body ;
}
else if ( typeof ( error . responseText ) === "string" ) {
message = error . responseText ;
}
}
message = ( message || "" ) . toLowerCase ( ) ;
// "Insufficient funds. The account you tried to send transaction from does not have enough funds. Required 21464000000000 and got: 0"
if ( message . match ( /insufficient funds/ ) ) {
logger . throwError ( "insufficient funds for intrinsic transaction cost" , Logger . errors . INSUFFICIENT _FUNDS , {
error , method , transaction
} ) ;
}
// "Transaction with the same hash was already imported."
if ( message . match ( /same hash was already imported|transaction nonce is too low/ ) ) {
logger . throwError ( "nonce has already been used" , Logger . errors . NONCE _EXPIRED , {
error , method , transaction
} ) ;
}
// "Transaction gas price is too low. There is another transaction with same nonce in the queue. Try increasing the gas price or incrementing the nonce."
if ( message . match ( /another transaction with same nonce/ ) ) {
logger . throwError ( "replacement fee too low" , Logger . errors . REPLACEMENT _UNDERPRICED , {
error , method , transaction
} ) ;
2020-09-11 02:10:58 -04:00
}
if ( message . match ( /execution failed due to an exception/ ) ) {
logger . throwError ( "cannot estimate gas; transaction may fail or may require manual gas limit" , Logger . errors . UNPREDICTABLE _GAS _LIMIT , {
2020-09-16 03:08:36 -04:00
error , method , transaction
2020-09-11 02:10:58 -04:00
} ) ;
}
throw error ;
}
2019-08-25 02:39:20 -04:00
export class EtherscanProvider extends BaseProvider {
constructor ( network , apiKey ) {
logger . checkNew ( new . target , EtherscanProvider ) ;
super ( network ) ;
2021-05-17 16:19:36 -04:00
defineReadOnly ( this , "baseUrl" , this . getBaseUrl ( ) ) ;
defineReadOnly ( this , "apiKey" , apiKey || defaultApiKey ) ;
}
getBaseUrl ( ) {
switch ( this . network ? this . network . name : "invalid" ) {
2019-05-14 18:48:48 -04:00
case "homestead" :
2021-05-17 16:19:36 -04:00
return "https:/\/api.etherscan.io" ;
2019-05-14 18:48:48 -04:00
case "ropsten" :
2021-05-17 16:19:36 -04:00
return "https:/\/api-ropsten.etherscan.io" ;
2019-05-14 18:48:48 -04:00
case "rinkeby" :
2021-05-17 16:19:36 -04:00
return "https:/\/api-rinkeby.etherscan.io" ;
2019-05-14 18:48:48 -04:00
case "kovan" :
2021-05-17 16:19:36 -04:00
return "https:/\/api-kovan.etherscan.io" ;
2019-05-14 18:48:48 -04:00
case "goerli" :
2021-05-17 16:19:36 -04:00
return "https:/\/api-goerli.etherscan.io" ;
2019-05-14 18:48:48 -04:00
default :
}
2021-05-17 16:19:36 -04:00
return logger . throwArgumentError ( "unsupported network" , "network" , name ) ;
}
getUrl ( module , params ) {
const query = Object . keys ( params ) . reduce ( ( accum , key ) => {
const value = params [ key ] ;
if ( value != null ) {
accum += ` & ${ key } = ${ value } ` ;
}
return accum ;
} , "" ) ;
const apiKey = ( ( this . apiKey ) ? ` &apikey= ${ this . apiKey } ` : "" ) ;
return ` ${ this . baseUrl } /api?module= ${ module } ${ query } ${ apiKey } ` ;
}
getPostUrl ( ) {
return ` ${ this . baseUrl } /api ` ;
}
getPostData ( module , params ) {
params . module = module ;
params . apikey = this . apiKey ;
return params ;
}
fetch ( module , params , post ) {
return _ _awaiter ( this , void 0 , void 0 , function * ( ) {
const url = ( post ? this . getPostUrl ( ) : this . getUrl ( module , params ) ) ;
const payload = ( post ? this . getPostData ( module , params ) : null ) ;
const procFunc = ( module === "proxy" ) ? getJsonResult : getResult ;
this . emit ( "debug" , {
action : "request" ,
request : url ,
provider : this
} ) ;
const connection = {
url : url ,
throttleSlotInterval : 1000 ,
throttleCallback : ( attempt , url ) => {
if ( this . isCommunityResource ( ) ) {
showThrottleMessage ( ) ;
}
return Promise . resolve ( true ) ;
}
} ;
let payloadStr = null ;
if ( payload ) {
connection . headers = { "content-type" : "application/x-www-form-urlencoded; charset=UTF-8" } ;
payloadStr = Object . keys ( payload ) . map ( ( key ) => {
return ` ${ key } = ${ payload [ key ] } ` ;
} ) . join ( "&" ) ;
}
const result = yield fetchJson ( connection , payloadStr , procFunc || getJsonResult ) ;
this . emit ( "debug" , {
action : "response" ,
request : url ,
response : deepCopy ( result ) ,
provider : this
} ) ;
return result ;
} ) ;
2019-05-14 18:48:48 -04:00
}
2020-05-03 17:53:58 -04:00
detectNetwork ( ) {
return _ _awaiter ( this , void 0 , void 0 , function * ( ) {
return this . network ;
} ) ;
}
2019-08-25 02:39:20 -04:00
perform ( method , params ) {
2019-11-20 18:57:38 +09:00
const _super = Object . create ( null , {
perform : { get : ( ) => super . perform }
} ) ;
return _ _awaiter ( this , void 0 , void 0 , function * ( ) {
switch ( method ) {
case "getBlockNumber" :
2021-05-17 16:19:36 -04:00
return this . fetch ( "proxy" , { action : "eth_blockNumber" } ) ;
2019-11-20 18:57:38 +09:00
case "getGasPrice" :
2021-05-17 16:19:36 -04:00
return this . fetch ( "proxy" , { action : "eth_gasPrice" } ) ;
2019-11-20 18:57:38 +09:00
case "getBalance" :
// Returns base-10 result
2021-05-17 16:19:36 -04:00
return this . fetch ( "account" , {
action : "balance" ,
address : params . address ,
tag : params . blockTag
} ) ;
2019-11-20 18:57:38 +09:00
case "getTransactionCount" :
2021-05-17 16:19:36 -04:00
return this . fetch ( "proxy" , {
action : "eth_getTransactionCount" ,
address : params . address ,
tag : params . blockTag
} ) ;
2019-11-20 18:57:38 +09:00
case "getCode" :
2021-05-17 16:19:36 -04:00
return this . fetch ( "proxy" , {
action : "eth_getCode" ,
address : params . address ,
tag : params . blockTag
} ) ;
2019-11-20 18:57:38 +09:00
case "getStorageAt" :
2021-05-17 16:19:36 -04:00
return this . fetch ( "proxy" , {
action : "eth_getStorageAt" ,
address : params . address ,
position : params . position ,
tag : params . blockTag
} ) ;
2019-11-20 18:57:38 +09:00
case "sendTransaction" :
2021-05-17 16:19:36 -04:00
return this . fetch ( "proxy" , {
2020-10-22 20:01:18 -04:00
action : "eth_sendRawTransaction" ,
2021-05-17 16:19:36 -04:00
hex : params . signedTransaction
} , true ) . catch ( ( error ) => {
2020-09-16 03:08:36 -04:00
return checkError ( "sendTransaction" , error , params . signedTransaction ) ;
2019-11-20 18:57:38 +09:00
} ) ;
case "getBlock" :
if ( params . blockTag ) {
2021-05-17 16:19:36 -04:00
return this . fetch ( "proxy" , {
action : "eth_getBlockByNumber" ,
tag : params . blockTag ,
boolean : ( params . includeTransactions ? "true" : "false" )
} ) ;
2019-05-14 18:48:48 -04:00
}
2020-04-23 23:35:39 -04:00
throw new Error ( "getBlock by blockHash not implemented" ) ;
2019-11-20 18:57:38 +09:00
case "getTransaction" :
2021-05-17 16:19:36 -04:00
return this . fetch ( "proxy" , {
action : "eth_getTransactionByHash" ,
txhash : params . transactionHash
} ) ;
2019-11-20 18:57:38 +09:00
case "getTransactionReceipt" :
2021-05-17 16:19:36 -04:00
return this . fetch ( "proxy" , {
action : "eth_getTransactionReceipt" ,
txhash : params . transactionHash
} ) ;
2019-11-20 18:57:38 +09:00
case "call" : {
if ( params . blockTag !== "latest" ) {
throw new Error ( "EtherscanProvider does not support blockTag for call" ) ;
2019-05-14 18:48:48 -04:00
}
2020-10-22 20:01:18 -04:00
const postData = getTransactionPostData ( params . transaction ) ;
postData . module = "proxy" ;
postData . action = "eth_call" ;
2020-09-11 02:10:58 -04:00
try {
2021-05-17 16:19:36 -04:00
return yield this . fetch ( "proxy" , postData , true ) ;
2020-09-11 02:10:58 -04:00
}
catch ( error ) {
2020-09-16 03:08:36 -04:00
return checkError ( "call" , error , params . transaction ) ;
2020-09-11 02:10:58 -04:00
}
2019-05-14 18:48:48 -04:00
}
2019-11-20 18:57:38 +09:00
case "estimateGas" : {
2020-10-22 20:01:18 -04:00
const postData = getTransactionPostData ( params . transaction ) ;
postData . module = "proxy" ;
postData . action = "eth_estimateGas" ;
2020-09-11 02:10:58 -04:00
try {
2021-05-17 16:19:36 -04:00
return yield this . fetch ( "proxy" , postData , true ) ;
2020-09-11 02:10:58 -04:00
}
catch ( error ) {
2020-09-16 03:08:36 -04:00
return checkError ( "estimateGas" , error , params . transaction ) ;
2020-09-11 02:10:58 -04:00
}
2019-05-14 18:48:48 -04:00
}
2019-11-20 18:57:38 +09:00
case "getLogs" : {
2021-05-17 16:19:36 -04:00
const args = { action : "getLogs" } ;
2019-05-14 18:48:48 -04:00
if ( params . filter . fromBlock ) {
2021-05-17 16:19:36 -04:00
args . fromBlock = checkLogTag ( params . filter . fromBlock ) ;
2019-05-14 18:48:48 -04:00
}
if ( params . filter . toBlock ) {
2021-05-17 16:19:36 -04:00
args . toBlock = checkLogTag ( params . filter . toBlock ) ;
2019-05-14 18:48:48 -04:00
}
if ( params . filter . address ) {
2021-05-17 16:19:36 -04:00
args . address = params . filter . address ;
2019-05-14 18:48:48 -04:00
}
// @TODO: We can handle slightly more complicated logs using the logs API
if ( params . filter . topics && params . filter . topics . length > 0 ) {
if ( params . filter . topics . length > 1 ) {
2019-11-20 18:57:38 +09:00
logger . throwError ( "unsupported topic count" , Logger . errors . UNSUPPORTED _OPERATION , { topics : params . filter . topics } ) ;
2019-05-14 18:48:48 -04:00
}
2019-11-20 18:57:38 +09:00
if ( params . filter . topics . length === 1 ) {
const topic0 = params . filter . topics [ 0 ] ;
if ( typeof ( topic0 ) !== "string" || topic0 . length !== 66 ) {
logger . throwError ( "unsupported topic format" , Logger . errors . UNSUPPORTED _OPERATION , { topic0 : topic0 } ) ;
}
2021-05-17 16:19:36 -04:00
args . topic0 = topic0 ;
2019-05-14 18:48:48 -04:00
}
}
2021-05-17 16:19:36 -04:00
const logs = yield this . fetch ( "logs" , args ) ;
2019-11-20 18:57:38 +09:00
// Cache txHash => blockHash
2020-10-22 21:55:40 -04:00
let blocks = { } ;
2019-11-20 18:57:38 +09:00
// Add any missing blockHash to the logs
for ( let i = 0 ; i < logs . length ; i ++ ) {
const log = logs [ i ] ;
if ( log . blockHash != null ) {
continue ;
}
2020-10-22 21:55:40 -04:00
if ( blocks [ log . blockNumber ] == null ) {
const block = yield this . getBlock ( log . blockNumber ) ;
if ( block ) {
blocks [ log . blockNumber ] = block . hash ;
2019-05-14 18:48:48 -04:00
}
2019-11-20 18:57:38 +09:00
}
2020-10-22 21:55:40 -04:00
log . blockHash = blocks [ log . blockNumber ] ;
2019-11-20 18:57:38 +09:00
}
return logs ;
2019-05-14 18:48:48 -04:00
}
2019-11-20 18:57:38 +09:00
case "getEtherPrice" :
if ( this . network . name !== "homestead" ) {
return 0.0 ;
}
2021-05-17 16:19:36 -04:00
return parseFloat ( ( yield this . fetch ( "stats" , { action : "ethprice" } ) ) . ethusd ) ;
2019-11-20 18:57:38 +09:00
default :
break ;
}
return _super . perform . call ( this , method , params ) ;
} ) ;
2019-08-25 02:39:20 -04:00
}
2021-05-17 16:19:36 -04:00
// Note: The `page` page parameter only allows pagination within the
// 10,000 window abailable without a page and offset parameter
// Error: Result window is too large, PageNo x Offset size must
// be less than or equal to 10000
2019-08-25 02:39:20 -04:00
getHistory ( addressOrName , startBlock , endBlock ) {
2021-05-17 16:19:36 -04:00
return _ _awaiter ( this , void 0 , void 0 , function * ( ) {
const params = {
action : "txlist" ,
address : ( yield this . resolveName ( addressOrName ) ) ,
startblock : ( ( startBlock == null ) ? 0 : startBlock ) ,
endblock : ( ( endBlock == null ) ? 99999999 : endBlock ) ,
sort : "asc"
2020-07-14 02:33:30 -04:00
} ;
2021-05-17 16:19:36 -04:00
const result = yield this . fetch ( "account" , params ) ;
return result . map ( ( tx ) => {
[ "contractAddress" , "to" ] . forEach ( function ( key ) {
if ( tx [ key ] == "" ) {
delete tx [ key ] ;
2019-05-14 18:48:48 -04:00
}
} ) ;
2021-05-17 16:19:36 -04:00
if ( tx . creates == null && tx . contractAddress != null ) {
tx . creates = tx . contractAddress ;
}
const item = this . formatter . transactionResponse ( tx ) ;
if ( tx . timeStamp ) {
item . timestamp = parseInt ( tx . timeStamp ) ;
}
return item ;
2019-05-14 18:48:48 -04:00
} ) ;
} ) ;
2019-08-25 02:39:20 -04:00
}
2020-10-07 20:10:50 -04:00
isCommunityResource ( ) {
return ( this . apiKey === defaultApiKey ) ;
}
2019-08-25 02:39:20 -04:00
}
2020-07-13 08:03:56 -04:00
//# sourceMappingURL=etherscan-provider.js.map