ethereumjs-util#toChecksumAddress TypeScript Examples

The following examples show how to use ethereumjs-util#toChecksumAddress. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: address.ts    From openzeppelin-upgrades with MIT License 6 votes vote down vote up
/**
 * Parses an address from a hex string which may come from storage or a returned address via eth_call.
 *
 * @param addressString The address hex string.
 * @returns The parsed checksum address, or undefined if the input string is not an address.
 */
export function parseAddress(addressString: string): string | undefined {
  const buf = Buffer.from(addressString.replace(/^0x/, ''), 'hex');
  if (!buf.slice(0, 12).equals(Buffer.alloc(12, 0))) {
    return undefined;
  }
  const address = '0x' + buf.toString('hex', 12, 32); // grab the last 20 bytes
  return toChecksumAddress(address);
}
Example #2
Source File: VmProxy.ts    From remix-project with MIT License 6 votes vote down vote up
async txWillProcess (data) {
    this.incr++
    this.processingHash = bufferToHex(data.hash())
    this.vmTraces[this.processingHash] = {
      gas: '0x0',
      return: '0x0',
      structLogs: []
    }
    const tx = {}
    tx['hash'] = this.processingHash
    tx['from'] = toChecksumAddress(data.getSenderAddress().toString())
    if (data.to) {
      tx['to'] = toChecksumAddress(data.to.toString())
    }
    this.processingAddress = tx['to']
    tx['input'] = bufferToHex(data.data)
    tx['gas'] = data.gasLimit.toString(10)
    if (data.value) {
      tx['value'] = data.value.toString(10)
    }
    this.txs[this.processingHash] = tx
    this.txsReceipt[this.processingHash] = tx
    this.storageCache[this.processingHash] = {}
    if (data.to) {
      try {
        const storage = await this.vm.stateManager.dumpStorage(data.to)
        this.storageCache[this.processingHash][tx['to']] = storage
        this.lastProcessedStorageTxHash[tx['to']] = this.processingHash
      } catch (e) {
        console.log(e)
      }
    }
    this.processingIndex = 0
  }
Example #3
Source File: VmProxy.ts    From remix-project with MIT License 6 votes vote down vote up
storageRangeAt (blockNumber, txIndex, address, start, maxLength, cb) {
    // we don't use the range params here
    address = toChecksumAddress(address)

    let txHash
    if (txIndex === 'latest') {
      txHash = this.lastProcessedStorageTxHash[address]
    } else {
      const block = this.vmContext.blocks[blockNumber]
      txHash = '0x' + block.transactions[txIndex].hash().toString('hex')
    }
    
    

    if (this.storageCache[txHash] && this.storageCache[txHash][address]) {
      const storage = this.storageCache[txHash][address]
      return cb(null, {
        storage: JSON.parse(JSON.stringify(storage)),
        nextKey: null
      })
    }
    // Before https://github.com/ethereum/remix-project/pull/1703, it used to throw error as
    // 'unable to retrieve storage ' + txIndex + ' ' + address
    cb(null, { storage: {} })
  }
Example #4
Source File: accounts.ts    From remix-project with MIT License 6 votes vote down vote up
_addAccount (privateKey, balance) {
    return new Promise((resolve, reject) => {
      privateKey = Buffer.from(privateKey, 'hex')
      const address: Buffer = privateToAddress(privateKey)
      const addressStr = toChecksumAddress('0x' + address.toString('hex'))
      this.accounts[addressStr] = { privateKey, nonce: 0 }
      this.accountsKeys[addressStr] = '0x' + privateKey.toString('hex')

      const stateManager = this.vmContext.vm().stateManager
      stateManager.getAccount(Address.fromString(addressStr)).then((account) => {
        account.balance = new BN(balance.replace('0x', '') || 'f00000000000000001', 16)
        stateManager.putAccount(Address.fromString(addressStr), account).catch((error) => {
          reject(error)
        }).then(() => {
          resolve({})
        })
      }).catch((error) => {
        reject(error)
      })
    })
  }
