ethers/lib/utils#hexlify TypeScript Examples

The following examples show how to use ethers/lib/utils#hexlify. 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: utils.ts    From hubble-contracts with MIT License 6 votes vote down vote up
export function randHex(n: number): string {
    return hexlify(randomBytes(n));
}
Example #2
Source File: tx.ts    From hubble-contracts with MIT License 6 votes vote down vote up
public encode(): string {
        const concated = concat([
            hexZeroPad(hexlify(this.fromIndex), stateIDLen),
            hexZeroPad(hexlify(this.toIndex), stateIDLen),
            hexZeroPad(hexlify(this.toPubkeyID), stateIDLen),
            float16.compress(this.amount),
            float16.compress(this.fee)
        ]);
        return hexlify(concated);
    }
Example #3
Source File: hashToField.test.ts    From hubble-contracts with MIT License 6 votes vote down vote up
describe("Hash to Field", () => {
    before(async () => {
        await mcl.init();
    });
    it("expand message", () => {
        for (let i = 0; i < vectors.length; i++) {
            const v = vectors[i];
            const msg = Uint8Array.from(Buffer.from(v.msg, "utf8"));
            const outLen = v.outLen;
            const out = expandMsg(DST, msg, outLen);
            assert.equal(hexlify(out), v.expected);
        }
    });
    it("hash to point", () => {
        const expectedX =
            "0x09b6a2dec1f1b0747c73332e5147ecacde20767f28a9b68261713bed9a1d2432";
        const expectedY =
            "0x0cb70ff0b1bdb5d30006bd0cc03dc2c071dcff0daea886c9793f304c695c1bc6";
        const dst = Uint8Array.from(Buffer.from("xxx", "utf8"));
        const msg = "0x616263";
        const p = mcl.hashToPoint(msg, dst);
        const [x, y] = mcl.g1ToHex(p);
        assert.equal(x, expectedX);
        assert.equal(y, expectedY);
    });
});
Example #4
Source File: transfer.ts    From hubble-contracts with MIT License 6 votes vote down vote up
serialize(): string {
        const concated = concat([
            hexZeroPad(hexlify(this.fromIndex), StateIDLen),
            hexZeroPad(hexlify(this.toIndex), StateIDLen),
            float16.compress(this.amount),
            float16.compress(this.fee)
        ]);
        return hexlify(concated);
    }
Example #5
Source File: transfer.ts    From hubble-contracts with MIT License 6 votes vote down vote up
serialize(): string {
        if (!this.signature) throw new Error("Signature must be assigned");
        const concated = concat([
            hexZeroPad(hexlify(this.fromIndex), StateIDLen),
            hexZeroPad(hexlify(this.toIndex), StateIDLen),
            float16.compress(this.amount),
            float16.compress(this.fee),
            hexZeroPad(hexlify(this.nonce), StateIDLen),
            dumpG1(this.signature?.sol)
        ]);
        return hexlify(concated);
    }
Example #6
Source File: tx.ts    From hubble-contracts with MIT License 6 votes vote down vote up
public encode(): string {
        const concated = concat([
            hexZeroPad(hexlify(this.fromIndex), stateIDLen),
            hexZeroPad(hexlify(this.toIndex), stateIDLen),
            float16.compress(this.amount),
            float16.compress(this.fee)
        ]);
        return hexlify(concated);
    }
