@ethersproject/bytes#concat TypeScript Examples

The following examples show how to use @ethersproject/bytes#concat. 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: util.ts    From fuels-ts with Apache License 2.0 7 votes vote down vote up
getContractId = (
  bytecode: BytesLike,
  salt: BytesLike,
  stateRoot: BytesLike
): string => {
  const root = getContractRoot(arrayify(bytecode));
  const contractId = sha256(concat(['0x4655454C', salt, root, stateRoot]));
  return contractId;
}
Example #2
Source File: Option.ts    From casper-js-sdk with Apache License 2.0 6 votes vote down vote up
/**
   * Serializes the `Option` into an array of bytes.
   */
  toBytes(value: CLOption<CLValue>): ToBytesResult {
    if (value.data.none) {
      return Ok(Uint8Array.from([OPTION_TAG_NONE]));
    }
    if (value.data.some) {
      return Ok(
        concat([
          Uint8Array.from([OPTION_TAG_SOME]),
          CLValueParsers.toBytes(value.data.unwrap()).unwrap()
        ])
      );
    }

    return Err(CLErrorCodes.UnknownValue);
  }
Example #3
Source File: mnemonic.ts    From fuels-ts with Apache License 2.0 6 votes vote down vote up
/**
   * Get the extendKey as defined on BIP-32 from the provided seed
   *
   * @param seed - BIP39 seed
   * @param testnet - Inform if should use testnet or mainnet prefix, default value is true (`mainnet`).
   * @returns BIP-32 extended private key
   */
  static seedToExtendedKey(seed: string, testnet: boolean = false): string {
    const masterKey = Mnemonic.masterKeysFromSeed(seed);
    const prefix = arrayify(testnet ? TestnetPRV : MainnetPRV);
    const depth = '0x00';
    const fingerprint = '0x00000000';
    const index = '0x00000000';
    // last 32 bites from the key
    const chainCode = masterKey.slice(32);
    // first 32 bites from the key
    const privateKey = masterKey.slice(0, 32);
    const extendedKey = concat([
      prefix,
      depth,
      fingerprint,
      index,
      chainCode,
      concat(['0x00', privateKey]),
    ]);
    const checksum = hexDataSlice(sha256(sha256(extendedKey)), 0, 4);

    return Base58.encode(concat([extendedKey, checksum]));
  }
Example #4
Source File: Signer.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
async _signMessage(
    evmAddress: string,
    message: Bytes | string
  ): Promise<string> {
    if (!evmAddress) {
      return logger.throwError('No binding evm address');
    }
    const messagePrefix = '\x19Ethereum Signed Message:\n';
    if (typeof message === 'string') {
      message = toUtf8Bytes(message);
    }
    const msg = u8aToHex(
      concat([
        toUtf8Bytes(messagePrefix),
        toUtf8Bytes(String(message.length)),
        message
      ])
    );

    if (!this.signingKey.signRaw) {
      return logger.throwError('Need to implement signRaw method');
    }

    const result = await this.signingKey.signRaw({
      address: evmAddress,
      data: msg,
      type: 'bytes'
    });

    return joinSignature(result.signature);
  }
Example #5
Source File: Signer.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
async _signMessage(evmAddress: string, message: Bytes | string): Promise<string> {
    if (!evmAddress) {
      return logger.throwError('No binding evm address');
    }
    const messagePrefix = '\x19Ethereum Signed Message:\n';
    if (typeof message === 'string') {
      message = toUtf8Bytes(message);
    }
    const msg = u8aToHex(concat([toUtf8Bytes(messagePrefix), toUtf8Bytes(String(message.length)), message]));

    if (!this.signingKey.signRaw) {
      return logger.throwError('Need to implement signRaw method');
    }

    const result = await this.signingKey.signRaw({
      address: evmAddress,
      data: msg,
      type: 'bytes'
    });

    return joinSignature(result.signature);
  }
