Near-One / omni-bridge

5 stars 3 forks source link

[OmniBridge]: compare abi and borsh encoding gas usage in solidity #4

Closed karim-en closed 2 months ago

kiseln commented 2 months ago

Ethereum RLP encoding is 3k gas cheaper than borsh. I would continue using borsh as the difference is insignificant

    function encodeBorsh() external returns (bytes32 result) {
        BridgeDeposit memory bridgeDeposit = BridgeDeposit(
            2,
            "wrap.testnet",
            100121,
            0x3A445243376C32fAba679F63586e236F77EA601e,
            0x0000000000000000000000000000000000000000
        );

        bytes memory borshEncoded = bytes.concat(
            encodeUint128(bridgeDeposit.nonce),
            encodeString(bridgeDeposit.token),
            encodeUint128(bridgeDeposit.amount),
            bytes1(0x00), // variant 1 in rust enum
            encodeAddress(bridgeDeposit.recipient),
            bridgeDeposit.relayer == address(0)  // None or Some(Address) in rust
                ? bytes("\x00")
                : bytes.concat(bytes("\x01"), encodeAddress(bridgeDeposit.relayer))
        );
        result = keccak256(borshEncoded);

        results.push(result);
    }

    function encodeRlp() external returns (bytes32 result) {
        BridgeDeposit memory bridgeDeposit = BridgeDeposit(
            2,
            "wrap.testnet",
            100121,
            0x3A445243376C32fAba679F63586e236F77EA601e,
            0x0000000000000000000000000000000000000000
        );

        bytes memory rlpEncoded = abi.encode(
            bridgeDeposit.nonce,
            bridgeDeposit.token,
            bridgeDeposit.amount,
            bridgeDeposit.recipient,
            bridgeDeposit.relayer
        );

        result = keccak256(rlpEncoded);

        results.push(result);
    }