Example #7
Source File: mcl.ts    From hubble-contracts with MIT License 6 votes vote down vote up
export function loadG2(hex: string): solG2 {
    const bytesarray = arrayify(hex);
    if (bytesarray.length != 128)
        throw new Error(`Expect length 128 but got ${bytesarray.length}`);
    const x0 = hexlify(bytesarray.slice(0, 32));
    const x1 = hexlify(bytesarray.slice(32, 64));
    const y0 = hexlify(bytesarray.slice(64, 96));
    const y1 = hexlify(bytesarray.slice(96, 128));
    return [x0, x1, y0, y1];
}
Example #8
Source File: mcl.ts    From hubble-contracts with MIT License 6 votes vote down vote up
export function g2ToHex(p: mclG2): solG2 {
    p.normalize();
    const x = toBigEndian(p.getX());
    const x0 = hexlify(x.slice(32));
    const x1 = hexlify(x.slice(0, 32));
    const y = toBigEndian(p.getY());
    const y0 = hexlify(y.slice(32));
    const y1 = hexlify(y.slice(0, 32));
    return [x0, x1, y0, y1];
}
Example #9
Source File: mcl.ts    From hubble-contracts with MIT License 5 votes vote down vote up
export function g1ToHex(p: mclG1): solG1 {
    p.normalize();
    const x = hexlify(toBigEndian(p.getX()));
    const y = hexlify(toBigEndian(p.getY()));
    return [x, y];
}
Example #10
Source File: tx.ts    From hubble-contracts with MIT License 5 votes vote down vote up
export function serialize(txs: Tx[]): string {
    return hexlify(concat(txs.map(tx => tx.encode())));
}
Example #11
Source File: tx.ts    From hubble-contracts with MIT License 5 votes vote down vote up
public encode(): string {
        const concated = concat([
            hexZeroPad(hexlify(this.fromIndex), stateIDLen),
            float16.compress(this.amount),
            float16.compress(this.fee)
        ]);
        return hexlify(concated);
    }
Example #12
Source File: mcl.ts    From hubble-contracts with MIT License 5 votes vote down vote up
export function loadG1(hex: string): solG1 {
    const bytesarray = arrayify(hex);
    if (bytesarray.length != 64)
        throw new Error(`Expect length 64 but got ${bytesarray.length}`);
    const x = hexlify(bytesarray.slice(0, 32));
    const y = hexlify(bytesarray.slice(32));
    return [x, y];
}
Example #13
Source File: uniswapV3.ts    From index-rebalance-utils with Apache License 2.0 5 votes vote down vote up
export async function getUniswapV3Quote(deployHelper: DeployHelper, token: Address, targetPriceImpact: BigNumber, feeAmount: number = FeeAmount.MEDIUM): Promise<ExchangeQuote> {
  const factoryInstance = await deployHelper.external.getUniswapV3FactoryInstance(UNI_V3_FACTORY);
  const poolAddress = await factoryInstance.getPool(token, ETH_ADDRESS, feeAmount);
  if (poolAddress == ADDRESS_ZERO) {
    return {
      exchange: exchanges.UNISWAP_V3,
      size: ZERO.toString(),
      data: "0x",
    } as ExchangeQuote;
  }

  const poolInstance = await deployHelper.external.getUniswapV3PoolInstance(poolAddress);
  const globalStorage = await poolInstance.slot0();
  const currentSqrtPrice = globalStorage.sqrtPriceX96;

  const currentPrice = preciseDiv(BigNumber.from(2).pow(192), currentSqrtPrice.pow(2));

  if (currentPrice.eq(0)) {
    return {
      exchange: exchanges.UNISWAP_V3,
      size: ZERO.toString(),
      data: "0x",
    } as ExchangeQuote;
  }

  // This is not actually target price where targetPrice = price*(1+targetPriceImpact). It instead sets a maximum price change after trade
  // of 2 * targetPriceImpact. If you assume that the liquidity is flat accross the 2 * targetPriceImpact, then it will equal to targetPriceImpact
  // slippage. The worst-case scenario outcome for this approximation is when you move across ticks and the liquidity falls off significantly,
  // and you execute the trade a price impact of 2% instead of 1%.

  // Divide by 50: convert basis point in percent to basis points in decimal (/100) multiply by two to meet target price impact
  const targetPrice = token > ETH_ADDRESS ? preciseMul(currentPrice, ether(1).add(targetPriceImpact.div(50))) :
    preciseMul(currentPrice, ether(1).sub(targetPriceImpact.div(50)));
  const sqrtPriceLimit = sqrt(preciseDiv(BigNumber.from(2).pow(192), targetPrice));

  const quoterInstance = await deployHelper.external.getUniswapV3QuoterInstance(UNI_V3_QUOTER);

  return {
    exchange: exchanges.UNISWAP_V3,
    size:   (await quoterInstance.callStatic.quoteExactInputSingle(
      ETH_ADDRESS,
      token,
      feeAmount,
      ether(10000),
      sqrtPriceLimit
    )).toString(),
    data: hexZeroPad(hexlify(feeAmount), 3),
  } as ExchangeQuote;
}
Example #14
Source File: transfer.ts    From hubble-contracts with MIT License 5 votes vote down vote up
export function compress(txs: OffchainTx[]): string {
    return hexlify(concat(txs.map(tx => tx.toCompressed().serialize())));
}
Example #15
Source File: transfer.ts    From hubble-contracts with MIT License 5 votes vote down vote up
static deserialize(bytes: Uint8Array) {
        const decompress = (input: Uint8Array) => float16.decompress(input);
        const fields = [
            {
                name: "fromIndex",
                length: StateIDLen,
                constructor: BigNumber.from
            },
            {
                name: "toIndex",
                length: StateIDLen,
                constructor: BigNumber.from
            },
            {
                name: "amount",
                length: FloatLength,
                constructor: decompress
            },
            {
                name: "fee",
                length: FloatLength,
                constructor: decompress
            },
            { name: "nonce", length: StateIDLen, constructor: BigNumber.from },
            { name: "signature", length: 64, constructor: hexlify }
        ];
        const sum = sumNumber(fields.map(x => x.length));
        if (bytes.length != sum) throw new Error("invalid bytes");
        const obj: any = {};
        let position = 0;
        for (const field of fields) {
            const byteSlice = bytes.slice(position, position + field.length);
            position += field.length;
            obj[field.name] = field.constructor(byteSlice);
        }
        const solG1 = loadG1(obj.signature);
        const mclG1 = parseG1(solG1);
        const signature = { sol: solG1, mcl: mclG1 };

        return new this(
            obj.fromIndex,
            obj.toIndex,
            obj.amount,
            obj.fee,
            obj.nonce,
            signature
        );
    }