Example #5
Source File: accounts.ts    From remix-project with MIT License 6 votes vote down vote up
eth_sign (payload, cb) {
    const address = payload.params[0]
    const message = payload.params[1]

    const privateKey = this.accountsKeys[toChecksumAddress(address)]
    if (!privateKey) {
      return cb(new Error('unknown account'))
    }
    const account = this.web3.eth.accounts.privateKeyToAccount(privateKey)

    const data = account.sign(message)

    cb(null, data.signature)
  }
Example #6
Source File: transactions.ts    From remix-project with MIT License 6 votes vote down vote up
eth_sendTransaction (payload, cb) {
    // from might be lowercased address (web3)
    if (payload.params && payload.params.length > 0 && payload.params[0].from) {
      payload.params[0].from = toChecksumAddress(payload.params[0].from)
    }
    processTx(this.txRunnerInstance, payload, false, (error, result) => {
      if (!error && result) {
        this.vmContext.addBlock(result.block)
        const hash = '0x' + result.tx.hash().toString('hex')
        this.vmContext.trackTx(hash, result.block, result.tx)
        this.vmContext.trackExecResult(hash, result.result.execResult)
        return cb(null, result.transactionHash)
      }
      cb(error)
    })
  }
Example #7
Source File: transactions.ts    From remix-project with MIT License 6 votes vote down vote up
eth_estimateGas (payload, cb) {
    // from might be lowercased address (web3)
    if (payload.params && payload.params.length > 0 && payload.params[0].from) {
      payload.params[0].from = toChecksumAddress(payload.params[0].from)
    }
    if (payload.params && payload.params.length > 0 && payload.params[0].to) {
      payload.params[0].to = toChecksumAddress(payload.params[0].to)
    }

    payload.params[0].gas = 10000000 * 10

    processTx(this.txRunnerInstance, payload, true, (error, { result }) => {
      if (error) return cb(error)
      if (result.status === '0x0') {
        try {
          const msg = result.execResult.returnValue
          const abiCoder = new ethers.utils.AbiCoder()
          const reason = abiCoder.decode(['string'], msg.slice(4))[0]
          return cb('revert ' + reason)
        } catch (e) {
          return cb(e.message)
        }
      }
      let gasUsed = result.execResult.gasUsed.toNumber()
      if (result.execResult.gasRefund) {
        gasUsed += result.execResult.gasRefund.toNumber()
      }
      cb(null, Math.ceil(gasUsed + (15 * gasUsed) / 100))
    })
  }
Example #8
Source File: transactions.ts    From remix-project with MIT License 6 votes vote down vote up
eth_call (payload, cb) {
    // from might be lowercased address (web3)
    if (payload.params && payload.params.length > 0 && payload.params[0].from) {
      payload.params[0].from = toChecksumAddress(payload.params[0].from)
    }
    if (payload.params && payload.params.length > 0 && payload.params[0].to) {
      payload.params[0].to = toChecksumAddress(payload.params[0].to)
    }

    payload.params[0].value = undefined

    const tag = payload.params[0].timestamp // e2e reference

    processTx(this.txRunnerInstance, payload, true, (error, result) => {
      if (!error && result) {
        this.vmContext.addBlock(result.block)
        const hash = '0x' + result.tx.hash().toString('hex')
        this.vmContext.trackTx(hash, result.block, result.tx)
        this.vmContext.trackExecResult(hash, result.result.execResult)
        this.tags[tag] = result.transactionHash
        // calls are not supposed to return a transaction hash. we do this for keeping track of it and allowing debugging calls.
        const returnValue = `0x${result.result.execResult.returnValue.toString('hex') || '0'}`
        return cb(null, returnValue)
      }
      cb(error)
    })
  }
