How to use the ethereumjs-util.setLengthLeft function in ethereumjs-util

To help you get started, we’ve selected a few ethereumjs-util examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ewasm / evm2wasm / tests / runVmTests.js View on Github external
// check storage
  if (testData.post) {
    const expectedAccount = testData.post[testData.exec.address]
    // TODO: check all accounts
    if (expectedAccount) {
      const expectedStorage = expectedAccount.storage
      if (expectedStorage) {
        for (let key in expectedStorage) {
          const keyHex = (new U256(key)).toString(16)
          // pad values to get consistent hex strings for comparison
          let expectedValue = ethUtil.setLengthLeft(ethUtil.toBuffer(expectedStorage[key]), 32)
          expectedValue = '0x' + expectedValue.toString('hex')
          let actualValue = environment.state[testData.exec.address]['storage'][keyHex]
          if (actualValue) {
            actualValue = '0x' + ethUtil.setLengthLeft(ethUtil.toBuffer(actualValue), 32).toString('hex')
          } else {
            actualValue = '0x' + ethUtil.setLengthLeft(ethUtil.toBuffer(0), 32).toString('hex')
          }
          t.equals(actualValue, expectedValue, `should have correct storage value at key ${key}`)
        }
      }
    }
  }
}
github BANKEX / PlasmaETHexchange / app / helpers / createTxFromJson.js View on Github external
const numOutputs = transactionJSON.outputs.length
            if (numInputs != NumInputsForType[txType] || numOutputs != NumOutputsForType[txType]){
                return null;
            }
            let inputsTotalValue = new BN(0);
            let outputsTotalValue = new BN(0);
            const txParams = {}
            let inputCounter = 0;
            // const inputs = []
            for (let inputJSON of transactionJSON.inputs) {
                const unspentOutput = await getUTXO(inputJSON.blockNumber, inputJSON.txNumber, inputJSON.outputNumber);
                if (!unspentOutput) {
                    return null;
                }
                const blockNumberBuffer = ethUtil.setLengthLeft(ethUtil.toBuffer(new BN(inputJSON.blockNumber)),blockNumberLength)
                const txNumberBuffer = ethUtil.setLengthLeft(ethUtil.toBuffer(new BN(inputJSON.txNumber)),txNumberLength)
                const txOutputNumberBuffer = ethUtil.setLengthLeft(ethUtil.toBuffer(new BN(inputJSON.outputNumber)),txOutputNumberLength)
                const inputParams = {
                    blockNumber: blockNumberBuffer,
                    txNumberInBlock: txNumberBuffer,
                    outputNumberInTransaction: txOutputNumberBuffer,
                    amountBuffer: unspentOutput.amountBuffer
                }
                const input = new TransactionInput(inputParams);
                // inputs.push(input)
                inputsTotalValue = inputsTotalValue.add(unspentOutput.value);
                txParams["inputNum"+inputCounter]=Buffer.concat(input.raw);
                inputCounter++;
            }
            let outputCounter = 0;
            for (let outputJSON of transactionJSON.outputs) {
                const outputNumberBuffer = ethUtil.setLengthLeft(ethUtil.toBuffer(new BN(outputCounter)),txOutputNumberLength)
github 0xProject / 0x-monorepo / packages / utils / src / abi_encoder / evm_data_types / string.ts View on Github external
public encodeValue(value: string): Buffer {
        // Encoded value is of the form: , with each field padded to be word-aligned.
        // 1/3 Construct the value
        const valueBuf = Buffer.from(value);
        const valueLengthInBytes = valueBuf.byteLength;
        const wordsToStoreValuePadded = Math.ceil(valueLengthInBytes / constants.EVM_WORD_WIDTH_IN_BYTES);
        const bytesToStoreValuePadded = wordsToStoreValuePadded * constants.EVM_WORD_WIDTH_IN_BYTES;
        const valueBufPadded = ethUtil.setLengthRight(valueBuf, bytesToStoreValuePadded);
        // 2/3 Construct the length
        const lengthBuf = ethUtil.toBuffer(valueLengthInBytes);
        const lengthBufPadded = ethUtil.setLengthLeft(lengthBuf, constants.EVM_WORD_WIDTH_IN_BYTES);
        // 3/3 Combine length and value
        const encodedValue = Buffer.concat([lengthBufPadded, valueBufPadded]);
        return encodedValue;
    }
github leapdao / leap-node / src / tx / applyTx / checkSpendCond.js View on Github external
let spendingAddress;

  // this is a bag of N(F/S)Ts to remember and update owners
  const nftBag = {};
  // this is a bag of ERC20s to help transform inputs to outputs
  const tokenBag = {};

  for (let i = 0; i < txInputLen; i += 1) {
    const input = tx.inputs[i];
    const unspent = state.unspent[input.prevout.hex()];

    if (!unspent) {
      throw new Error(`unspent: ${input.prevout.hex()} does not exists`);
    }

    const tokenValueBuf = utils.setLengthLeft(
      utils.toBuffer(`0x${BigInt(unspent.value).toString(16)}`),
      32
    );
    const contractAddr = colorMap[unspent.color];
    const contractAddrStr = `0x${contractAddr.toString('hex')}`;
    if (isNFT(unspent.color) || isNST(unspent.color)) {
      const tokenId = `0x${tokenValueBuf.toString('hex')}`;
      nftBag[contractAddrStr] = !nftBag[contractAddrStr]
        ? {}
        : nftBag[contractAddrStr];
      nftBag[contractAddrStr][tokenId] = {
        addr: unspent.address,
        touched: false,
      };
    } else if (i > 0) {
      tokenBag[contractAddrStr] = !tokenBag[contractAddrStr]
github BANKEX / PlasmaETHexchange / app / miner.js View on Github external
async function createBlock() {
        try{
            try{
                lastBlock = await levelDB.get('lastBlockNumber');
            }
            catch(error) {
                lastBlock = ethUtil.setLengthLeft(ethUtil.toBuffer(new BN(0)),blockNumberLength)
                await levelDB.put('lastBlockNumber', lastBlock);
            }
            try{
                lastBlockHash = await levelDB.get('lastBlockHash');
            }
            catch(error) {
                lastBlockHash = ethUtil.sha3('bankex.com')
                await levelDB.put('lastBlockHash', lastBlockHash);
            }

            let sliceLen;
            let TXs;
            console.log("Mining a block")
            console.log("Queue length = " + app.txQueueArray.length);
            if (app.txQueueArray.length == 0) {
                return false;
github RequestNetwork / requestNetwork / packages / requestNetwork.js / src / lib / ethereumjs-abi-perso.js View on Github external
ABI.toSolidityBytes32 = function(type, value) {
    type = elementaryName(type);
    var ret = []
    if (type === 'bytes') {
      ret.push(utils.setLengthRight(value, 32))
    } else if (type === 'bool') {
      ret.push(utils.setLengthLeft(value ? 1 : 0, 32));
    } else if (type === 'address') {
      ret.push(utils.setLengthLeft(value, 32))
    } else if (type.startsWith('bytes')) {
      size = parseTypeN(type)
      if (size < 1 || size > 32) {
        throw new Error('Invalid bytes width: ' + size)
      }
      ret.push(utils.setLengthRight(value, 32))
    } else if (type.startsWith('uint')) {
      size = parseTypeN(type)
      if ((size % 8) || (size < 8) || (size > 256)) {
        throw new Error('Invalid uint width: ' + size)
      }

      num = parseNumber(value)
      if (num.bitLength() > size) {
github OpenZeppelin / openzeppelin-gsn-provider / src / tabookey-gasless / utils.js View on Github external
function toUint256_noPrefix(int) {
  return removeHexPrefix(ethUtils.bufferToHex(ethUtils.setLengthLeft(int, 32)));
}
github DigixGlobal / truffle-lightwallet-provider / node_modules / ethereumjs-vm / lib / precompiled / 01-ecrecover.js View on Github external
var data = utils.setLengthRight(opts.data, 128)

  var msgHash = data.slice(0, 32)
  var v = data.slice(32, 64)
  var r = data.slice(64, 96)
  var s = data.slice(96, 128)

  var publicKey
  try {
    publicKey = utils.ecrecover(msgHash, v, r, s)
  } catch (e) {
    return results
  }

  results.return = utils.setLengthLeft(utils.publicToAddress(publicKey), 32)
  results.exception = 1

  return results
}
github RequestNetwork / requestNetwork / packages / requestNetwork.js / src / lib / ethereumjs-abi-perso.js View on Github external
ABI.toSolidityBytes32 = function(type, value) {
    type = elementaryName(type);
    var ret = []
    if (type === 'bytes') {
      ret.push(utils.setLengthRight(value, 32))
    } else if (type === 'bool') {
      ret.push(utils.setLengthLeft(value ? 1 : 0, 32));
    } else if (type === 'address') {
      ret.push(utils.setLengthLeft(value, 32))
    } else if (type.startsWith('bytes')) {
      size = parseTypeN(type)
      if (size < 1 || size > 32) {
        throw new Error('Invalid bytes width: ' + size)
      }
      ret.push(utils.setLengthRight(value, 32))
    } else if (type.startsWith('uint')) {
      size = parseTypeN(type)
      if ((size % 8) || (size < 8) || (size > 256)) {
        throw new Error('Invalid uint width: ' + size)
      }

      num = parseNumber(value)
      if (num.bitLength() > size) {
        throw new Error('Supplied uint exceeds width: ' + size + ' vs ' + num.bitLength())
      }
github BANKEX / PlasmaETHexchange / server.js View on Github external
async function prepareOracle(){
    await startVM();
    await comp();
    await deployContracts();
    try{
        lastBlock = await levelDB.get('lastBlockNumber');
    }
    catch(error) {
        lastBlock = ethUtil.setLengthLeft(ethUtil.toBuffer(new BN(0)),blockNumberLength)
        await levelDB.put('lastBlockNumber', lastBlock);
    }
    try{
        lastBlockHash = await levelDB.get('lastBlockHash');
    }
    catch(error) {
        lastBlockHash = ethUtil.sha3('bankex.com')
        await levelDB.put('lastBlockHash', lastBlockHash);
    }
    app.txQueueArray = [];
    app.DeployedPlasmaContract = DeployedPlasmaContract;
    const processDepositEvent = require('./app/helpers/processDepositEvent')(app, levelDB, web3);
    const processExpressWithdrawMakeEvent = require('./app/helpers/processExpressWithdrawMadeEvent')(app, levelDB, web3);
    app.processDepositEvent = processDepositEvent;
    app.processExpressWithdrawMakeEvent = processExpressWithdrawMakeEvent;
    require('./app/miner')(app, levelDB, web3);