Example #16
Source File: OpenEthereumClient.ts    From tx2uml with MIT License 5 votes vote down vote up
async getTransactionError(tx: TransactionDetails): Promise<string> {
        if (!tx?.hash.match(transactionHash)) {
            throw TypeError(
                `There is no transaction hash on the receipt object`
            )
        }
        if (tx.status) {
            return undefined
        }
        if (tx.gasUsed === tx.gasLimit) {
            throw Error("Transaction failed as it ran out of gas.")
        }

        try {
            debug(`About to get transaction trace for ${tx.hash}`)
            const params = [
                {
                    // A Nethermind bug means the nonce of the original transaction can be used.
                    // error.data: "wrong transaction nonce"
                    // nonce: tx.nonce,
                    gasPrice: tx.gasPrice.toHexString(),
                    gas: tx.gasLimit.toHexString(),
                    value: tx.value.toHexString(),
                    from: tx.from,
                    to: tx.to,
                    data: tx.data,
                },
                hexlify(tx.blockNumber),
            ]
            const response = await axios.post(this.url, {
                id: this.jsonRpcId++,
                jsonrpc: "2.0",
                method: "eth_call",
                params,
            })

            return response.data?.error?.data
        } catch (err) {
            throw new VError(
                err,
                `Failed to get transaction trace for tx hash ${tx.hash} from url ${this.url}.`
            )
        }
    }