Example #9
Source File: checksum.ts    From beefy-api with MIT License 5 votes vote down vote up
validateAllAddressesChecksum = (): InvalidAddressInfo[][] => {
  const invalidPlatformAddressList: InvalidAddressInfo[] = [];
  const invalidTokenAddressList: InvalidAddressInfo[] = [];

  const chains = Object.entries(addressBook);
  for (const chain of chains) {
    const chainName = chain[0] as Exclude<keyof typeof addressBook, ChainId>;
    const { platforms, tokens } = chain[1];
    const platformEntries = Object.entries(platforms);

    // validate platforms
    for (const platform of platformEntries) {
      const platformName = platform[0];
      const addresses = platform[1];

      for (const addressEntry of Object.entries(addresses)) {
        const addressName = addressEntry[0];
        const address = addressEntry[1] as string;

        const isValid = isValidChecksumAddress(address);
        const correctAddress = address ? toChecksumAddress(address) : '';
        if (!isValid) {
          invalidPlatformAddressList.push({
            chainName,
            platformName,
            address,
            addressName,
            correctAddress,
          });
        }
      }
    }

    const tokenInfoEntries = Object.entries(tokens);
    // validate token addresses
    for (const tokenInfoEntry of tokenInfoEntries) {
      const tokenName = tokenInfoEntry[0];
      const tokenInfo = tokenInfoEntry[1];
      const address = tokenInfo.address;

      const isValid = isValidChecksumAddress(address);
      const correctAddress = address ? toChecksumAddress(address) : '';
      if (!isValid) {
        invalidTokenAddressList.push({
          chainName,
          addressName: tokenName,
          address,
          correctAddress,
        });
      }
    }
  }

  return [invalidPlatformAddressList, invalidTokenAddressList];
}
Example #10
Source File: toChecksumTokenList.ts    From beefy-api with MIT License 5 votes vote down vote up
toChecksumTokenList = (tokens: Token[]): void => {
  for (const token of tokens) {
    token.address = toChecksumAddress(token.address);
  }
}
Example #11
Source File: common.ts    From react-celo with MIT License 5 votes vote down vote up
testAddress = toChecksumAddress(account)
Example #12
Source File: VmProxy.ts    From remix-project with MIT License 5 votes vote down vote up
async txProcessed (data) {
    const lastOp = this.vmTraces[this.processingHash].structLogs[this.processingIndex - 1]
    if (lastOp) {
      lastOp.error = lastOp.op !== 'RETURN' && lastOp.op !== 'STOP' && lastOp.op !== 'DESTRUCT'
    }
    const gasUsed = '0x' + data.gasUsed.toString(16)
    this.vmTraces[this.processingHash].gas = gasUsed
    this.txsReceipt[this.processingHash].gasUsed = gasUsed
    const logs = []
    for (const l in data.execResult.logs) {
      const log = data.execResult.logs[l]
      const topics = []
      if (log[1].length > 0) {
        for (const k in log[1]) {
          topics.push('0x' + log[1][k].toString('hex'))
        }
      } else {
        topics.push('0x')
      }
      logs.push({
        address: '0x' + log[0].toString('hex'),
        data: '0x' + log[2].toString('hex'),
        topics: topics,
        rawVMResponse: log
      })
    }
    this.txsReceipt[this.processingHash].logs = logs
    this.txsReceipt[this.processingHash].transactionHash = this.processingHash
    const status = data.execResult.exceptionError ? 0 : 1
    this.txsReceipt[this.processingHash].status = `0x${status}`

    if (data.createdAddress) {
      const address = data.createdAddress.toString()
      this.vmTraces[this.processingHash].return = toChecksumAddress(address)
      this.txsReceipt[this.processingHash].contractAddress = toChecksumAddress(address)
    } else if (data.execResult.returnValue) {
      this.vmTraces[this.processingHash].return = bufferToHex(data.execResult.returnValue)
    } else {
      this.vmTraces[this.processingHash].return = '0x'
    }
    this.processingIndex = null
    this.processingAddress = null
    this.previousDepth = 0
  }
Example #13
Source File: VmProxy.ts    From remix-project with MIT License 5 votes vote down vote up
getCode (address, cb) {
    address = toChecksumAddress(address)
    this.vm.stateManager.getContractCode(Address.fromString(address)).then((result) => {
      cb(null, bufferToHex(result))
    }).catch((error) => {
      cb(error)
    })
  }
