ethereumjs-util#Address TypeScript Examples

The following examples show how to use ethereumjs-util#Address. 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: 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 #2
Source File: accounts.ts    From remix-project with MIT License 6 votes vote down vote up
eth_getBalance (payload, cb) {
    const address = payload.params[0]

    this.vmContext.vm().stateManager.getAccount(Address.fromString(address)).then((account) => {
      cb(null, new BN(account.balance).toString(10))
    }).catch((error) => {
      cb(error)
    })
  }
Example #3
Source File: transactions.ts    From remix-project with MIT License 6 votes vote down vote up
eth_getTransactionCount (payload, cb) {
    const address = payload.params[0]

    this.vmContext.vm().stateManager.getAccount(Address.fromString(address)).then((account) => {
      const nonce = new BN(account.nonce).toString(10)
      cb(null, nonce)
    }).catch((error) => {
      cb(error)
    })
  }
Example #4
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 #5
Source File: cosmos_evm_metamask_web_wallet.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
function encodeEthAddress(bech32Prefix: string, address: string): string {
  return bech32.encode(bech32Prefix, bech32.toWords(Address.fromString(address).toBuffer()));
}
Example #6
Source File: txRunnerVM.ts    From remix-project with MIT License 4 votes vote down vote up
runInVm (from, to, data, value, gasLimit, useCall, timestamp, callback) {
    const self = this
    let account
    if (!from && useCall && Object.keys(self.vmaccounts).length) {
      from = Object.keys(self.vmaccounts)[0]
      account = self.vmaccounts[from]
    } else account = self.vmaccounts[from] 
    
    if (!account) {
      return callback('Invalid account selected')
    }
    if (Number.isInteger(gasLimit)) {
      gasLimit = '0x' + gasLimit.toString(16)
    }

    this.getVMObject().stateManager.getAccount(Address.fromString(from)).then((res) => {
      // See https://github.com/ethereumjs/ethereumjs-tx/blob/master/docs/classes/transaction.md#constructor
      // for initialization fields and their types
      if (!value) value = 0
      if (typeof value === 'string') {
        if (value.startsWith('0x')) value = new BN(value.replace('0x', ''), 'hex')
        else {
          try {
            value = new BN(value, 10)
          } catch (e) {
            return callback('Unable to parse the value ' + e.message)
          }
        }
      }

      const EIP1559 = this.commonContext.hardfork() !== 'berlin' // berlin is the only pre eip1559 fork that we handle.
      let tx
      if (!EIP1559) {
        tx = Transaction.fromTxData({
          nonce: useCall ? this.nextNonceForCall : new BN(res.nonce),
          gasPrice: '0x1',
          gasLimit: gasLimit,
          to: to,
          value: value,
          data: Buffer.from(data.slice(2), 'hex')
        }, { common: this.commonContext }).sign(account.privateKey)
      } else {
        tx = FeeMarketEIP1559Transaction.fromTxData({
          nonce: useCall ? this.nextNonceForCall : new BN(res.nonce),
          maxPriorityFeePerGas: '0x01',
          maxFeePerGas: '0x1',
          gasLimit: gasLimit,
          to: to,
          value: value,
          data: Buffer.from(data.slice(2), 'hex')
        }).sign(account.privateKey)
      }
      if (useCall) this.nextNonceForCall++

      const coinbases = ['0x0e9281e9c6a0808672eaba6bd1220e144c9bb07a', '0x8945a1288dc78a6d8952a92c77aee6730b414778', '0x94d76e24f818426ae84aa404140e8d5f60e10e7e']
      const difficulties = [new BN('69762765929000', 10), new BN('70762765929000', 10), new BN('71762765929000', 10)]

      const block = Block.fromBlockData({
        header: {
          timestamp: timestamp || (new Date().getTime() / 1000 | 0),
          number: self.blockNumber,
          coinbase: coinbases[self.blockNumber % coinbases.length],
          difficulty: difficulties[self.blockNumber % difficulties.length],
          gasLimit: new BN(gasLimit.replace('0x', ''), 16).imuln(2),
          baseFeePerGas: EIP1559 ? '0x1' : undefined
        },
        transactions: [tx]
      }, { common: this.commonContext })

      if (!useCall) {
        ++self.blockNumber
        this.runBlockInVm(tx, block, callback)
      } else {
        this.getVMObject().stateManager.checkpoint().then(() => {
          this.runBlockInVm(tx, block, (err, result) => {
            this.getVMObject().stateManager.revert().then(() => {
              callback(err, result)
            })
          })
        })
      }
    }).catch((e) => {
      callback(e)
    })
  }
Example #7
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
  }