Example #17
Source File: GethClient.ts    From tx2uml with MIT License 5 votes vote down vote up
async getTransactionError(tx: TransactionDetails): Promise<string> {
        if (!tx?.hash.match(transactionHash)) {
            throw TypeError(
                `There is no transaction hash on the receipt object`
            )
        }
        if (tx.status) {
            return undefined
        }
        if (tx.gasUsed === tx.gasLimit) {
            throw Error("Transaction failed as it ran out of gas.")
        }

        let rawMessageData
        try {
            const params = [
                {
                    nonce: tx.nonce,
                    gasPrice: convertBigNumber2Hex(tx.gasPrice),
                    gas: convertBigNumber2Hex(tx.gasLimit),
                    value: convertBigNumber2Hex(tx.value),
                    from: tx.from,
                    to: tx.to,
                    data: tx.data,
                },
                // need to call for the block before
                hexlify(tx.blockNumber - 1).replace(/^0x0/, "0x"),
            ]
            const response = await axios.post(this.url, {
                id: this.jsonRpcId++,
                jsonrpc: "2.0",
                method: "eth_call",
                params,
            })

            return response.data?.error?.message
        } catch (e) {
            if (e.message.startsWith("Node error: ")) {
                // Trim "Node error: "
                const errorObjectStr = e.message.slice(12)
                // Parse the error object
                const errorObject = JSON.parse(errorObjectStr)

                if (!errorObject.data) {
                    throw Error(
                        "Failed to parse data field error object:" +
                            errorObjectStr
                    )
                }

                if (errorObject.data.startsWith("Reverted 0x")) {
                    // Trim "Reverted 0x" from the data field
                    rawMessageData = errorObject.data.slice(11)
                } else if (errorObject.data.startsWith("0x")) {
                    // Trim "0x" from the data field
                    rawMessageData = errorObject.data.slice(2)
                } else {
                    throw Error(
                        "Failed to parse data field of error object:" +
                            errorObjectStr
                    )
                }
            } else {
                throw Error(
                    "Failed to parse error message from Ethereum call: " +
                        e.message
                )
            }
        }

        return parseReasonCode(rawMessageData)
    }