Example #14
Source File: compiler-fetch-and-compile.ts    From remix-project with MIT License 4 votes vote down vote up
/**
   * Fetch compiliation metadata from source-Verify from a given @arg contractAddress - https://github.com/ethereum/source-verify
   * Put the artifacts in the file explorer
   * Compile the code using Solidity compiler
   * Returns compilation data
   *
   * @param {string} contractAddress - Address of the contrac to resolve
   * @param {string} deployedBytecode - deployedBytecode of the contract
   * @param {string} targetPath - Folder where to save the compilation arfefacts
   * @return {CompilerAbstract} - compilation data targeting the given @arg contractAddress
   */
  async resolve (contractAddress, codeAtAddress, targetPath) {
    contractAddress = toChecksumAddress(contractAddress)

    const localCompilation = async () => await this.call('compilerArtefacts', 'get', contractAddress) ? await this.call('compilerArtefacts', 'get', contractAddress) : await this.call('compilerArtefacts', 'get', '__last') ? await this.call('compilerArtefacts', 'get', '__last') : null

    const resolved = await this.call('compilerArtefacts', 'get', contractAddress)
    if (resolved) return resolved
    if (this.unresolvedAddresses.includes(contractAddress)) return localCompilation()

    // sometimes when doing an internal call, the only available artifact is the Solidity interface.
    // resolving addresses of internal call would allow to step over the source code, even if the declaration was made using an Interface.

    let network
    try {
      network = await this.call('network', 'detectNetwork')
    } catch (e) {
      return localCompilation()
    }
    if (!network) return localCompilation()
    if (!this.sourceVerifierNetWork.includes(network.name)) return localCompilation()

    // check if the contract if part of the local compilation result
    const compilation = await localCompilation()
    if (compilation) {
      let found = false
      compilation.visitContracts((contract) => {
        found = util.compareByteCode('0x' + contract.object.evm.deployedBytecode.object, codeAtAddress)
        return found
      })
      if (found) {
        await this.call('compilerArtefacts', 'addResolvedContract', contractAddress, compilation)
        setTimeout(_ => this.emit('usingLocalCompilation', contractAddress), 0)
        return compilation
      }
    }

    targetPath = `${targetPath}/${network.id}/${contractAddress}`
    let data
    try {
      data = await fetchContractFromSourcify(this, network, contractAddress, targetPath)
    } catch (e) {
      this.call('notification', 'toast', e.message)
      console.log(e) // and fallback to getting the compilation result from etherscan
    }

    if (!data) {
      this.call('notification', 'toast', `contract ${contractAddress} not found in Sourcify, checking in Etherscan..`)
      try {
        data = await fetchContractFromEtherscan(this, network, contractAddress, targetPath)
      } catch (e) {
        this.call('notification', 'toast', e.message)
        setTimeout(_ => this.emit('notFound', contractAddress), 0) // plugin framework returns a time out error although it actually didn't find the source...
        this.unresolvedAddresses.push(contractAddress)
        return localCompilation()    
      }
    }

    if (!data) {
      setTimeout(_ => this.emit('notFound', contractAddress), 0)
      this.unresolvedAddresses.push(contractAddress)
      return localCompilation()
    }
    const { settings, compilationTargets } = data
   
    try {
      setTimeout(_ => this.emit('compiling', settings), 0)
      const compData = await compile(
        compilationTargets,
        settings,
        async (url, cb) => {
          // we first try to resolve the content from the compilation target using a more appropiate path
          const path = `${targetPath}/${url}`
          if (compilationTargets[path] && compilationTargets[path].content) {
            return cb(null, compilationTargets[path].content)
          } else {
            await this.call('contentImport', 'resolveAndSave', url).then((result) => cb(null, result)).catch((error) => cb(error.message))
          }
        })
      await this.call('compilerArtefacts', 'addResolvedContract', contractAddress, compData)
      return compData
    } catch (e) {
      this.unresolvedAddresses.push(contractAddress)
      setTimeout(_ => this.emit('compilationFailed'), 0)
      return localCompilation()
    }
  }