Example #6
Source File: output.ts    From fuels-ts with Apache License 2.0 6 votes vote down vote up
encode(value: Output): Uint8Array {
    const parts: Uint8Array[] = [];

    parts.push(new NumberCoder('u8').encode(value.type));
    switch (value.type) {
      case OutputType.Coin: {
        parts.push(new OutputCoinCoder().encode(value));
        break;
      }
      case OutputType.Contract: {
        parts.push(new OutputContractCoder().encode(value));
        break;
      }
      case OutputType.Withdrawal: {
        parts.push(new OutputWithdrawalCoder().encode(value));
        break;
      }
      case OutputType.Change: {
        parts.push(new OutputChangeCoder().encode(value));
        break;
      }
      case OutputType.Variable: {
        parts.push(new OutputVariableCoder().encode(value));
        break;
      }
      case OutputType.ContractCreated: {
        parts.push(new OutputContractCreatedCoder().encode(value));
        break;
      }
      default: {
        throw new Error('Invalid Output type');
      }
    }

    return concat(parts);
  }
Example #7
Source File: Key.ts    From casper-js-sdk with Apache License 2.0 6 votes vote down vote up
toBytes(value: CLKey): ToBytesResult {
    if (value.isAccount()) {
      return Ok(
        concat([
          Uint8Array.from([KeyVariant.Account]),
          new CLAccountHashBytesParser()
            .toBytes(value.data as CLAccountHash)
            .unwrap()
        ])
      );
    }
    if (value.isHash()) {
      return Ok(
        concat([
          Uint8Array.from([KeyVariant.Hash]),
          new CLByteArrayBytesParser()
            .toBytes(value.data as CLByteArray)
            .unwrap()
        ])
      );
    }
    if (value.isURef()) {
      return Ok(
        concat([
          Uint8Array.from([KeyVariant.URef]),
          CLValueParsers.toBytes(value.data as CLURef).unwrap()
        ])
      );
    }

    throw new Error('Unknown byte types');
  }
Example #8
Source File: interface.ts    From fuels-ts with Apache License 2.0 6 votes vote down vote up
encodeFunctionData(
    functionFragment: FunctionFragment | string,
    values: Array<InputValue>
  ): Uint8Array {
    const fragment =
      typeof functionFragment === 'string' ? this.getFunction(functionFragment) : functionFragment;

    if (!fragment) {
      throw new Error('Fragment not found');
    }

    const selector = Interface.getSighash(fragment);
    const inputs = filterEmptyParams(fragment.inputs);

    if (inputs.length === 0) {
      return selector;
    }

    const isRef = inputs.length > 1 || isReferenceType(inputs[0].type);
    const args = this.abiCoder.encode(inputs, values);
    return concat([selector, new BooleanCoder().encode(isRef), args]);
  }
Example #9
Source File: CLValue.ts    From clarity with Apache License 2.0 6 votes vote down vote up
public toAccountHash(): Uint8Array {
    const algorithmIdentifier = this.signatureAlgorithm();
    const separator = Buffer.from([0]);
    const prefix = Buffer.concat([
      Buffer.from(algorithmIdentifier.toLowerCase()),
      separator
    ]);

    if (this.rawPublicKey.length === 0) {
      return Buffer.from([]);
    } else {
      return byteHash(Buffer.concat([prefix, Buffer.from(this.rawPublicKey)]));
    }
  }
Example #10
Source File: DeployUtil.ts    From casper-js-sdk with Apache License 2.0 6 votes vote down vote up
serializeApprovals = (approvals: Approval[]): Uint8Array => {
  const len = toBytesU32(approvals.length);
  const bytes = concat(
    approvals.map(approval => {
      return concat([
        Uint8Array.from(Buffer.from(approval.signer, 'hex')),
        Uint8Array.from(Buffer.from(approval.signature, 'hex'))
      ]);
    })
  );
  return concat([len, bytes]);
}
Example #11
Source File: CLValue.ts    From clarity with Apache License 2.0 6 votes vote down vote up
/**
   * Serializes a `CLValue` into an array of bytes.
   */
  public toBytes() {
    return concat([
      toBytesArrayU8(this.clValueBytes()),
      CLTypeHelper.toBytesHelper(this.clType)
    ]);
  }