Example #18
Source File: bls.test.ts    From hubble-contracts with MIT License 4 votes vote down vote up
describe("BLS", async () => {
    let bls: TestBLS;
    before(async function() {
        const signer = ethers.provider.getSigner();
        await deployKeyless(signer, false, { PairingGasEstimators: true });
        await mcl.init();
        const accounts = await ethers.getSigners();
        bls = await new TestBLS__factory(accounts[0]).deploy();
        await bls.deployed();
    });
    it("map to point", async function() {
        for (let i = 0; i < 100; i++) {
            const e = randFs();
            const [expectX, expectY] = mcl.g1ToHex(mcl.mapToPoint(e));
            const [actualX, actualY] = await bls.mapToPoint(e);
            assert.equal(to32Hex(actualX), expectX, "e " + e);
            assert.equal(to32Hex(actualY), expectY, "e " + e);
        }
    });
    it("expand message to 96", async function() {
        for (let i = 0; i < 100; i++) {
            const msg = randomBytes(i);
            const expected = expandMsg(DOMAIN, msg, 96);
            const result = await bls.expandMsg(DOMAIN, msg);
            assert.equal(result, hexlify(expected));
        }
    });
    it("hash to field", async function() {
        for (let i = 0; i < 100; i++) {
            const msg = randomBytes(i);
            const [expectX, expectY] = hashToField(DOMAIN, msg, 2);
            const [actualX, actualY] = await bls.hashToField(DOMAIN, msg);
            assert.equal(actualX.toHexString(), expectX.toHexString());
            assert.equal(actualY.toHexString(), expectY.toHexString());
        }
    });
    it("hash to point", async function() {
        for (let i = 0; i < 100; i++) {
            const msg = randHex(i);
            const [expectX, expectY] = mcl.g1ToHex(
                mcl.hashToPoint(msg, DOMAIN)
            );
            const [actualX, actualY] = await bls.hashToPoint(DOMAIN, msg);
            assert.equal(to32Hex(actualX), expectX);
            assert.equal(to32Hex(actualY), expectY);
        }
    });
    it("verify aggregated signature", async function() {
        const n = 10;
        const messages = [];
        const pubkeys = [];
        const signatures = [];
        for (let i = 0; i < n; i++) {
            const message = randHex(12);
            const { pubkey, secret } = mcl.newKeyPair();
            const { signature, messagePoint } = mcl.sign(
                message,
                secret,
                DOMAIN
            );
            messages.push(mcl.g1ToHex(messagePoint));
            pubkeys.push(mcl.g2ToHex(pubkey));
            signatures.push(signature);
            const aggSignature = mcl.g1ToHex(mcl.aggregateRaw(signatures));
            const { 0: checkResult, 1: callSuccess } = await bls.verifyMultiple(
                aggSignature,
                pubkeys,
                messages
            );
            assert.isTrue(callSuccess, `call failed i=${i}`);
            assert.isTrue(checkResult, `check failed i=${i}`);
        }
    });
    it("verify aggregated signature: fail bad signature", async function() {
        const n = 10;
        const messages = [];
        const pubkeys = [];
        const signatures = [];
        for (let i = 0; i < n; i++) {
            const message = randHex(12);
            const { pubkey, secret } = mcl.newKeyPair();
            const { signature, messagePoint } = mcl.sign(
                message,
                secret,
                DOMAIN
            );
            messages.push(mcl.g1ToHex(messagePoint));
            pubkeys.push(mcl.g2ToHex(pubkey));
            if (i != 0) {
                signatures.push(signature);
            }
        }
        const aggSignature = mcl.g1ToHex(mcl.aggregateRaw(signatures));
        const res = await bls.verifyMultiple(aggSignature, pubkeys, messages);
        assert.isFalse(res[0]);
        assert.isTrue(res[1]);
    });
    it("verify aggregated signature: fail signature is not on curve", async function() {
        const n = 10;
        const messages = [];
        const pubkeys = [];
        for (let i = 0; i < n; i++) {
            const message = randHex(12);
            const { pubkey, secret } = mcl.newKeyPair();
            const { messagePoint } = mcl.sign(message, secret, DOMAIN);
            messages.push(mcl.g1ToHex(messagePoint));
            pubkeys.push(mcl.g2ToHex(pubkey));
        }
        const aggSignature: mcl.solG1 = [100, 100];
        let res = await bls.verifyMultiple(aggSignature, pubkeys, messages);
        assert.isFalse(res[0]);
        assert.isFalse(res[1]);
    });
    it("verify aggregated signature: fail pubkey is not on curve", async function() {
        const n = 10;
        const messages = [];
        const pubkeys: mcl.solG2[] = [];
        const signatures = [];
        for (let i = 0; i < n; i++) {
            const message = randHex(12);
            const { pubkey, secret } = mcl.newKeyPair();
            const { signature, messagePoint } = mcl.sign(
                message,
                secret,
                DOMAIN
            );
            messages.push(mcl.g1ToHex(messagePoint));
            if (i == 0) {
                pubkeys.push([3, 3, 3, 3]);
            } else {
                pubkeys.push(mcl.g2ToHex(pubkey));
            }
            signatures.push(signature);
        }
        const aggSignature = mcl.g1ToHex(mcl.aggregateRaw(signatures));
        const res = await bls.verifyMultiple(aggSignature, pubkeys, messages);
        assert.isFalse(res[0]);
        assert.isFalse(res[1]);
    });
    it("verify aggregated signature: fail pubkey is not on correct subgroup", async function() {
        const n = 10;
        const messages = [];
        const pubkeys = [];
        const signatures = [];

        for (let i = 0; i < n; i++) {
            const message = randHex(12);
            const { pubkey, secret } = mcl.newKeyPair();
            const { signature, messagePoint } = mcl.sign(
                message,
                secret,
                DOMAIN
            );
            messages.push(mcl.g1ToHex(messagePoint));
            if (i == 0) {
                pubkeys.push(g2PointOnIncorrectSubgroup);
                assert.isTrue(await bls.isOnCurveG2(pubkeys[i]));
            } else {
                pubkeys.push(mcl.g2ToHex(pubkey));
            }
            signatures.push(signature);
        }
        const aggSignature = mcl.g1ToHex(mcl.aggregateRaw(signatures));
        let res = await bls.verifyMultiple(aggSignature, pubkeys, messages);
        assert.isFalse(res[0]);
        assert.isFalse(res[1]);
    });
    it("verify single signature", async function() {
        const message = randHex(12);
        const { pubkey, secret } = mcl.newKeyPair();
        const { signature, messagePoint } = mcl.sign(message, secret, DOMAIN);
        let res = await bls.verifySingle(
            mcl.g1ToHex(signature),
            mcl.g2ToHex(pubkey),
            mcl.g1ToHex(messagePoint)
        );
        assert.isTrue(res[0]);
        assert.isTrue(res[1]);
    });
    it("verify single signature: fail bad signature", async function() {
        const message = randHex(12);
        const { pubkey } = mcl.newKeyPair();
        const { secret } = mcl.newKeyPair();
        const { signature, messagePoint } = mcl.sign(message, secret, DOMAIN);
        let res = await bls.verifySingle(
            mcl.g1ToHex(signature),
            mcl.g2ToHex(pubkey),
            mcl.g1ToHex(messagePoint)
        );
        assert.isFalse(res[0]);
        assert.isTrue(res[1]);
    });
    it("verify single signature: fail pubkey is not on curve", async function() {
        const message = randHex(12);
        const { secret } = mcl.newKeyPair();
        const { signature, messagePoint } = mcl.sign(message, secret, DOMAIN);
        const pubkey: mcl.solG2 = [3, 3, 3, 3];
        let res = await bls.verifySingle(
            mcl.g1ToHex(signature),
            pubkey,
            mcl.g1ToHex(messagePoint)
        );
        assert.isFalse(res[0]);
        assert.isFalse(res[1]);
    });
    it("verify single signature: fail signature is not on curve", async function() {
        const message = randHex(12);
        const { pubkey, secret } = mcl.newKeyPair();
        const { messagePoint } = mcl.sign(message, secret, DOMAIN);
        const signature: mcl.solG1 = [3, 3];
        let res = await bls.verifySingle(
            signature,
            mcl.g2ToHex(pubkey),
            mcl.g1ToHex(messagePoint)
        );
        assert.isFalse(res[0]);
        assert.isFalse(res[1]);
    });
    it("verify single signature: fail pubkey is not on correct subgroup", async function() {
        const message = randHex(12);
        const { secret } = mcl.newKeyPair();
        const { signature, messagePoint } = mcl.sign(message, secret, DOMAIN);
        const pubkey = g2PointOnIncorrectSubgroup;
        assert.isTrue(await bls.isOnCurveG2(pubkey));
        let res = await bls.verifySingle(
            mcl.g1ToHex(signature),
            pubkey,
            mcl.g1ToHex(messagePoint)
        );
        assert.isFalse(res[0]);
        assert.isFalse(res[1]);
    });
    it("is on curve g1", async function() {
        for (let i = 0; i < 20; i++) {
            const point = mcl.randG1();
            let isOnCurve = await bls.isOnCurveG1(point);
            assert.isTrue(isOnCurve);
        }
        for (let i = 0; i < 20; i++) {
            const point: mcl.solG1 = [randomBytes(31), randomBytes(31)];
            const isOnCurve = await bls.isOnCurveG1(point);
            assert.isFalse(isOnCurve);
        }
    });
    it("is on curve g2", async function() {
        for (let i = 0; i < 20; i++) {
            const point = mcl.randG2();
            let isOnCurve = await bls.isOnCurveG2(point);
            assert.isTrue(isOnCurve);
        }
        for (let i = 0; i < 20; i++) {
            const point: mcl.solG2 = [
                randomBytes(31),
                randomBytes(31),
                randomBytes(31),
                randomBytes(31)
            ];
            const isOnCurve = await bls.isOnCurveG2(point);
            assert.isFalse(isOnCurve);
        }
    });
    it.skip("gas cost: verify signature", async function() {
        const n = 100;
        const messages = [];
        const pubkeys = [];
        const signatures = [];
        for (let i = 0; i < n; i++) {
            const message = randHex(12);
            const { pubkey, secret } = mcl.newKeyPair();
            const { signature, messagePoint } = mcl.sign(
                message,
                secret,
                DOMAIN
            );
            messages.push(mcl.g1ToHex(messagePoint));
            pubkeys.push(mcl.g2ToHex(pubkey));
            signatures.push(signature);
        }
        const aggSignature = mcl.g1ToHex(mcl.aggregateRaw(signatures));
        const cost = await bls.callStatic.verifyMultipleGasCost(
            aggSignature,
            pubkeys,
            messages
        );
        console.log(`verify signature for ${n} message: ${cost.toNumber()}`);
    });
    it.skip("gas cost: verify single signature", async function() {
        const message = randHex(12);
        const { pubkey, secret } = mcl.newKeyPair();
        const { signature, messagePoint } = mcl.sign(message, secret, DOMAIN);
        const cost = await bls.callStatic.verifySingleGasCost(
            mcl.g1ToHex(signature),
            mcl.g2ToHex(pubkey),
            mcl.g1ToHex(messagePoint)
        );
        console.log(`verify single signature:: ${cost.toNumber()}`);
    });
});