Example #15
Source File: VmProxy.ts    From remix-project with MIT License 4 votes vote down vote up
async pushTrace (data) {
    const depth = data.depth + 1 // geth starts the depth from 1
    if (!this.processingHash) {
      console.log('no tx processing')
      return
    }
    let previousopcode
    if (this.vmTraces[this.processingHash] && this.vmTraces[this.processingHash].structLogs[this.processingIndex - 1]) {
      previousopcode = this.vmTraces[this.processingHash].structLogs[this.processingIndex - 1]
    }

    if (this.previousDepth > depth && previousopcode) {
      // returning from context, set error it is not STOP, RETURN
      previousopcode.invalidDepthChange = previousopcode.op !== 'RETURN' && previousopcode.op !== 'STOP'
    }
    const step = {
      stack: hexListFromBNs(data.stack),
      memory: formatMemory(data.memory),
      storage: data.storage,
      op: data.opcode.name,
      pc: data.pc,
      gasCost: data.opcode.fee.toString(),
      gas: data.gasLeft.toString(),
      depth: depth,
      error: data.error === false ? undefined : data.error
    }
    this.vmTraces[this.processingHash].structLogs.push(step)
    // Track hardhat console.log call
    if (step.op === 'STATICCALL' && step.stack[step.stack.length - 2] === '0x000000000000000000000000000000000000000000636f6e736f6c652e6c6f67') {
      const stackLength = step.stack.length
      const payloadStart = parseInt(step.stack[stackLength - 3], 16)
      const memory = step.memory.join('')
      let payload = memory.substring(payloadStart * 2, memory.length)
      const fnselectorStr = payload.substring(0, 8)
      const fnselectorStrInHex = '0x' + fnselectorStr
      const fnselector = parseInt(fnselectorStrInHex)
      const fnArgs = ConsoleLogs[fnselector]
      const iface = new ethers.utils.Interface([`function log${fnArgs} view`])
      const functionDesc = iface.getFunction(`log${fnArgs}`)
      const sigHash = iface.getSighash(`log${fnArgs}`)
      if (fnArgs.includes('uint') && sigHash !== fnselectorStrInHex) {
        payload = payload.replace(fnselectorStr, sigHash)
      } else {
        payload = '0x' + payload
      }
      const consoleArgs = iface.decodeFunctionData(functionDesc, payload)
      this.hhLogs[this.processingHash] = this.hhLogs[this.processingHash] ? this.hhLogs[this.processingHash] : []
      this.hhLogs[this.processingHash].push(consoleArgs)
    }

    if (step.op === 'CREATE' || step.op === 'CALL') {
      if (step.op === 'CREATE') {
        this.processingAddress = '(Contract Creation - Step ' + this.processingIndex + ')'
        this.storageCache[this.processingHash][this.processingAddress] = {}
        this.lastProcessedStorageTxHash[this.processingAddress] = this.processingHash
      } else {
        this.processingAddress = normalizeHexAddress(step.stack[step.stack.length - 2])
        this.processingAddress = toChecksumAddress(this.processingAddress)
        if (!this.storageCache[this.processingHash][this.processingAddress]) {
          const account = Address.fromString(this.processingAddress)
          try {
            const storage = await this.vm.stateManager.dumpStorage(account)
            this.storageCache[this.processingHash][this.processingAddress] = storage
            this.lastProcessedStorageTxHash[this.processingAddress] = this.processingHash
          } catch (e) {
            console.log(e)
          }
        }
      }
    }
    if (previousopcode && previousopcode.op === 'SHA3') {
      const preimage = this.getSha3Input(previousopcode.stack, previousopcode.memory)
      const imageHash = step.stack[step.stack.length - 1].replace('0x', '')
      this.sha3Preimages[imageHash] = {
        preimage: preimage
      }
    }

    this.processingIndex++
    this.previousDepth = depth
  }