Example #12
Source File: DeployUtil.ts    From casper-js-sdk with Apache License 2.0 6 votes vote down vote up
public toBytes(): ToBytesResult {
    let serializedVersion;

    if (this.version === null) {
      serializedVersion = new CLOption(None, new CLU32Type());
    } else {
      serializedVersion = new CLOption(Some(new CLU32(this.version as number)));
    }
    return Ok(
      concat([
        Uint8Array.from([this.tag]),
        toBytesBytesArray(this.hash),
        CLValueParsers.toBytes(serializedVersion).unwrap(),
        toBytesString(this.entryPoint),
        toBytesBytesArray(this.args.toBytes().unwrap())
      ])
    );
  }
Example #13
Source File: DeployUtil.ts    From clarity with Apache License 2.0 6 votes vote down vote up
public toBytes(): Uint8Array {
    let serializedVersion;
    if (this.version === null) {
      serializedVersion = new Option(null, CLTypeHelper.u32());
    } else {
      serializedVersion = new Option(new U32(this.version as number));
    }
    return concat([
      Uint8Array.from([this.tag]),
      toBytesString(this.name),
      serializedVersion.toBytes(),
      toBytesString(this.entryPoint),
      toBytesBytesArray(this.args.toBytes())
    ]);
  }
Example #14
Source File: DeployUtil.ts    From casper-js-sdk with Apache License 2.0 6 votes vote down vote up
public toBytes(): ToBytesResult {
    return Ok(
      concat([
        Uint8Array.from([this.tag]),
        toBytesBytesArray(this.hash),
        toBytesString(this.entryPoint),
        toBytesBytesArray(this.args.toBytes().unwrap())
      ])
    );
  }
Example #15
Source File: byterepr.ts    From clarity with Apache License 2.0 6 votes vote down vote up
toBytesNumber = (
  bitSize: number,
  signed: boolean,
  value: BigNumberish
) => {
  let v = BigNumber.from(value);

  // Check bounds are safe for encoding
  const maxUintValue = MaxUint256.mask(bitSize);
  if (signed) {
    const bounds = maxUintValue.mask(bitSize - 1); // 1 bit for signed
    if (v.gt(bounds) || v.lt(bounds.add(One).mul(NegativeOne))) {
      throw new Error('value out-of-bounds, value: ' + value);
    }
  } else if (v.lt(Zero) || v.gt(maxUintValue.mask(bitSize))) {
    throw new Error('value out-of-bounds, value: ' + value);
  }
  v = v.toTwos(bitSize).mask(bitSize);
  const bytes = arrayify(v);
  if (v.gte(0)) {
    // for positive number, we had to deal with paddings
    if (bitSize > 64) {
      // for u128, u256, u512, we have to and append extra byte for length
      return concat([bytes, Uint8Array.from([bytes.length])]).reverse();
    } else {
      // for other types, we have to add padding 0s
      const byteLength = bitSize / 8;
      return concat([
        bytes.reverse(),
        new Uint8Array(byteLength - bytes.length)
      ]);
    }
  } else {
    return bytes.reverse();
  }
}
Example #16
Source File: array.ts    From fuels-ts with Apache License 2.0 6 votes vote down vote up
encode(value: InputValueOf<TCoder>): Uint8Array {
    if (!Array.isArray(value)) {
      this.throwError('expected array value', value);
    }

    if (this.length !== value.length) {
      this.throwError('Types/values length mismatch', value);
    }

    return concat(Array.from(value).map((v) => this.coder.encode(v)));
  }
Example #17
Source File: Result.ts    From casper-js-sdk with Apache License 2.0 6 votes vote down vote up
toBytes(value: CLResult<CLType, CLType>): ToBytesResult {
    if (value.isOk() && value.data.val.isCLValue) {
      return Ok(
        concat([
          Uint8Array.from([RESULT_TAG_OK]),
          CLValueParsers.toBytes(value.data.val).unwrap()
        ])
      );
    } else if (value.isError()) {
      return Ok(
        concat([
          Uint8Array.from([RESULT_TAG_ERROR]),
          CLValueParsers.toBytes(value.data.val).unwrap()
        ])
      );
    } else {
      throw new Error('Unproper data stored in CLResult');
    }
  }
Example #18
Source File: struct.ts    From fuels-ts with Apache License 2.0 6 votes vote down vote up
encode(value: InputValueOf<TCoders>): any {
    const encodedFields = Object.keys(this.coders).map((fieldName) => {
      const fieldCoder = this.coders[fieldName];
      const fieldValue = value[fieldName];
      const encoded = fieldCoder.encode(fieldValue);
      return encoded;
    });
    return concat(encodedFields);
  }
Example #19
Source File: DeployUtil.ts    From casper-js-sdk with Apache License 2.0 6 votes vote down vote up
public toBytes(): ToBytesResult {
    return Ok(
      concat([
        CLValueParsers.toBytes(this.account).unwrap(),
        toBytesU64(this.timestamp),
        toBytesU64(this.ttl),
        toBytesU64(this.gasPrice),
        toBytesDeployHash(this.bodyHash),
        toBytesVector(this.dependencies.map(d => new DeployHash(d))),
        toBytesString(this.chainName)
      ])
    );
  }
Example #20
Source File: output.ts    From fuels-ts with Apache License 2.0 5 votes vote down vote up
encode(value: OutputContractCreated): Uint8Array {
    const parts: Uint8Array[] = [];

    parts.push(new B256Coder().encode(value.contractId));
    parts.push(new B256Coder().encode(value.stateRoot));

    return concat(parts);
  }
Example #21
Source File: List.ts    From casper-js-sdk with Apache License 2.0 5 votes vote down vote up
toBytes(): Uint8Array {
    return concat([Uint8Array.from([this.tag]), this.inner.toBytes()]);
  }
Example #22
Source File: byterepr.ts    From clarity with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes an array of u8, equal to Vec<u8> in rust.
 */
export function toBytesArrayU8(arr: Uint8Array): Uint8Array {
  return concat([toBytesU32(arr.length), arr]);
}
Example #23
Source File: ByteConverters.ts    From casper-js-sdk with Apache License 2.0 5 votes vote down vote up
toBytesVectorNew = <T extends CLValue>(vec: T[]): Uint8Array => {
  const valueByteList = vec.map(e => CLValueParsers.toBytes(e).unwrap());
  valueByteList.splice(0, 0, toBytesU32(vec.length));
  return concat(valueByteList);
}
Example #24
Source File: byterepr.ts    From clarity with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes a vector of values of type `T` into an array of bytes.
 */
export function toBytesVecT<T extends ToBytes>(vec: T[]) {
  const valueByteList = vec.map(e => e.toBytes());
  valueByteList.splice(0, 0, toBytesU32(vec.length));
  return concat(valueByteList);
}
Example #25
Source File: string.ts    From fuels-ts with Apache License 2.0 5 votes vote down vote up
encode(value: string): Uint8Array {
    let pad = (8 - this.length) % 8;
    pad = pad < 0 ? pad + 8 : pad;
    const str = toUtf8Bytes(value.slice(0, this.length));
    return concat([str, new Uint8Array(pad)]);
  }
Example #26
Source File: ByteConverters.ts    From casper-js-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes a string into an array of bytes.
 */
export function toBytesString(str: string): Uint8Array {
  const arr = Uint8Array.from(Buffer.from(str));
  return concat([toBytesU32(arr.byteLength), arr]);
}