Verified contractPartialMIT
BungeeComposer
Address0x0cf931ce09de5cc5e994efb4e9da6c744faea12f
- Balance
0 ETH
- Transactions
3
- Compiler
solc 0.8.27
- Same code
Only this contract
Details
- Compiler
- solc 0.8.27+commit.40a35a09
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- prague
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,542,718
- Creation transaction
- 0x57ef7d0ad6…ef1b585e21
28 files
- src/composers/BungeeComposer.solmain3.61 KB
- dependencies/@bob-collective-bitcoin-spv-v1/src/BTCUtils.sol39.09 KB
- dependencies/@bob-collective-bitcoin-spv-v1/src/BytesLib.sol18.96 KB
- dependencies/@bob-collective-bitcoin-spv-v1/src/SafeMath.sol2.69 KB
- dependencies/@bob-collective-bitcoin-spv-v1/src/ValidateSPV.sol5.72 KB
- dependencies/@bob-collective-bob-v1/contracts/src/relay/IFullRelay.sol1.33 KB
- dependencies/@bob-collective-bob-v1/contracts/src/relay/IFullRelayWithVerify.sol397 B
- dependencies/@bob-collective-bob-v1/contracts/src/relay/ILightRelay.sol1.18 KB
- dependencies/@bob-collective-bob-v1/contracts/src/relay/LightRelay.sol24 KB
- dependencies/@bob-collective-bob-v1/contracts/src/utils/BitcoinTx.sol22.72 KB
- dependencies/@openzeppelin-contracts-5.5.0/access/Ownable.sol3.1 KB
- dependencies/@openzeppelin-contracts-5.5.0/access/Ownable2Step.sol2.48 KB
- dependencies/@openzeppelin-contracts-5.5.0/interfaces/IERC1363.sol4.45 KB
- dependencies/@openzeppelin-contracts-5.5.0/interfaces/IERC165.sol193 B
- dependencies/@openzeppelin-contracts-5.5.0/interfaces/IERC20.sol182 B
- dependencies/@openzeppelin-contracts-5.5.0/interfaces/draft-IERC6093.sol6.54 KB
- dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/ERC20.sol10.8 KB
- dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/IERC20.sol2.78 KB
- dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/extensions/IERC20Metadata.sol684 B
- dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/utils/SafeERC20.sol13.31 KB
- dependencies/@openzeppelin-contracts-5.5.0/utils/Context.sol963 B
- dependencies/@openzeppelin-contracts-5.5.0/utils/introspection/IERC165.sol871 B
- src/CommonStructs.sol4.31 KB
- src/IERC20Ext.sol321 B
- src/IGatewayOfframpRegistryV7.sol7.8 KB
- src/interfaces/IBungeeExecutor.sol669 B
- src/strategy/IStrategy.sol993 B
- src/swapper/ISwapper.sol689 B
src/composers/BungeeComposer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {IBungeeExecutor} from "../interfaces/IBungeeExecutor.sol";
import {IGatewayOfframpRegistryV7} from "../IGatewayOfframpRegistryV7.sol";
import {OfframpOrderArgs} from "../CommonStructs.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @title Bungee Composer
/// @notice Creates gateway offramp orders from Socket v3 destination payloads.
///
/// The BungeeReceiver delivers the bridged tokens, approves them to this contract and calls
/// {executeData} with the payload `abi.encode(offrampRegistry, offrampOrderArgs, solverSignature)`.
/// Any failure reverts, and Bungee then sends the delivery to this contract, the route's receiver,
/// rather than to the quote's refund address. The owner withdraws such deliveries, and any tokens
/// or native coin left on it by mistake, to return them by hand.
contract BungeeComposer is IBungeeExecutor, Ownable2Step {
using SafeERC20 for IERC20;
/// @notice The only caller allowed to execute payloads.
address public immutable bungeeReceiver;
error ZeroAddress();
error UnauthorizedCaller();
error ZeroAmount();
error InvalidToken();
error NoBalance();
error ETHTransferFailed();
/// @param initialOwner Withdraws stuck funds; ownership moves only once the new owner accepts it.
/// @param _bungeeReceiver The BungeeReceiver allowed to call {executeData}.
constructor(address initialOwner, address _bungeeReceiver) Ownable(initialOwner) {
if (_bungeeReceiver == address(0)) revert ZeroAddress();
bungeeReceiver = _bungeeReceiver;
}
/// @notice Accepts the native coin Bungee falls back to sending here when {executeData} reverts.
receive() external payable {}
/// @inheritdoc IBungeeExecutor
function executeData(bytes32, uint256 amount, address token, bytes calldata callData) external override {
if (msg.sender != bungeeReceiver) revert UnauthorizedCaller();
if (amount == 0) revert ZeroAmount();
(address offrampRegistry, OfframpOrderArgs memory args, bytes memory solverSignature) =
abi.decode(callData, (address, OfframpOrderArgs, bytes));
if (token != args.token || IGatewayOfframpRegistryV7(offrampRegistry).allowedTokens(token) == 0) {
revert InvalidToken();
}
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
// Lock all of it; the solver signed `minimumTokenAmountToLock`, not this.
args.tokenAmountToLock = amount;
IERC20(token).forceApprove(offrampRegistry, amount);
IGatewayOfframpRegistryV7(offrampRegistry).createOrder(args, solverSignature);
}
function withdrawStuckTokens(IERC20 token, address recipient) external onlyOwner {
if (recipient == address(0)) revert ZeroAddress();
uint256 balance = token.balanceOf(address(this));
if (balance == 0) revert NoBalance();
token.safeTransfer(recipient, balance);
}
function withdrawStuckNative(address recipient) external onlyOwner {
if (recipient == address(0)) revert ZeroAddress();
uint256 balance = address(this).balance;
if (balance == 0) revert NoBalance();
(bool success,) = payable(recipient).call{value: balance}("");
if (!success) revert ETHTransferFailed();
}
}
dependencies/@bob-collective-bitcoin-spv-v1/src/BTCUtils.sol
pragma solidity ^0.8.4;
import {BytesLib} from "./BytesLib.sol";
import {SafeMath} from "./SafeMath.sol";
/// @title BTCUtils
/// @author Summa (https://github.com/summa-tx) and Bob (https://github.com/bob-collective)
/// @notice Utility library for Bitcoin Actions
library BTCUtils {
using BytesLib for bytes;
using SafeMath for uint256;
// The target at minimum Difficulty. Also the target of the genesis block
uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000;
uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds
uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks
uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/* ***** */
/* UTILS */
/* ***** */
/// @notice Determines the length of a VarInt in bytes
/// @dev A VarInt of >1 byte is prefixed with a flag indicating its length
/// @param _flag The first byte of a VarInt
/// @return The number of non-flag bytes in the VarInt
function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) {
return determineVarIntDataLengthAt(_flag, 0);
}
/// @notice Determines the length of a VarInt in bytes
/// @dev A VarInt of >1 byte is prefixed with a flag indicating its length
/// @param _b The byte array containing a VarInt
/// @param _at The position of the VarInt in the array
/// @return The number of non-flag bytes in the VarInt
function determineVarIntDataLengthAt(bytes memory _b, uint256 _at) internal pure returns (uint8) {
if (uint8(_b[_at]) == 0xff) {
return 8; // one-byte flag, 8 bytes data
}
if (uint8(_b[_at]) == 0xfe) {
return 4; // one-byte flag, 4 bytes data
}
if (uint8(_b[_at]) == 0xfd) {
return 2; // one-byte flag, 2 bytes data
}
return 0; // flag is data
}
/// @notice Parse a VarInt into its data length and the number it represents
/// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.
/// Caller SHOULD explicitly handle this case (or bubble it up)
/// @param _b A byte-string starting with a VarInt
/// @return number of bytes in the encoding (not counting the tag), the encoded int
function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) {
return parseVarIntAt(_b, 0);
}
/// @notice Parse a VarInt into its data length and the number it represents
/// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.
/// Caller SHOULD explicitly handle this case (or bubble it up)
/// @param _b A byte-string containing a VarInt
/// @param _at The position of the VarInt
/// @return number of bytes in the encoding (not counting the tag), the encoded int
function parseVarIntAt(bytes memory _b, uint256 _at) internal pure returns (uint256, uint256) {
uint8 _dataLen = determineVarIntDataLengthAt(_b, _at);
if (_dataLen == 0) {
return (0, uint8(_b[_at]));
}
if (_b.length < 1 + _dataLen + _at) {
return (ERR_BAD_ARG, 0);
}
uint256 _number;
if (_dataLen == 2) {
_number = reverseUint16(uint16(_b.slice2(1 + _at)));
} else if (_dataLen == 4) {
_number = reverseUint32(uint32(_b.slice4(1 + _at)));
} else if (_dataLen == 8) {
_number = reverseUint64(uint64(_b.slice8(1 + _at)));
}
return (_dataLen, _number);
}
/// @notice Changes the endianness of a byte array
/// @dev Returns a new, backwards, bytes
/// @param _b The bytes to reverse
/// @return The reversed bytes
function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) {
bytes memory _newValue = new bytes(_b.length);
for (uint256 i = 0; i < _b.length; i++) {
_newValue[_b.length - i - 1] = _b[i];
}
return _newValue;
}
/// @notice Changes the endianness of a uint256
/// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint256(uint256 _b) internal pure returns (uint256 v) {
v = _b;
// swap bytes
v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF)
| ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF)
| ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF)
| ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
// swap 8-byte long pairs
v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF)
| ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
// swap 16-byte long pairs
v = (v >> 128) | (v << 128);
}
/// @notice Changes the endianness of a uint64
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint64(uint64 _b) internal pure returns (uint64 v) {
v = _b;
// swap bytes
v = ((v >> 8) & 0x00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v = ((v >> 16) & 0x0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v = (v >> 32) | (v << 32);
}
/// @notice Changes the endianness of a uint32
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint32(uint32 _b) internal pure returns (uint32 v) {
v = _b;
// swap bytes
v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);
// swap 2-byte long pairs
v = (v >> 16) | (v << 16);
}
/// @notice Changes the endianness of a uint24
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint24(uint24 _b) internal pure returns (uint24 v) {
v = (_b << 16) | (_b & 0x00FF00) | (_b >> 16);
}
/// @notice Changes the endianness of a uint16
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint16(uint16 _b) internal pure returns (uint16 v) {
v = (_b << 8) | (_b >> 8);
}
/// @notice Converts big-endian bytes to a uint
/// @dev Traverses the byte array and sums the bytes
/// @param _b The big-endian bytes-encoded integer
/// @return The integer representation
function bytesToUint(bytes memory _b) internal pure returns (uint256) {
uint256 _number;
for (uint256 i = 0; i < _b.length; i++) {
_number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1))));
}
return _number;
}
/// @notice Get the last _num bytes from a byte array
/// @param _b The byte array to slice
/// @param _num The number of bytes to extract from the end
/// @return The last _num bytes of _b
function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) {
uint256 _start = _b.length.sub(_num);
return _b.slice(_start, _num);
}
/// @notice Implements bitcoin's hash160 (rmd160(sha2()))
/// @dev abi.encodePacked changes the return to bytes instead of bytes32
/// @param _b The pre-image
/// @return The digest
function hash160(bytes memory _b) internal pure returns (bytes memory) {
return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));
}
/// @notice Implements bitcoin's hash160 (sha2 + ripemd160)
/// @dev sha2 precompile at address(2), ripemd160 at address(3)
/// @param _b The pre-image
/// @return res The digest
function hash160View(bytes memory _b) internal view returns (bytes20 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))
pop(staticcall(gas(), 3, 0x00, 32, 0x00, 32))
// read from position 12 = 0c
res := mload(0x0c)
}
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev abi.encodePacked changes the return to bytes instead of bytes32
/// @param _b The pre-image
/// @return The digest
function hash256(bytes memory _b) internal pure returns (bytes32) {
return sha256(abi.encodePacked(sha256(_b)));
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev sha2 is precompiled smart contract located at address(2)
/// @param _b The pre-image
/// @return res The digest
function hash256View(bytes memory _b) internal view returns (bytes32 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))
pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))
res := mload(0x00)
}
}
/// @notice Implements bitcoin's hash256 on a pair of bytes32
/// @dev sha2 is precompiled smart contract located at address(2)
/// @param _a The first bytes32 of the pre-image
/// @param _b The second bytes32 of the pre-image
/// @return res The digest
function hash256Pair(bytes32 _a, bytes32 _b) internal view returns (bytes32 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
mstore(0x00, _a)
mstore(0x20, _b)
pop(staticcall(gas(), 2, 0x00, 64, 0x00, 32))
pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))
res := mload(0x00)
}
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev sha2 is precompiled smart contract located at address(2)
/// @param _b The array containing the pre-image
/// @param at The start of the pre-image
/// @param len The length of the pre-image
/// @return res The digest
function hash256Slice(bytes memory _b, uint256 at, uint256 len) internal view returns (bytes32 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
pop(staticcall(gas(), 2, add(_b, add(32, at)), len, 0x00, 32))
pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))
res := mload(0x00)
}
}
/* ************ */
/* Legacy Input */
/* ************ */
/// @notice Extracts the nth input from the vin (0-indexed)
/// @dev Iterates over the vin. If you need to extract several, write a custom function
/// @param _vin The vin as a tightly-packed byte array
/// @param _index The 0-indexed location of the input to extract
/// @return The input as a byte array
function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _nIns;
(_varIntDataLen, _nIns) = parseVarInt(_vin);
require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing");
require(_index < _nIns, "Vin read overrun");
uint256 _len = 0;
uint256 _offset = 1 + _varIntDataLen;
for (uint256 _i = 0; _i < _index; _i++) {
_len = determineInputLengthAt(_vin, _offset);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig");
_offset = _offset + _len;
}
_len = determineInputLengthAt(_vin, _offset);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _vin.slice(_offset, _len);
}
/// @notice Determines whether an input is legacy
/// @dev False if no scriptSig, otherwise True
/// @param _input The input
/// @return True for legacy, False for witness
function isLegacyInput(bytes memory _input) internal pure returns (bool) {
return _input[36] != hex"00";
}
/// @notice Determines the length of a scriptSig in an input
/// @dev Will return 0 if passed a witness input.
/// @param _input The LEGACY input
/// @return The length of the script sig
function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) {
return extractScriptSigLenAt(_input, 0);
}
/// @notice Determines the length of a scriptSig in an input
/// starting at the specified position
/// @dev Will return 0 if passed a witness input.
/// @param _input The byte array containing the LEGACY input
/// @param _at The position of the input in the array
/// @return The length of the script sig
function extractScriptSigLenAt(bytes memory _input, uint256 _at) internal pure returns (uint256, uint256) {
if (_input.length < 37 + _at) {
return (ERR_BAD_ARG, 0);
}
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = parseVarIntAt(_input, _at + 36);
return (_varIntDataLen, _scriptSigLen);
}
/// @notice Determines the length of an input from its scriptSig
/// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence
/// @param _input The input
/// @return The length of the input in bytes
function determineInputLength(bytes memory _input) internal pure returns (uint256) {
return determineInputLengthAt(_input, 0);
}
/// @notice Determines the length of an input from its scriptSig,
/// starting at the specified position
/// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence
/// @param _input The byte array containing the input
/// @param _at The position of the input in the array
/// @return The length of the input in bytes
function determineInputLengthAt(bytes memory _input, uint256 _at) internal pure returns (uint256) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLenAt(_input, _at);
if (_varIntDataLen == ERR_BAD_ARG) {
return ERR_BAD_ARG;
}
return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;
}
/// @notice Extracts the LE sequence bytes from an input
/// @dev Sequence is used for relative time locks
/// @param _input The LEGACY input
/// @return The sequence bytes (LE uint)
function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes4) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _input.slice4(36 + 1 + _varIntDataLen + _scriptSigLen);
}
/// @notice Extracts the sequence from the input
/// @dev Sequence is a 4-byte little-endian number
/// @param _input The LEGACY input
/// @return The sequence number (big-endian uint)
function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) {
uint32 _leSeqence = uint32(extractSequenceLELegacy(_input));
uint32 _beSequence = reverseUint32(_leSeqence);
return _beSequence;
}
/// @notice Extracts the VarInt-prepended scriptSig from the input in a tx
/// @dev Will return hex"00" if passed a witness input
/// @param _input The LEGACY input
/// @return The length-prepended scriptSig
function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen);
}
/* ************* */
/* Witness Input */
/* ************* */
/// @notice Extracts the LE sequence bytes from an input
/// @dev Sequence is used for relative time locks
/// @param _input The WITNESS input
/// @return The sequence bytes (LE uint)
function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes4) {
return _input.slice4(37);
}
/// @notice Extracts the sequence from the input in a tx
/// @dev Sequence is a 4-byte little-endian number
/// @param _input The WITNESS input
/// @return The sequence number (big-endian uint)
function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) {
uint32 _leSeqence = uint32(extractSequenceLEWitness(_input));
uint32 _inputeSequence = reverseUint32(_leSeqence);
return _inputeSequence;
}
/// @notice Extracts the outpoint from the input in a tx
/// @dev 32-byte tx id with 4-byte index
/// @param _input The input
/// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index)
function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) {
return _input.slice(0, 36);
}
/// @notice Extracts the outpoint tx id from an input
/// @dev 32-byte tx id
/// @param _input The input
/// @return The tx id (little-endian bytes)
function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) {
return _input.slice32(0);
}
/// @notice Extracts the outpoint tx id from an input
/// starting at the specified position
/// @dev 32-byte tx id
/// @param _input The byte array containing the input
/// @param _at The position of the input
/// @return The tx id (little-endian bytes)
function extractInputTxIdLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes32) {
return _input.slice32(_at);
}
/// @notice Extracts the LE tx input index from the input in a tx
/// @dev 4-byte tx index
/// @param _input The input
/// @return The tx index (little-endian bytes)
function extractTxIndexLE(bytes memory _input) internal pure returns (bytes4) {
return _input.slice4(32);
}
/// @notice Extracts the LE tx input index from the input in a tx
/// starting at the specified position
/// @dev 4-byte tx index
/// @param _input The byte array containing the input
/// @param _at The position of the input
/// @return The tx index (little-endian bytes)
function extractTxIndexLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes4) {
return _input.slice4(32 + _at);
}
/* ****** */
/* Output */
/* ****** */
/// @notice Determines the length of an output
/// @dev Works with any properly formatted output
/// @param _output The output
/// @return The length indicated by the prefix, error if invalid length
function determineOutputLength(bytes memory _output) internal pure returns (uint256) {
return determineOutputLengthAt(_output, 0);
}
/// @notice Determines the length of an output
/// starting at the specified position
/// @dev Works with any properly formatted output
/// @param _output The byte array containing the output
/// @param _at The position of the output
/// @return The length indicated by the prefix, error if invalid length
function determineOutputLengthAt(bytes memory _output, uint256 _at) internal pure returns (uint256) {
if (_output.length < 9 + _at) {
return ERR_BAD_ARG;
}
uint256 _varIntDataLen;
uint256 _scriptPubkeyLength;
(_varIntDataLen, _scriptPubkeyLength) = parseVarIntAt(_output, 8 + _at);
if (_varIntDataLen == ERR_BAD_ARG) {
return ERR_BAD_ARG;
}
// 8-byte value, 1-byte for tag itself
return 8 + 1 + _varIntDataLen + _scriptPubkeyLength;
}
/// @notice Extracts the output at a given index in the TxOuts vector
/// @dev Iterates over the vout. If you need to extract multiple, write a custom function
/// @param _vout The _vout to extract from
/// @param _index The 0-indexed location of the output to extract
/// @return The specified output
function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _nOuts;
(_varIntDataLen, _nOuts) = parseVarInt(_vout);
require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing");
require(_index < _nOuts, "Vout read overrun");
uint256 _len = 0;
uint256 _offset = 1 + _varIntDataLen;
for (uint256 _i = 0; _i < _index; _i++) {
_len = determineOutputLengthAt(_vout, _offset);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey");
_offset += _len;
}
_len = determineOutputLengthAt(_vout, _offset);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey");
return _vout.slice(_offset, _len);
}
/// @notice Extracts the value bytes from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The output
/// @return The output value as LE bytes
function extractValueLE(bytes memory _output) internal pure returns (bytes8) {
return _output.slice8(0);
}
/// @notice Extracts the value from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The output
/// @return The output value
function extractValue(bytes memory _output) internal pure returns (uint64) {
uint64 _leValue = uint64(extractValueLE(_output));
uint64 _beValue = reverseUint64(_leValue);
return _beValue;
}
/// @notice Extracts the value from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The byte array containing the output
/// @param _at The starting index of the output in the array
/// @return The output value
function extractValueAt(bytes memory _output, uint256 _at) internal pure returns (uint64) {
uint64 _leValue = uint64(_output.slice8(_at));
uint64 _beValue = reverseUint64(_leValue);
return _beValue;
}
/// @notice Extracts the data from an op return output
/// @dev Returns hex"" if no data or not an op return
/// @param _output The output
/// @return Any data contained in the opreturn output, null if not an op return
function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) {
if (_output[9] != hex"6a") {
return hex"";
}
bytes1 _dataLen = _output[10];
return _output.slice(11, uint256(uint8(_dataLen)));
}
/// @notice Extracts the hash from the output script
/// @dev Determines type by the length prefix and validates format
/// @param _output The output
/// @return The hash committed to by the pk_script, or null for errors
function extractHash(bytes memory _output) internal pure returns (bytes memory) {
return extractHashAt(_output, 8, _output.length - 8);
}
/// @notice Extracts the hash from the output script
/// @dev Determines type by the length prefix and validates format
/// @param _output The byte array containing the output
/// @param _at The starting index of the output script in the array
/// (output start + 8)
/// @param _len The length of the output script
/// (output length - 8)
/// @return The hash committed to by the pk_script, or null for errors
function extractHashAt(bytes memory _output, uint256 _at, uint256 _len) internal pure returns (bytes memory) {
uint8 _scriptLen = uint8(_output[_at]);
// don't have to worry about overflow here.
// if _scriptLen + 1 overflows, then output length would have to be < 1
// for this check to pass. if it's < 1, then we errored when assigning
// _scriptLen
if (_scriptLen + 1 != _len) {
return hex"";
}
// version opcode is 0x00 for p2wpkh and p2wsh, 0x51 for p2tr
uint256 _version = uint8(_output[_at + 1]);
if (_version == 0x00 || _version == 0x51) {
// p2wpkh, p2wsh, p2tr
if (_scriptLen < 2) {
return hex"";
}
uint256 _payloadLen = uint8(_output[_at + 2]);
// Check for maliciously formatted witness outputs.
// No need to worry about underflow as long b/c of the `< 2` check
// p2wsh and p2tr have a payload length of 32 bytes, p2wpkh has a payload length of 20 bytes
if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) {
return hex"";
}
return _output.slice(_at + 3, _payloadLen);
} else {
bytes3 _tag = _output.slice3(_at);
// p2pkh
if (_tag == hex"1976a9") {
// Check for maliciously formatted p2pkh
// No need to worry about underflow, b/c of _scriptLen check
if (uint8(_output[_at + 3]) != 0x14 || _output.slice2(_at + _len - 2) != hex"88ac") {
return hex"";
}
return _output.slice(_at + 4, 20);
//p2sh
} else if (_tag == hex"17a914") {
// Check for maliciously formatted p2sh
// No need to worry about underflow, b/c of _scriptLen check
if (uint8(_output[_at + _len - 1]) != 0x87) {
return hex"";
}
return _output.slice(_at + 3, 20);
}
}
return hex""; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */
}
/* ********** */
/* Witness TX */
/* ********** */
/// @notice Checks that the vin passed up is properly formatted
/// @dev Consider a vin with a valid vout in its scriptsig
/// @param _vin Raw bytes length-prefixed input vector
/// @return True if it represents a validly formatted vin
function validateVin(bytes memory _vin) internal pure returns (bool) {
uint256 _varIntDataLen;
uint256 _nIns;
(_varIntDataLen, _nIns) = parseVarInt(_vin);
// Not valid if it says there are too many or no inputs
if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) {
return false;
}
uint256 _offset = 1 + _varIntDataLen;
for (uint256 i = 0; i < _nIns; i++) {
// If we're at the end, but still expect more
if (_offset >= _vin.length) {
return false;
}
// Grab the next input and determine its length.
uint256 _nextLen = determineInputLengthAt(_vin, _offset);
if (_nextLen == ERR_BAD_ARG) {
return false;
}
// Increase the offset by that much
_offset += _nextLen;
}
// Returns false if we're not exactly at the end
return _offset == _vin.length;
}
/// @notice Checks that the vout passed up is properly formatted
/// @dev Consider a vout with a valid scriptpubkey
/// @param _vout Raw bytes length-prefixed output vector
/// @return True if it represents a validly formatted vout
function validateVout(bytes memory _vout) internal pure returns (bool) {
uint256 _varIntDataLen;
uint256 _nOuts;
(_varIntDataLen, _nOuts) = parseVarInt(_vout);
// Not valid if it says there are too many or no outputs
if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) {
return false;
}
uint256 _offset = 1 + _varIntDataLen;
for (uint256 i = 0; i < _nOuts; i++) {
// If we're at the end, but still expect more
if (_offset >= _vout.length) {
return false;
}
// Grab the next output and determine its length.
// Increase the offset by that much
uint256 _nextLen = determineOutputLengthAt(_vout, _offset);
if (_nextLen == ERR_BAD_ARG) {
return false;
}
_offset += _nextLen;
}
// Returns false if we're not exactly at the end
return _offset == _vout.length;
}
/* ************ */
/* Block Header */
/* ************ */
/// @notice Extracts the transaction merkle root from a block header
/// @dev Use verifyHash256Merkle to verify proofs with this root
/// @param _header The header
/// @return The merkle root (little-endian)
function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes32) {
return _header.slice32(36);
}
/// @notice Extracts the target from a block header
/// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent
/// @param _header The header
/// @return The target threshold
function extractTarget(bytes memory _header) internal pure returns (uint256) {
return extractTargetAt(_header, 0);
}
/// @notice Extracts the target from a block header
/// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent
/// @param _header The array containing the header
/// @param at The start of the header
/// @return The target threshold
function extractTargetAt(bytes memory _header, uint256 at) internal pure returns (uint256) {
uint24 _m = uint24(_header.slice3(72 + at));
uint8 _e = uint8(_header[75 + at]);
uint256 _mantissa = uint256(reverseUint24(_m));
uint256 _exponent = _e - 3;
return _mantissa * (256 ** _exponent);
}
/// @notice Calculate difficulty from the difficulty 1 target and current target
/// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet
/// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent
/// @param _target The current target
/// @return The block difficulty (bdiff)
function calculateDifficulty(uint256 _target) internal pure returns (uint256) {
// Difficulty 1 calculated from 0x1d00ffff
return DIFF1_TARGET.div(_target);
}
/// @notice Extracts the previous block's hash from a block header
/// @dev Block headers do NOT include block number :(
/// @param _header The header
/// @return The previous block's hash (little-endian)
function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes32) {
return _header.slice32(4);
}
/// @notice Extracts the previous block's hash from a block header
/// @dev Block headers do NOT include block number :(
/// @param _header The array containing the header
/// @param at The start of the header
/// @return The previous block's hash (little-endian)
function extractPrevBlockLEAt(bytes memory _header, uint256 at) internal pure returns (bytes32) {
return _header.slice32(4 + at);
}
/// @notice Extracts the timestamp from a block header
/// @dev Time is not 100% reliable
/// @param _header The header
/// @return The timestamp (little-endian bytes)
function extractTimestampLE(bytes memory _header) internal pure returns (bytes4) {
return _header.slice4(68);
}
/// @notice Extracts the timestamp from a block header
/// @dev Time is not 100% reliable
/// @param _header The header
/// @return The timestamp (uint)
function extractTimestamp(bytes memory _header) internal pure returns (uint32) {
return reverseUint32(uint32(extractTimestampLE(_header)));
}
/// @notice Extracts the expected difficulty from a block header
/// @dev Does NOT verify the work
/// @param _header The header
/// @return The difficulty as an integer
function extractDifficulty(bytes memory _header) internal pure returns (uint256) {
return calculateDifficulty(extractTarget(_header));
}
/// @notice Concatenates and hashes two inputs for merkle proving
/// @param _a The first hash
/// @param _b The second hash
/// @return The double-sha256 of the concatenated hashes
function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal view returns (bytes32) {
return hash256View(abi.encodePacked(_a, _b));
}
/// @notice Concatenates and hashes two inputs for merkle proving
/// @param _a The first hash
/// @param _b The second hash
/// @return The double-sha256 of the concatenated hashes
function _hash256MerkleStep(bytes32 _a, bytes32 _b) internal view returns (bytes32) {
return hash256Pair(_a, _b);
}
/// @notice Verifies a Bitcoin-style merkle tree
/// @dev Leaves are 0-indexed. Inefficient version.
/// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root
/// @param _index The index of the leaf
/// @return true if the proof is valid, else false
function verifyHash256Merkle(bytes memory _proof, uint256 _index) internal view returns (bool) {
// Not an even number of hashes
if (_proof.length % 32 != 0) {
return false;
}
// Special case for coinbase-only blocks
if (_proof.length == 32) {
return true;
}
// Should never occur
if (_proof.length == 64) {
return false;
}
bytes32 _root = _proof.slice32(_proof.length - 32);
bytes32 _current = _proof.slice32(0);
bytes memory _tree = _proof.slice(32, _proof.length - 64);
return verifyHash256Merkle(_current, _tree, _root, _index);
}
/// @notice Verifies a Bitcoin-style merkle tree
/// @dev Leaves are 0-indexed. Efficient version.
/// @param _leaf The leaf of the proof. LE sha256 hash.
/// @param _tree The intermediate nodes in the proof.
/// Tightly packed LE sha256 hashes.
/// @param _root The root of the proof. LE sha256 hash.
/// @param _index The index of the leaf
/// @return true if the proof is valid, else false
function verifyHash256Merkle(bytes32 _leaf, bytes memory _tree, bytes32 _root, uint256 _index)
internal
view
returns (bool)
{
// Not an even number of hashes
if (_tree.length % 32 != 0) {
return false;
}
// Should never occur
if (_tree.length == 0) {
return false;
}
uint256 _idx = _index;
bytes32 _current = _leaf;
// i moves in increments of 32
for (uint256 i = 0; i < _tree.length; i += 32) {
if (_idx % 2 == 1) {
_current = _hash256MerkleStep(_tree.slice32(i), _current);
} else {
_current = _hash256MerkleStep(_current, _tree.slice32(i));
}
_idx = _idx >> 1;
}
return _current == _root;
}
/*
NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72
NB: We get a full-bitlength target from this. For comparison with
header-encoded targets we need to mask it with the header target
e.g. (full & truncated) == truncated
*/
/// @notice performs the bitcoin difficulty retarget
/// @dev implements the Bitcoin algorithm precisely
/// @param _previousTarget the target of the previous period
/// @param _firstTimestamp the timestamp of the first block in the difficulty period
/// @param _secondTimestamp the timestamp of the last block in the difficulty period
/// @return the new period's target threshold
function retargetAlgorithm(uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp)
internal
pure
returns (uint256)
{
uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp);
// Normalize ratio to factor of 4 if very long or very short
if (_elapsedTime < RETARGET_PERIOD.div(4)) {
_elapsedTime = RETARGET_PERIOD.div(4);
}
if (_elapsedTime > RETARGET_PERIOD.mul(4)) {
_elapsedTime = RETARGET_PERIOD.mul(4);
}
/*
NB: high targets e.g. ffff0020 can cause overflows here
so we divide it by 256**2, then multiply by 256**2 later
we know the target is evenly divisible by 256**2, so this isn't an issue
*/
uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime);
return _adjusted.div(RETARGET_PERIOD).mul(65536);
}
}
dependencies/@bob-collective-bitcoin-spv-v1/src/BytesLib.sol
pragma solidity ^0.8.4;
/*
https://github.com/GNSPS/solidity-bytes-utils/
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
*/
/**
* @title BytesLib *
*/
/**
* @author https://github.com/GNSPS *
*/
library BytesLib {
function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for { let cc := add(_postBytes, 0x20) } lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} { mstore(mc, mload(cc)) }
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(
0x40,
and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
)
)
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes.slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes.slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes.slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} { sstore(sc, mload(mc)) }
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes.slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} { sstore(sc, mload(mc)) }
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory res) {
if (_length == 0) {
return hex"";
}
uint256 _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
// Alloc bytes array with additional 32 bytes afterspace and assign it's size
res := mload(0x40)
mstore(0x40, add(add(res, 64), _length))
mstore(res, _length)
// Compute distance between source and destination pointers
let diff := sub(res, add(_bytes, _start))
for {
let src := add(add(_bytes, 32), _start)
let end := add(src, _length)
} lt(src, end) { src := add(src, 32) } { mstore(add(src, diff), mload(src)) }
}
}
/// @notice Take a slice of the byte array, overwriting the destination.
/// The length of the slice will equal the length of the destination array.
/// @dev Make sure the destination array has afterspace if required.
/// @param _bytes The source array
/// @param _dest The destination array.
/// @param _start The location to start in the source array.
function sliceInPlace(bytes memory _bytes, bytes memory _dest, uint256 _start) internal pure {
uint256 _length = _dest.length;
uint256 _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
for {
let src := add(add(_bytes, 32), _start)
let res := add(_dest, 32)
let end := add(src, _length)
} lt(src, end) {
src := add(src, 32)
res := add(res, 32)
} { mstore(res, mload(src)) }
}
}
// Static slice functions, no bounds checking
/// @notice take a 32-byte slice from the specified position
function slice32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 res) {
assembly {
res := mload(add(add(_bytes, 32), _start))
}
}
/// @notice take a 20-byte slice from the specified position
function slice20(bytes memory _bytes, uint256 _start) internal pure returns (bytes20) {
return bytes20(slice32(_bytes, _start));
}
/// @notice take a 8-byte slice from the specified position
function slice8(bytes memory _bytes, uint256 _start) internal pure returns (bytes8) {
return bytes8(slice32(_bytes, _start));
}
/// @notice take a 4-byte slice from the specified position
function slice4(bytes memory _bytes, uint256 _start) internal pure returns (bytes4) {
return bytes4(slice32(_bytes, _start));
}
/// @notice take a 3-byte slice from the specified position
function slice3(bytes memory _bytes, uint256 _start) internal pure returns (bytes3) {
return bytes3(slice32(_bytes, _start));
}
/// @notice take a 2-byte slice from the specified position
function slice2(bytes memory _bytes, uint256 _start) internal pure returns (bytes2) {
return bytes2(slice32(_bytes, _start));
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
uint256 _totalLen = _start + 20;
require(_totalLen > _start && _bytes.length >= _totalLen, "Address conversion out of bounds.");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
uint256 _totalLen = _start + 32;
require(_totalLen > _start && _bytes.length >= _totalLen, "Uint conversion out of bounds.");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success = true;
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for { let cc := add(_postBytes, 0x20) }
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes.slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function toBytes32(bytes memory _source) internal pure returns (bytes32 result) {
if (_source.length == 0) {
return 0x0;
}
assembly {
result := mload(add(_source, 32))
}
}
function keccak256Slice(bytes memory _bytes, uint256 _start, uint256 _length)
internal
pure
returns (bytes32 result)
{
uint256 _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
result := keccak256(add(add(_bytes, 32), _start), _length)
}
}
}
dependencies/@bob-collective-bitcoin-spv-v1/src/SafeMath.sol
pragma solidity ^0.8.4;
/*
The MIT License (MIT)
Copyright (c) 2016 Smart Contract Solutions, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
require(c / _a == _b, "Overflow during multiplication.");
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, "Underflow during subtraction.");
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
require(c >= _a, "Overflow during addition.");
return c;
}
}
dependencies/@bob-collective-bitcoin-spv-v1/src/ValidateSPV.sol
pragma solidity ^0.8.4;
/**
* @title ValidateSPV
*/
/**
* @author Summa (https://summa.one)
*/
import {BytesLib} from "./BytesLib.sol";
import {SafeMath} from "./SafeMath.sol";
import {BTCUtils} from "./BTCUtils.sol";
library ValidateSPV {
using BTCUtils for bytes;
using BTCUtils for uint256;
using BytesLib for bytes;
using SafeMath for uint256;
enum InputTypes {
NONE,
LEGACY,
COMPATIBILITY,
WITNESS
}
enum OutputTypes {
NONE,
WPKH,
WSH,
OP_RETURN,
PKH,
SH,
NONSTANDARD
}
uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe;
uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd;
function getErrBadLength() internal pure returns (uint256) {
return ERR_BAD_LENGTH;
}
function getErrInvalidChain() internal pure returns (uint256) {
return ERR_INVALID_CHAIN;
}
function getErrLowWork() internal pure returns (uint256) {
return ERR_LOW_WORK;
}
/// @notice Validates a tx inclusion in the block
/// @dev `index` is not a reliable indicator of location within a block
/// @param _txid The txid (LE)
/// @param _merkleRoot The merkle root (as in the block header)
/// @param _intermediateNodes The proof's intermediate nodes (digests between leaf and root)
/// @param _index The leaf's index in the tree (0-indexed)
/// @return true if fully valid, false otherwise
function prove(bytes32 _txid, bytes32 _merkleRoot, bytes memory _intermediateNodes, uint256 _index)
internal
view
returns (bool)
{
// Shortcut the empty-block case
if (_txid == _merkleRoot && _index == 0 && _intermediateNodes.length == 0) {
return true;
}
// If the Merkle proof failed, bubble up error
return BTCUtils.verifyHash256Merkle(_txid, _intermediateNodes, _merkleRoot, _index);
}
/// @notice Hashes transaction to get txid
/// @dev Supports Legacy and Witness
/// @param _version 4-bytes version
/// @param _vin Raw bytes length-prefixed input vector
/// @param _vout Raw bytes length-prefixed output vector
/// @param _locktime 4-byte tx locktime
/// @return 32-byte transaction id, little endian
function calculateTxId(bytes4 _version, bytes memory _vin, bytes memory _vout, bytes4 _locktime)
internal
view
returns (bytes32)
{
// Get transaction hash double-Sha256(version + nIns + inputs + nOuts + outputs + locktime)
return abi.encodePacked(_version, _vin, _vout, _locktime).hash256View();
}
/// @notice Checks validity of header chain
/// @notice Compares the hash of each header to the prevHash in the next header
/// @param headers Raw byte array of header chain
/// @return totalDifficulty The total accumulated difficulty of the header chain, or an error code
function validateHeaderChain(bytes memory headers) internal view returns (uint256 totalDifficulty) {
// Check header chain length
if (headers.length % 80 != 0) return ERR_BAD_LENGTH;
// Initialize header start index
bytes32 digest;
totalDifficulty = 0;
for (uint256 start = 0; start < headers.length; start += 80) {
// After the first header, check that headers are in a chain
if (start != 0) {
if (!validateHeaderPrevHash(headers, start, digest)) return ERR_INVALID_CHAIN;
}
// ith header target
uint256 target = headers.extractTargetAt(start);
// Require that the header has sufficient work
digest = headers.hash256Slice(start, 80);
if (uint256(digest).reverseUint256() > target) {
return ERR_LOW_WORK;
}
// Add ith header difficulty to difficulty sum
totalDifficulty = totalDifficulty + target.calculateDifficulty();
}
}
/// @notice Checks validity of header work
/// @param digest Header digest
/// @param target The target threshold
/// @return true if header work is valid, false otherwise
function validateHeaderWork(bytes32 digest, uint256 target) internal pure returns (bool) {
if (digest == bytes32(0)) return false;
return (uint256(digest).reverseUint256() < target);
}
/// @notice Checks validity of header chain
/// @dev Compares current header prevHash to previous header's digest
/// @param headers The raw bytes array containing the header
/// @param at The position of the header
/// @param prevHeaderDigest The previous header's digest
/// @return true if the connect is valid, false otherwise
function validateHeaderPrevHash(bytes memory headers, uint256 at, bytes32 prevHeaderDigest)
internal
pure
returns (bool)
{
// Extract prevHash of current header
bytes32 prevHash = headers.extractPrevBlockLEAt(at);
// Compare prevHash of current header to previous header's digest
if (prevHash != prevHeaderDigest) return false;
return true;
}
}
dependencies/@bob-collective-bob-v1/contracts/src/relay/IFullRelay.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.17;
interface IFullRelay {
event Extension(bytes32 indexed _first, bytes32 indexed _last);
event NewTip(bytes32 indexed _from, bytes32 indexed _to, bytes32 indexed _gcd);
function getCurrentEpochDifficulty() external view returns (uint256);
function getPrevEpochDifficulty() external view returns (uint256);
function getRelayGenesis() external view returns (bytes32);
function getBestKnownDigest() external view returns (bytes32);
function getLastReorgCommonAncestor() external view returns (bytes32);
function findHeight(bytes32 _digest) external view returns (uint256);
function findAncestor(bytes32 _digest, uint256 _offset) external view returns (bytes32);
function isAncestor(bytes32 _ancestor, bytes32 _descendant, uint256 _limit) external view returns (bool);
function addHeaders(bytes calldata _anchor, bytes calldata _headers) external returns (bool);
function addHeadersWithRetarget(
bytes calldata _oldPeriodStartHeader,
bytes calldata _oldPeriodEndHeader,
bytes calldata _headers
) external returns (bool);
function markNewHeaviest(bytes32 _ancestor, bytes calldata _currentBest, bytes calldata _newBest, uint256 _limit)
external
returns (bool);
}
dependencies/@bob-collective-bob-v1/contracts/src/relay/IFullRelayWithVerify.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.17;
import {IFullRelay} from "./IFullRelay.sol";
interface IFullRelayWithVerify is IFullRelay {
function verifyProof(bytes calldata _header, bytes calldata _proof, bytes32 _txId, uint256 _index, uint8 _numConfs)
external
view;
function verifyHeaderHash(bytes32 _headerHash, uint8 _numConfs) external view;
}
dependencies/@bob-collective-bob-v1/contracts/src/relay/ILightRelay.sol
// SPDX-License-Identifier: GPL-3.0-only
// Forked from https://github.com/keep-network/tbtc-v2s
pragma solidity ^0.8.17;
/// @title Interface for the Bitcoin Light relay
interface ILightRelay {
event Genesis(uint256 blockHeight);
event Retarget(uint256 oldDifficulty, uint256 newDifficulty);
event ProofLengthChanged(uint256 newLength);
event AuthorizationRequirementChanged(bool newStatus);
event SubmitterAuthorized(address submitter);
event SubmitterDeauthorized(address submitter);
function retarget(bytes memory headers) external;
function validateChain(bytes memory headers)
external
view
returns (uint256 startingHeaderTimestamp, uint256 headerCount);
function getBlockDifficulty(uint256 blockNumber) external view returns (uint256);
/// @notice Returns the difficulty of the current epoch.
function getCurrentEpochDifficulty() external view returns (uint256);
/// @notice Returns the difficulty of the previous epoch.
function getPrevEpochDifficulty() external view returns (uint256);
function getRelayRange() external view returns (uint256 relayGenesis, uint256 currentEpochEnd);
}
dependencies/@bob-collective-bob-v1/contracts/src/relay/LightRelay.sol
// SPDX-License-Identifier: GPL-3.0-only
// Forked from https://github.com/keep-network/tbtc-v2
pragma solidity ^0.8.17;
import "@openzeppelin/contracts/access/Ownable.sol";
import {BytesLib} from "@bob-collective/bitcoin-spv/BytesLib.sol";
import {BTCUtils} from "@bob-collective/bitcoin-spv/BTCUtils.sol";
import {ValidateSPV} from "@bob-collective/bitcoin-spv/ValidateSPV.sol";
import {ILightRelay} from "./ILightRelay.sol";
struct Epoch {
uint32 timestamp;
// By definition, bitcoin targets have at least 32 leading zero bits.
// Thus we can only store the bits that aren't guaranteed to be 0.
uint224 target;
}
library RelayUtils {
using BytesLib for bytes;
/// @notice Extract the timestamp of the header at the given position.
/// @param headers Byte array containing the header of interest.
/// @param at The start of the header in the array.
/// @return The timestamp of the header.
/// @dev Assumes that the specified position contains a valid header.
/// Performs no validation whatsoever.
function extractTimestampAt(bytes memory headers, uint256 at) internal pure returns (uint32) {
return BTCUtils.reverseUint32(uint32(headers.slice4(68 + at)));
}
}
/// @title LightRelay Contract
/// @dev The LightRelay contract manages a relay for Bitcoin header information,
/// allowing retargeting and validation of header chains.
/// THE RELAY MUST NOT BE USED BEFORE GENESIS AND AT LEAST ONE RETARGET.
contract LightRelay is Ownable, ILightRelay {
using BytesLib for bytes;
using BTCUtils for bytes;
using ValidateSPV for bytes;
using RelayUtils for bytes;
/// @notice Constructor that sets the initial owner.
/// @param initialOwner The address that will be the initial owner.
constructor(address initialOwner) Ownable(initialOwner) {}
/// @notice Flag indicating whether the relay is ready for use.
bool public ready;
// Whether the relay requires the address submitting a retarget to be
// authorised in advance by governance.
/// @notice Flag indicating whether authorization is required for retarget submitters.
bool public authorizationRequired;
/// @notice Number of blocks required for each side of a retarget proof.
// A retarget must provide `proofLength` blocks before the retarget
// and `proofLength` blocks after it.
// Governable
// Should be set to a fairly high number (e.g. 20-50) in production.
uint64 public proofLength;
/// @notice The number of the first epoch recorded by the relay.
// This should equal the height of the block starting the genesis epoch,
// divided by 2016, but this is not enforced as the relay has no
// information about block numbers.
uint64 public genesisEpoch;
/// @notice The number of the latest epoch whose difficulty is proven to the relay.
// If the genesis epoch's number is set correctly, and retargets along the
// way have been legitimate, this equals the height of the block starting
// the most recent epoch, divided by 2016.
uint64 public currentEpoch;
/// @notice Difficulty of the current epoch.
uint256 internal currentEpochDifficulty;
/// @notice Difficulty of the previous epoch.
uint256 internal prevEpochDifficulty;
/// @notice Mapping of each epoch from genesis to the current one, keyed by their numbers.
mapping(uint256 => Epoch) internal epochs;
/// @notice Mapping of authorized submitters.
mapping(address => bool) public isAuthorized;
/// @notice Modifier to check if the relay is active.
modifier relayActive() {
require(ready, "Relay is not ready for use");
_;
}
/// @notice Establish a starting point for the relay by providing the
/// target, timestamp and blockheight of the first block of the relay
/// genesis epoch.
/// @param genesisHeader The first block header of the genesis epoch.
/// @param genesisHeight The block number of the first block of the epoch.
/// @param genesisProofLength The number of blocks required to accept a
/// proof.
/// @dev If the relay is used by querying the current and previous epoch
/// difficulty, at least one retarget needs to be provided after genesis;
/// otherwise the prevEpochDifficulty will be uninitialised and zero.
function genesis(bytes calldata genesisHeader, uint256 genesisHeight, uint64 genesisProofLength)
external
onlyOwner
{
require(!ready, "Genesis already performed");
require(genesisHeader.length == 80, "Invalid genesis header length");
require(genesisHeight % 2016 == 0, "Invalid height of relay genesis block");
require(genesisProofLength < 2016, "Proof length excessive");
require(genesisProofLength > 0, "Proof length may not be zero");
genesisEpoch = uint64(genesisHeight / 2016);
currentEpoch = genesisEpoch;
uint256 genesisTarget = genesisHeader.extractTarget();
uint256 genesisTimestamp = genesisHeader.extractTimestamp();
epochs[genesisEpoch] = Epoch(uint32(genesisTimestamp), uint224(genesisTarget));
proofLength = genesisProofLength;
currentEpochDifficulty = BTCUtils.calculateDifficulty(genesisTarget);
ready = true;
emit Genesis(genesisHeight);
}
/// @notice Set the number of blocks required to accept a header chain.
/// @param newLength The required number of blocks. Must be less than 2016.
/// @dev For production, a high number (e.g. 20-50) is recommended.
/// Small numbers are accepted but should only be used for testing.
function setProofLength(uint64 newLength) external relayActive onlyOwner {
require(newLength < 2016, "Proof length excessive");
require(newLength > 0, "Proof length may not be zero");
require(newLength != proofLength, "Proof length unchanged");
proofLength = newLength;
emit ProofLengthChanged(newLength);
}
/// @notice Set whether the relay requires retarget submitters to be
/// pre-authorised by governance.
/// @param status True if authorisation is to be required, false if not.
function setAuthorizationStatus(bool status) external onlyOwner {
authorizationRequired = status;
emit AuthorizationRequirementChanged(status);
}
/// @notice Authorise the given address to submit retarget proofs.
/// @param submitter The address to be authorised.
function authorize(address submitter) external onlyOwner {
isAuthorized[submitter] = true;
emit SubmitterAuthorized(submitter);
}
/// @notice Rescind the authorisation of the submitter to retarget.
/// @param submitter The address to be deauthorised.
function deauthorize(address submitter) external onlyOwner {
isAuthorized[submitter] = false;
emit SubmitterDeauthorized(submitter);
}
/// @notice Add a new epoch to the relay by providing a proof
/// of the difficulty before and after the retarget.
/// @param headers A chain of headers including the last X blocks before
/// the retarget, followed by the first X blocks after the retarget,
/// where X equals the current proof length.
/// @dev Checks that the first X blocks are valid in the most recent epoch,
/// that the difficulty of the new epoch is calculated correctly according
/// to the block timestamps, and that the next X blocks would be valid in
/// the new epoch.
/// We have no information of block heights, so we cannot enforce that
/// retargets only happen every 2016 blocks; instead, we assume that this
/// is the case if a valid proof of work is provided.
/// It is possible to cheat the relay by providing X blocks from earlier in
/// the most recent epoch, and then mining X new blocks after them.
/// However, each of these malicious blocks would have to be mined to a
/// higher difficulty than the legitimate ones.
/// Alternatively, if the retarget has not been performed yet, one could
/// first mine X blocks in the old difficulty with timestamps set far in
/// the future, and then another X blocks at a greatly reduced difficulty.
/// In either case, cheating the relay requires more work than mining X
/// legitimate blocks.
/// Only the most recent epoch is vulnerable to these attacks; once a
/// retarget has been proven to the relay, the epoch is immutable even if a
/// contradictory proof were to be presented later.
function retarget(bytes memory headers) external relayActive {
if (authorizationRequired) {
require(isAuthorized[msg.sender], "Submitter unauthorized");
}
require(
// Require proofLength headers on both sides of the retarget
headers.length == (proofLength * 2 * 80),
"Invalid header length"
);
Epoch storage latest = epochs[currentEpoch];
uint256 oldTarget = latest.target;
bytes32 previousHeaderDigest = bytes32(0);
// Validate old chain
for (uint256 i = 0; i < proofLength; i++) {
(bytes32 currentDigest, uint256 currentHeaderTarget) = validateHeader(headers, i * 80, previousHeaderDigest);
require(currentHeaderTarget == oldTarget, "Invalid target in pre-retarget headers");
previousHeaderDigest = currentDigest;
}
// get timestamp of retarget block
uint256 epochEndTimestamp = headers.extractTimestampAt((proofLength - 1) * 80);
// An attacker could produce blocks with timestamps in the future,
// in an attempt to reduce the difficulty after the retarget
// to make mining the second part of the retarget proof easier.
// In particular, the attacker could reuse all but one block
// from the legitimate chain, and only mine the last block.
// To hinder this, require that the epoch end timestamp does not
// exceed the ethereum timestamp.
// NOTE: both are unix seconds, so this comparison should be valid.
require(
/* solhint-disable-next-line not-rely-on-time */
epochEndTimestamp < block.timestamp,
"Epoch cannot end in the future"
);
// Expected target is the full-length target
uint256 expectedTarget = BTCUtils.retargetAlgorithm(oldTarget, latest.timestamp, epochEndTimestamp);
// Mined target is the header-encoded target
uint256 minedTarget = 0;
uint256 epochStartTimestamp = headers.extractTimestampAt(proofLength * 80);
// validate new chain
for (uint256 j = proofLength; j < proofLength * 2; j++) {
(bytes32 _currentDigest, uint256 _currentHeaderTarget) =
validateHeader(headers, j * 80, previousHeaderDigest);
if (minedTarget == 0) {
// The new target has not been set, so check its correctness
minedTarget = _currentHeaderTarget;
require(
// Although the target is a 256-bit number, there are only 32 bits of
// space in the Bitcoin header. Because of that, the version stored in
// the header is a less-precise representation of the actual target
// using base-256 version of scientific notation.
//
// The 256-bit unsigned integer returned from BTCUtils.retargetAlgorithm
// is the precise target value.
// The 256-bit unsigned integer returned from validateHeader is the less
// precise target value because it was read from 32 bits of space of
// Bitcoin block header.
//
// We can't compare the precise and less precise representations together
// so we first mask them to obtain the less precise version:
// (full & truncated) == truncated
_currentHeaderTarget == (expectedTarget & _currentHeaderTarget),
"Invalid target in new epoch"
);
} else {
// The new target has been set, so remaining targets should match.
require(_currentHeaderTarget == minedTarget, "Unexpected target change after retarget");
}
previousHeaderDigest = _currentDigest;
}
currentEpoch = currentEpoch + 1;
epochs[currentEpoch] = Epoch(uint32(epochStartTimestamp), uint224(minedTarget));
uint256 oldDifficulty = currentEpochDifficulty;
uint256 newDifficulty = BTCUtils.calculateDifficulty(minedTarget);
prevEpochDifficulty = oldDifficulty;
currentEpochDifficulty = newDifficulty;
emit Retarget(oldDifficulty, newDifficulty);
}
/// @notice Check whether a given chain of headers should be accepted as
/// valid within the rules of the relay.
/// If the validation fails, this function throws an exception.
/// @param headers A chain of 2 to 2015 bitcoin headers.
/// @return startingHeaderTimestamp The timestamp of the first header.
/// @return headerCount The number of headers.
/// @dev A chain of headers is accepted as valid if:
/// - Its length is between 2 and 2015 headers.
/// - Headers in the chain are sequential and refer to previous digests.
/// - Each header is mined with the correct amount of work.
/// - The difficulty in each header matches an epoch of the relay,
/// as determined by the headers' timestamps. The headers must be between
/// the genesis epoch and the latest proven epoch (inclusive).
/// If the chain contains a retarget, it is accepted if the retarget has
/// already been proven to the relay.
/// If the chain contains blocks of an epoch that has not been proven to
/// the relay (after a retarget within the header chain, or when the entire
/// chain falls within an epoch that has not been proven yet), it will be
/// rejected.
/// One exception to this is when two subsequent epochs have exactly the
/// same difficulty; headers from the latter epoch will be accepted if the
/// previous epoch has been proven to the relay.
/// This is because it is not possible to distinguish such headers from
/// headers of the previous epoch.
///
/// If the difficulty increases significantly between relay genesis and the
/// present, creating fraudulent proofs for earlier epochs becomes easier.
/// Users of the relay should check the timestamps of valid headers and
/// only accept appropriately recent ones.
function validateChain(bytes memory headers)
external
view
returns (uint256 startingHeaderTimestamp, uint256 headerCount)
{
require(headers.length % 80 == 0, "Invalid header length");
headerCount = headers.length / 80;
require(headerCount > 1 && headerCount < 2016, "Invalid number of headers");
startingHeaderTimestamp = headers.extractTimestamp();
// Short-circuit the first header's validation.
// We validate the header here to get the target which is needed to
// precisely identify the epoch.
(bytes32 previousHeaderDigest, uint256 currentHeaderTarget) = validateHeader(headers, 0, bytes32(0));
Epoch memory nullEpoch = Epoch(0, 0);
uint256 startingEpochNumber = currentEpoch;
Epoch memory startingEpoch = epochs[startingEpochNumber];
Epoch memory nextEpoch = nullEpoch;
// Find the correct epoch for the given chain
// Fastest with recent epochs, but able to handle anything after genesis
//
// The rules for bitcoin timestamps are:
// - must be greater than the median of the last 11 blocks' timestamps
// - must be less than the network-adjusted time +2 hours
//
// Because of this, the timestamp of a header may be smaller than the
// starting time, or greater than the ending time of its epoch.
// However, a valid timestamp is guaranteed to fall within the window
// formed by the epochs immediately before and after its timestamp.
// We can identify cases like these by comparing the targets.
while (startingHeaderTimestamp < startingEpoch.timestamp) {
startingEpochNumber -= 1;
nextEpoch = startingEpoch;
startingEpoch = epochs[startingEpochNumber];
}
// We have identified the centre of the window,
// by reaching the most recent epoch whose starting timestamp
// or reached before the genesis where epoch slots are empty.
// Therefore check that the timestamp is nonzero.
require(startingEpoch.timestamp > 0, "Cannot validate chains before relay genesis");
// The targets don't match. This could be because the block is invalid,
// or it could be because of timestamp inaccuracy.
// To cover the latter case, check adjacent epochs.
if (currentHeaderTarget != startingEpoch.target) {
// The target matches the next epoch.
// This means we are right at the beginning of the next epoch,
// and retargets during the chain should not be possible.
if (currentHeaderTarget == nextEpoch.target) {
startingEpoch = nextEpoch;
nextEpoch = nullEpoch;
}
// The target doesn't match the next epoch.
// Therefore the only valid epoch is the previous one.
// Because the timestamp can't be more than 2 hours into the future
// we must be right near the end of the epoch,
// so a retarget is possible.
else {
startingEpochNumber -= 1;
nextEpoch = startingEpoch;
startingEpoch = epochs[startingEpochNumber];
// We have failed to find a match,
// therefore the target has to be invalid.
require(currentHeaderTarget == startingEpoch.target, "Invalid target in header chain");
}
}
// We've found the correct epoch for the first header.
// Validate the rest.
for (uint256 i = 1; i < headerCount; i++) {
bytes32 currentDigest;
(currentDigest, currentHeaderTarget) = validateHeader(headers, i * 80, previousHeaderDigest);
// If the header's target does not match the expected target,
// check if a retarget is possible.
//
// If next epoch timestamp exists, a valid retarget is possible
// (if next epoch timestamp doesn't exist, either a retarget has
// already happened in this chain, the relay needs a retarget
// before this chain can be validated, or a retarget is not allowed
// because we know the headers are within a timestamp irregularity
// of the previous retarget).
//
// In this case the target must match the next epoch's target,
// and the header's timestamp must match the epoch's start.
if (currentHeaderTarget != startingEpoch.target) {
uint256 currentHeaderTimestamp = headers.extractTimestampAt(i * 80);
require(
nextEpoch.timestamp != 0 && currentHeaderTarget == nextEpoch.target
&& currentHeaderTimestamp == nextEpoch.timestamp,
"Invalid target in header chain"
);
startingEpoch = nextEpoch;
nextEpoch = nullEpoch;
}
previousHeaderDigest = currentDigest;
}
return (startingHeaderTimestamp, headerCount);
}
/// @notice Get the difficulty of the specified block.
/// @param blockNumber The number of the block. Must fall within the relay
/// range (at or after the relay genesis, and at or before the end of the
/// most recent epoch proven to the relay).
/// @return The difficulty of the epoch.
function getBlockDifficulty(uint256 blockNumber) external view returns (uint256) {
return getEpochDifficulty(blockNumber / 2016);
}
/// @notice Get the range of blocks the relay can accept proofs for.
/// @dev Assumes that the genesis has been set correctly.
/// Additionally, if the next epoch after the current one has the exact
/// same difficulty, headers for it can be validated as well.
/// This function should be used for informative purposes,
/// e.g. to determine whether a retarget must be provided before submitting
/// a header chain for validation.
/// @return relayGenesis The height of the earliest block that can be
/// included in header chains for the relay to validate.
/// @return currentEpochEnd The height of the last block that can be
/// included in header chains for the relay to validate.
function getRelayRange() external view returns (uint256 relayGenesis, uint256 currentEpochEnd) {
relayGenesis = genesisEpoch * 2016;
currentEpochEnd = (currentEpoch * 2016) + 2015;
}
/// @notice Returns the difficulty of the current epoch.
/// @dev returns 0 if the relay is not ready.
/// @return The difficulty of the current epoch.
function getCurrentEpochDifficulty() external view virtual returns (uint256) {
return currentEpochDifficulty;
}
/// @notice Returns the difficulty of the previous epoch.
/// @dev Returns 0 if the relay is not ready or has not had a retarget.
/// @return The difficulty of the previous epoch.
function getPrevEpochDifficulty() external view virtual returns (uint256) {
return prevEpochDifficulty;
}
function getCurrentAndPrevEpochDifficulty() external view returns (uint256 current, uint256 previous) {
return (currentEpochDifficulty, prevEpochDifficulty);
}
/// @notice Get the difficulty of the specified epoch.
/// @param epochNumber The number of the epoch (the height of the first
/// block of the epoch, divided by 2016). Must fall within the relay range.
/// @return The difficulty of the epoch.
function getEpochDifficulty(uint256 epochNumber) public view returns (uint256) {
require(epochNumber >= genesisEpoch, "Epoch is before relay genesis");
require(epochNumber <= currentEpoch, "Epoch is not proven to the relay yet");
return BTCUtils.calculateDifficulty(epochs[epochNumber].target);
}
/// @notice Check that the specified header forms a correct chain with the
/// digest of the previous header (if provided), and has sufficient work.
/// @param headers The byte array containing the header of interest.
/// @param start The start of the header in the array.
/// @param prevDigest The digest of the previous header
/// (optional; providing zeros for the digest skips the check).
/// @return digest The digest of the current header.
/// @return target The PoW target of the header.
/// @dev Throws an exception if the header's chain or PoW are invalid.
/// Performs no other validation.
function validateHeader(bytes memory headers, uint256 start, bytes32 prevDigest)
internal
view
returns (bytes32 digest, uint256 target)
{
// If previous block digest has been provided, require that it matches
if (prevDigest != bytes32(0)) {
require(headers.validateHeaderPrevHash(start, prevDigest), "Invalid chain");
}
// Require that the header has sufficient work for its stated target
target = headers.extractTargetAt(start);
digest = headers.hash256Slice(start, 80);
require(ValidateSPV.validateHeaderWork(digest, target), "Invalid work");
return (digest, target);
}
}
dependencies/@bob-collective-bob-v1/contracts/src/utils/BitcoinTx.sol
// SPDX-License-Identifier: GPL-3.0-only
// Forked from https://github.com/keep-network/tbtc-v2
pragma solidity ^0.8.17;
import {BTCUtils} from "@bob-collective/bitcoin-spv/BTCUtils.sol";
import {BytesLib} from "@bob-collective/bitcoin-spv/BytesLib.sol";
import {ValidateSPV} from "@bob-collective/bitcoin-spv/ValidateSPV.sol";
import {ILightRelay} from "../relay/ILightRelay.sol";
import {IFullRelayWithVerify} from "../relay/IFullRelayWithVerify.sol";
/// @title Bitcoin transaction
/// @notice Allows to reference Bitcoin raw transaction in Solidity.
/// @dev See https://developer.bitcoin.org/reference/transactions.html#raw-transaction-format
// Raw Bitcoin transaction data:
// | Bytes | Name | BTC type | Description |
// |--------|--------------|------------------------|---------------------------|
// | 4 | version | int32_t (LE) | TX version number |
// | varies | tx_in_count | compactSize uint (LE) | Number of TX inputs |
// | varies | tx_in | txIn[] | TX inputs |
// | varies | tx_out_count | compactSize uint (LE) | Number of TX outputs |
// | varies | tx_out | txOut[] | TX outputs |
// | 4 | lock_time | uint32_t (LE) | Unix time or block number |
//
// Non-coinbase transaction input (txIn):
//
// | Bytes | Name | BTC type | Description |
// |--------|------------------|------------------------|---------------------------------------------|
// | 36 | previous_output | outpoint | The previous outpoint being spent |
// | varies | script_bytes | compactSize uint (LE) | The number of bytes in the signature script |
// | varies | signature_script | char[] | The signature script, empty for P2WSH |
// | 4 | sequence | uint32_t (LE) | Sequence number |
//
//
// The reference to transaction being spent (outpoint):
//
// | Bytes | Name | BTC type | Description |
// |-------|-------|---------------|------------------------------------------|
// | 32 | hash | char[32] | Hash of the transaction to spend |
// | 4 | index | uint32_t (LE) | Index of the specific output from the TX |
//
//
// Transaction output (txOut):
//
// | Bytes | Name | BTC type | Description |
// |--------|-----------------|-----------------------|--------------------------------------|
// | 8 | value | int64_t (LE) | Number of satoshis to spend |
// | 1+ | pk_script_bytes | compactSize uint (LE) | Number of bytes in the pubkey script |
// | varies | pk_script | char[] | Pubkey script |
//
// compactSize uint format:
//
// | Value | Bytes | Format |
// |-----------------------------------------|-------|----------------------------------------------|
// | >= 0 && <= 252 | 1 | uint8_t |
// | >= 253 && <= 0xffff | 3 | 0xfd followed by the number as uint16_t (LE) |
// | >= 0x10000 && <= 0xffffffff | 5 | 0xfe followed by the number as uint32_t (LE) |
// | >= 0x100000000 && <= 0xffffffffffffffff | 9 | 0xff followed by the number as uint64_t (LE) |
//
// (*) compactSize uint is often references as VarInt)
//
// Coinbase transaction input (txIn):
//
// | Bytes | Name | BTC type | Description |
// |--------|------------------|------------------------|---------------------------------------------|
// | 32 | hash | char[32] | A 32-byte 0x0 null (no previous_outpoint) |
// | 4 | index | uint32_t (LE) | 0xffffffff (no previous_outpoint) |
// | varies | script_bytes | compactSize uint (LE) | The number of bytes in the coinbase script |
// | varies | height | char[] | The block height of this block (BIP34) (*) |
// | varies | coinbase_script | none | Arbitrary data, max 100 bytes |
// | 4 | sequence | uint32_t (LE) | Sequence number
//
// (*) Uses script language: starts with a data-pushing opcode that indicates how many bytes to push to
// the stack followed by the block height as a little-endian unsigned integer. This script must be as
// short as possible, otherwise it may be rejected. The data-pushing opcode will be 0x03 and the total
// size four bytes until block 16,777,216 about 300 years from now.
library BitcoinTx {
using BTCUtils for bytes;
using BTCUtils for uint256;
using BytesLib for bytes;
using ValidateSPV for bytes;
using ValidateSPV for bytes32;
/// @notice Represents Bitcoin transaction data.
struct Info {
/// @notice Bitcoin transaction version.
/// @dev `version` from raw Bitcoin transaction data.
/// Encoded as 4-bytes signed integer, little endian.
bytes4 version;
/// @notice All Bitcoin transaction inputs, prepended by the number of
/// transaction inputs.
/// @dev `tx_in_count | tx_in` from raw Bitcoin transaction data.
///
/// The number of transaction inputs encoded as compactSize
/// unsigned integer, little-endian.
///
/// Note that some popular block explorers reverse the order of
/// bytes from `outpoint`'s `hash` and display it as big-endian.
/// Solidity code expects hashes in little-endian, just like
/// they are represented in a raw Bitcoin transaction.
bytes inputVector;
/// @notice All Bitcoin transaction outputs prepended by the number of
/// transaction outputs.
/// @dev `tx_out_count | tx_out` from raw Bitcoin transaction data.
///
/// The number of transaction outputs encoded as a compactSize
/// unsigned integer, little-endian.
bytes outputVector;
/// @notice Bitcoin transaction locktime.
///
/// @dev `lock_time` from raw Bitcoin transaction data.
/// Encoded as 4-bytes unsigned integer, little endian.
bytes4 locktime;
}
/// @notice Represents data needed to perform a Bitcoin SPV proof.
struct Proof {
/// @notice The merkle proof of transaction inclusion in a block.
bytes merkleProof;
/// @notice Transaction index in the block (0-indexed).
uint256 txIndexInBlock;
/// @notice Single byte-string of 80-byte bitcoin headers,
/// lowest height first.
bytes bitcoinHeaders;
/// @notice The sha256 preimage of the coinbase tx hash
/// i.e. the sha256 hash of the coinbase transaction.
bytes32 coinbasePreimage;
/// @notice The merkle proof of the coinbase transaction.
bytes coinbaseProof;
}
/// @notice Represents info about an unspent transaction output.
struct UTXO {
/// @notice Hash of the transaction the output belongs to.
/// @dev Byte order corresponds to the Bitcoin internal byte order.
bytes32 txHash;
/// @notice Index of the transaction output (0-indexed).
uint32 txOutputIndex;
/// @notice Value of the transaction output.
uint64 txOutputValue;
}
/// @notice Validates the SPV proof of the Bitcoin transaction using a light relay contract.
/// Reverts in case the validation or proof verification fail.
/// @param relay Bitcoin light relay providing the current Bitcoin network difficulty.
/// @param txProofDifficultyFactor The number of confirmations required on the Bitcoin chain.
/// @param txInfo Bitcoin transaction data.
/// @param proof Bitcoin proof data.
/// @return txHash Proven 32-byte transaction hash.
function validateProof(ILightRelay relay, uint256 txProofDifficultyFactor, Info memory txInfo, Proof memory proof)
internal
view
returns (bytes32 txHash)
{
txHash = computeTxHash(txInfo);
verifySPVProof(txHash, proof);
evaluateProofDifficulty(relay, txProofDifficultyFactor, proof.bitcoinHeaders);
return txHash;
}
/// @notice Validates the SPV proof of the Bitcoin transaction using a full relay contract.
/// Reverts in case the validation or proof verification fail.
/// @param relay Bitcoin full relay contract.
/// @param minConfirmations The minimumnumber of confirmations required on the Bitcoin chain stored in the full relay.
/// @param txInfo Bitcoin transaction data.
/// @param proof Bitcoin proof data.
/// @return txHash Proven 32-byte transaction hash.
function validateProof(IFullRelayWithVerify relay, uint256 minConfirmations, Info memory txInfo, Proof memory proof)
internal
view
returns (bytes32 txHash)
{
txHash = computeTxHash(txInfo);
verifySPVProof(txHash, proof);
verifyHeader(relay, minConfirmations, proof.bitcoinHeaders);
return txHash;
}
/// @notice Verifies an SPV proof of a Bitcoin transaction.
/// @param txHash The hash of the transaction to verify.
/// @param proof The proof.
function verifySPVProof(bytes32 txHash, Proof memory proof) internal view {
require(isMerkleArrayValidLength(proof.merkleProof), "Bad merkle array proof");
// Due to a vulnerability in the Bitcoin SPV proof verification detailed here:
// https://bitslog.com/2018/06/09/leaf-node-weakness-in-bitcoin-merkle-tree-design/
// we verify a proof of the coinbase tx in the block as well as the tx we want to verify
// and then ensure that both proofs are the same length.
require(
proof.merkleProof.length == proof.coinbaseProof.length, "Tx not on same level of merkle tree as coinbase"
);
bytes32 root = proof.bitcoinHeaders.extractMerkleRootLE();
require(
txHash.prove(root, proof.merkleProof, proof.txIndexInBlock),
"Tx merkle proof is not valid for provided header and tx hash"
);
bytes32 coinbaseHash = sha256(abi.encodePacked(proof.coinbasePreimage));
// Coinbase tx always has an index of 0
require(
coinbaseHash.prove(root, proof.coinbaseProof, 0),
"Coinbase merkle proof is not valid for provided header and hash"
);
}
/// @notice Validates Bitcoin transaction input and output vectors then computes the hash.
/// @param txInfo Bitcoin transaction data.
/// @return txHash 32-byte transaction hash.
function computeTxHash(Info memory txInfo) internal view returns (bytes32 txHash) {
require(txInfo.inputVector.validateVin(), "Invalid input vector provided");
require(txInfo.outputVector.validateVout(), "Invalid output vector provided");
return abi.encodePacked(txInfo.version, txInfo.inputVector, txInfo.outputVector, txInfo.locktime).hash256View();
}
/// @notice Evaluates the given Bitcoin proof difficulty against the actual
/// Bitcoin chain difficulty provided by the light relay oracle.
/// Reverts in case the evaluation fails.
/// @param relay Bitcoin light relay providing the current Bitcoin network difficulty.
/// @param txProofDifficultyFactor The number of confirmations required on the Bitcoin chain.
/// @param bitcoinHeaders Bitcoin headers chain being part of the SPV
/// proof. Used to extract the observed proof difficulty.
function evaluateProofDifficulty(ILightRelay relay, uint256 txProofDifficultyFactor, bytes memory bitcoinHeaders)
internal
view
{
uint256 currentEpochDifficulty = relay.getCurrentEpochDifficulty();
uint256 previousEpochDifficulty = relay.getPrevEpochDifficulty();
uint256 requestedDiff = 0;
uint256 firstHeaderDiff = bitcoinHeaders.extractTarget().calculateDifficulty();
if (firstHeaderDiff == currentEpochDifficulty) {
requestedDiff = currentEpochDifficulty;
} else if (firstHeaderDiff == previousEpochDifficulty) {
requestedDiff = previousEpochDifficulty;
} else {
revert("Not at current or previous difficulty");
}
uint256 observedDiff = bitcoinHeaders.validateHeaderChain();
require(observedDiff != ValidateSPV.getErrBadLength(), "Invalid length of the headers chain");
require(observedDiff != ValidateSPV.getErrInvalidChain(), "Invalid headers chain");
require(observedDiff != ValidateSPV.getErrLowWork(), "Insufficient work in a header");
require(
observedDiff >= requestedDiff * txProofDifficultyFactor,
"Insufficient accumulated difficulty in header chain"
);
}
/// @notice Validates the header using the full relay contract by checking it against the chain stored in the full relay.
/// @param relay Bitcoin full relay contract.
/// @param minConfirmations The minimum number of confirmations required on the Bitcoin chain stored in the full relay.
/// @param bitcoinHeader Bitcoin header to verify.
function verifyHeader(IFullRelayWithVerify relay, uint256 minConfirmations, bytes memory bitcoinHeader)
internal
view
{
require(isHeaderValidLength(bitcoinHeader), "Bad header block");
bytes32 headerHash = bitcoinHeader.hash256();
relay.verifyHeaderHash(headerHash, uint8(minConfirmations));
}
/// @notice Represents temporary information needed during the processing of
/// the Bitcoin transaction outputs. This structure is an internal one
/// and should not be exported outside of the transaction processing code.
/// @dev Allows to mitigate "stack too deep" errors on EVM.
struct TxOutputsProcessingInfo {
// The first output starting index in the transaction.
uint256 outputStartingIndex;
// The number of outputs in the transaction.
uint256 outputsCount;
}
/// @notice Represents an outcome of the Bitcoin transaction
/// outputs processing.
struct TxOutputsInfo {
// Sum of all outputs values spending to the output.
uint64 value;
// Optional EVM address specified in OP_RETURN.
address evmAddress;
// Optional hash specified in OP_RETURN.
bytes32 hash;
}
/// @notice Processes all outputs from the transaction.
/// @param txOutputVector Bitcoin transaction output vector. This function
/// assumes vector's structure is valid so it must be validated using
/// e.g. `BTCUtils.validateVout` function before it is passed here.
/// @param scriptPubKeyHash Expected Bitcoin scriptPubKey keccak256 hash.
function processTxOutputs(bytes memory txOutputVector, bytes32 scriptPubKeyHash)
internal
pure
returns (TxOutputsInfo memory resultInfo)
{
// needed to avoid stack too deep errors
TxOutputsProcessingInfo memory processInfo;
// Determining the total number of transaction outputs in the same way as
// for number of inputs. See `BitcoinTx.outputVector` docs for more details.
(processInfo.outputStartingIndex, processInfo.outputsCount) = txOutputVector.parseVarInt();
// To determine the first output starting index, we must jump over
// the compactSize uint which prepends the output vector. One byte
// must be added because `BtcUtils.parseVarInt` does not include
// compactSize uint tag in the returned length.
//
// For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
// returns `0`, so we jump over one byte of compactSize uint.
//
// For >= 253 && <= 0xffff there is `0xfd` tag,
// `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
// tag byte included) so we need to jump over 1+2 bytes of
// compactSize uint.
//
// Please refer `BTCUtils` library and compactSize uint
// docs in `BitcoinTx` library for more details.
processInfo.outputStartingIndex++;
// Helper flag indicating whether there was at least one
// output present
bool outputPresent = false;
// Outputs processing loop.
for (uint256 i = 0; i < processInfo.outputsCount; i++) {
uint256 outputLength = txOutputVector.determineOutputLengthAt(processInfo.outputStartingIndex);
// Extract the value from given output.
uint64 outputValue = txOutputVector.extractValueAt(processInfo.outputStartingIndex);
// The output consists of an 8-byte value and a variable length
// script. To hash that script we slice the output starting from
// 9th byte until the end.
uint256 scriptLength = outputLength - 8;
uint256 outputScriptStart = processInfo.outputStartingIndex + 8;
bytes32 outputScriptHash;
/* solhint-disable-next-line no-inline-assembly */
assembly {
// The first argument to assembly keccak256 is the pointer.
// We point to `txOutputVector` but at the position indicated
// by `outputScriptStart`. To load that position, we
// need to call `add(outputScriptStart, 32)` because
// `outputScriptStart` has 32 bytes.
outputScriptHash := keccak256(add(txOutputVector, add(outputScriptStart, 32)), scriptLength)
}
if (scriptPubKeyHash == outputScriptHash) {
outputPresent = true;
// Accumulate the total in case there are multiple
// payments to the same output
resultInfo.value += outputValue;
} else {
address outputEvmAddress = extractEvmAddressFromOutput(txOutputVector, processInfo.outputStartingIndex);
if (outputEvmAddress != address(0)) {
// NOTE: this will overwrite if there are multiple OP_RETURN outputs
resultInfo.evmAddress = outputEvmAddress;
}
bytes32 outputHash = extractHashFromOutput(txOutputVector, processInfo.outputStartingIndex);
if (outputHash != 0) {
// NOTE: this will overwrite if there are multiple OP_RETURN outputs
resultInfo.hash = outputHash;
}
}
// Make the `outputStartingIndex` pointing to the next output by
// increasing it by current output's length.
processInfo.outputStartingIndex += outputLength;
}
require(outputPresent, "No output found for scriptPubKey");
}
function extractEvmAddressFromOutput(bytes memory _output, uint256 _at)
internal
pure
returns (address evmAddress)
{
// OP_RETURN
if (_output[_at + 9] != hex"6a") {
return address(0);
}
bytes1 _dataLen = _output[_at + 10];
if (uint256(uint8(_dataLen)) == 20) {
uint256 opReturnStart = _at + 11;
assembly {
evmAddress := mload(add(_output, add(opReturnStart, 20)))
}
}
}
function extractHashFromOutput(bytes memory _output, uint256 _at) internal pure returns (bytes32 outputHash) {
// OP_RETURN
if (_output[_at + 9] != hex"6a") {
return 0;
}
bytes1 _dataLen = _output[_at + 10];
if (uint256(uint8(_dataLen)) == 32) {
uint256 opReturnStart = _at + 11;
assembly {
outputHash := mload(add(_output, add(opReturnStart, 32)))
}
}
}
function reverseEndianness(bytes32 b) internal pure returns (bytes32 txHash) {
bytes memory newValue = new bytes(b.length);
for (uint256 i = 0; i < b.length; i++) {
newValue[b.length - i - 1] = b[i];
}
assembly {
txHash := mload(add(newValue, 32))
}
}
function ensureTxInputSpendsUtxo(bytes memory _vin, BitcoinTx.UTXO memory utxo) internal pure {
uint256 _varIntDataLen;
uint256 _nIns;
(_varIntDataLen, _nIns) = BTCUtils.parseVarInt(_vin);
require(_varIntDataLen != BTCUtils.ERR_BAD_ARG, "Read overrun during VarInt parsing");
uint256 _len = 0;
uint256 _offset = 1 + _varIntDataLen;
bytes32 expectedTxHash = reverseEndianness(utxo.txHash);
for (uint256 _i = 0; _i < _nIns; _i++) {
bytes32 outpointTxHash = _vin.extractInputTxIdLeAt(_offset);
uint32 outpointIndex = BTCUtils.reverseUint32(uint32(_vin.extractTxIndexLeAt(_offset)));
// check if it matches tx
if (expectedTxHash == outpointTxHash && utxo.txOutputIndex == outpointIndex) {
return;
}
_len = BTCUtils.determineInputLengthAt(_vin, _offset);
require(_len != BTCUtils.ERR_BAD_ARG, "Bad VarInt in scriptSig");
_offset = _offset + _len;
}
revert("Transaction does not spend the required utxo");
}
/// @notice Checks whether the header is 80 bytes long
/// @param _header The header for which the length is checked
/// @return True if the header's length is 80 bytes, and false otherwise
function isHeaderValidLength(bytes memory _header) internal pure returns (bool) {
return _header.length == 80;
}
/// @notice Checks whether the merkle proof array's length is a multiple of 32 bytes
/// @param _merkleProofArray The merkle proof array for which the length is checked
/// @return True if the merkle proof array's length is a multiple of 32 bytes, and false otherwise
function isMerkleArrayValidLength(bytes memory _merkleProofArray) internal pure returns (bool) {
return _merkleProofArray.length % 32 == 0;
}
}
dependencies/@openzeppelin-contracts-5.5.0/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
dependencies/@openzeppelin-contracts-5.5.0/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
dependencies/@openzeppelin-contracts-5.5.0/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
dependencies/@openzeppelin-contracts-5.5.0/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
dependencies/@openzeppelin-contracts-5.5.0/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
dependencies/@openzeppelin-contracts-5.5.0/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
dependencies/@openzeppelin-contracts-5.5.0/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
* return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
* value: the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
* the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
dependencies/@openzeppelin-contracts-5.5.0/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
dependencies/@openzeppelin-contracts-5.5.0/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/CommonStructs.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {IStrategy} from "./strategy/IStrategy.sol";
import {IERC20Ext} from "./IERC20Ext.sol";
import {ISwapper} from "./swapper/ISwapper.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {BitcoinTx} from "@bob-collective/bob/utils/BitcoinTx.sol";
struct OnrampOrderArgs {
uint256 tokenFillAmount; // The amount of tokens that will be sent by the LP to fill the order, already net of the protocol, affiliate and solver fees.
IStrategy strategy; // The address of the strategy that will be called when the order is filled, zero address if there is no strategy
uint256 tokenWithheldForGasAmount; // The portion of the fill the solver retains to reimburse its gas. Never transferred into the onramp contract: the release pulls only the payout.
bytes32 recipient; // The recipient identifier passed to the strategy (supports non-EVM destinations)
bytes strategyExtraData; // Calldata for the strategy call
}
// Arguments required to submit an offramp order.
struct OfframpOrderArgs {
uint256 tokenAmountToLock; // Total token amount locked by the user
uint256 minimumTokenAmountToLock; // Solver-approved floor; tokenAmountToLock must be >= this. For cross-chain
// compose flows (LayerZero/Bungee/Across/Velora) the real lock amount is only known at
// execution time, after a swap or bridge whose output the solver cannot predict when it
// signs the corresponding OfframpOrderSignedData, so the solver signs this floor instead.
uint256 satOutputMinimum; // Minimum amount of sats of BTC that the user is willing to receive from the order, taking into account all fees and the token/BTC exchange rate
FeeDetails[] affiliateFees; // Affiliate fee details
uint256 creationDeadline; // Timestamp that the order must be created by
bytes outputScript; // User's Bitcoin output script (scriptPubKey)
address token; // Address of the token that will be used to pay the solver for filling the order
address owner; // Address of the order owner, can bump the order fee or request a refund
uint256 nonce; // Per-order uniqueness salt included in the solver's EIP-712 approval
}
// The fields of `OfframpOrderArgs` that the solver signs off-chain (EIP-712) to approve an order
// before it is escrowed on-chain. `tokenAmountToLock` is intentionally excluded — see the comment
// on `OfframpOrderArgs.minimumTokenAmountToLock` above. `nonce` ensures each approval digest is
// unique even when all other signed fields match a prior order.
struct OfframpOrderSignedData {
uint256 nonce;
uint256 minimumTokenAmountToLock;
uint256 satOutputMinimum;
FeeDetails[] affiliateFees;
uint256 creationDeadline;
bytes outputScript;
address token;
address owner;
}
struct OfframpOrderDetails {
uint256 tokenAmountToLock; // Total token amount locked by the user
uint256 satOutputMinimum; // Minimum amount of sats of BTC that the user is willing to receive from the order, taking into account all fees and the token/BTC exchange rate
FeeDetails[] affiliateFees; // Affiliate fee details
address owner; // Address of the order owner, can bump the order fee or request a refund
bytes outputScript; // User's Bitcoin output script (scriptPubKey)
OfframpOrderStatus status; // Current status of the order
uint256 timestamp; // Timestamp when the order was created or its fee was last bumped
address token; // Address of the token that will be used to pay the solver for filling the order
}
enum OfframpOrderStatus {
Active, // Order is active and awaiting processing
Processed, // Order has been successfully processed by the solver
Refunded // User has claimed a refund for the order
}
struct FinalizeOfframpOrderArgs {
BitcoinTx.Info txInfo; // Bitcoin transaction information
BitcoinTx.Proof txProof; // SPV proof data for the transaction
uint256 orderId; // ID of the associated off-ramp order
}
struct AssetConfig {
address token;
address pricer;
}
struct FeeDetails {
uint256 amount; // The fee amount, this is a bps value for the protocol fee and a fixed token amount for the affiliate fee
address recipient; // The address of the affiliate fee recipient
}
src/IERC20Ext.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// Extension of the IERC20 interface to include functions that
// almost all ERC20 contract supports.
interface IERC20Ext is IERC20 {
function decimals() external view returns (uint8);
}
src/IGatewayOfframpRegistryV7.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
OfframpOrderDetails,
OfframpOrderArgs,
OfframpOrderStatus,
FinalizeOfframpOrderArgs,
FeeDetails
} from "./CommonStructs.sol";
import {LightRelay} from "@bob-collective/bob/relay/LightRelay.sol";
import {IERC20Ext} from "./IERC20Ext.sol";
interface IGatewayOfframpRegistryV7 {
// ------------------- Events -------------------
event SubmitterAuthorized(address submitter);
event SubmitterDeauthorized(address submitter);
event OrderCreated(
uint256 id,
address sender,
address orderOwner,
address token,
uint256 tokenAmountLocked,
uint256 satOutputMinimum,
FeeDetails[] affiliateFees,
bytes outputScript,
uint256 nonce
);
event OrderRefunded(uint256 orderId, uint256 amount, address token);
event SolverUpdated(address recipient, uint256 minSatToBridge);
event TokenAllowed(address token);
event OrderProcessed(
uint256 orderId,
uint256 amountForSolver,
uint256 amountForProtocol,
uint256 totalAmountForAffiliates,
uint256 btcAmount,
address token
);
event TxProofDifficultyFactorUpdated(uint64 txProofDifficultyFactor);
event ProtocolFeeUpdated(FeeDetails protocolFeeDetails);
event RefundDelayUpdated(uint64 refundDelay);
event OrderSignerUpdated(address indexed orderSigner);
// ------------------- Public State -------------------
/// @notice The version of the registry
function VERSION() external view returns (uint16);
/// @notice Delay before the contract owner can refund an order.
function refundDelay() external view returns (uint64);
/// @notice Minimum configurable refund delay
function MIN_REFUND_DELAY() external view returns (uint64);
/// @notice Maximum configurable refund delay
function MAX_REFUND_DELAY() external view returns (uint64);
/// @notice Address that receives solver payouts on order finalization
function solverRecipient() external view returns (address);
/// @notice Minimum BTC output in sats required for quote calculations
function minSatToBridge() external view returns (uint256);
/// @notice Address authorized to sign EIP-712 offramp order approvals
function orderSigner() external view returns (address);
/// @notice TODO
function MAX_PROTOCOL_FEE() external view returns (uint256);
/// @notice Minimum value for the tx proof difficulty factor
function MIN_FACTOR() external view returns (uint64);
/// @notice Maximum value for the tx proof difficulty factor, set to roughly the number of bitcoin blocks in 1 day
/// @dev This is to ensure there is enough time to execute the order before the claim delay of a week is exceeded
function MAX_FACTOR() external view returns (uint64);
/// @notice Returns true if the tx hash has been spent by an offramp order
/// @param txHash The hash of the bitcoin tx to check
function spentTxHashes(bytes32 txHash) external view returns (bool);
/// @notice Returns true if the given solver-approval EIP-712 digest has already been consumed
/// by a `createOrder` call. Each solver-signed approval can only create one order.
/// @param digest The EIP-712 digest of an `OfframpOrderSignedData`
function usedDigests(bytes32 digest) external view returns (bool);
/// @notice The relay contract
function relay() external view returns (LightRelay);
/// @notice The difficulty factor for the tx proof, which is the minimum number of bitcoin blocks on top of the block containing the offramp order in order to accept it
function txProofDifficultyFactor() external view returns (uint64);
/// @notice The ID of the next order to be created
function nextOrderId() external view returns (uint256);
/// @notice The protocol fee details
function protocolFeeDetails() external view returns (uint256 amount, address recipient);
/// @notice Mapping of authorized submitters
function isAuthorized(address submitter) external view returns (bool);
/// @notice Mapping of allowed tokens, where the value is the multiplier to convert from an amount of sats to the token
function allowedTokens(address token) external view returns (uint256);
// ------------------- View Functions -------------------
/// @notice Returns the details of an offramp order by its ID.
/// @param orderId The ID of the offramp order.
/// @return orderDetails The details of the specified offramp order.
function getOrderDetails(uint256 orderId) external view returns (OfframpOrderDetails memory orderDetails);
// ------------------- Actions -------------------
/// @notice Authorizes an address to finalize offramp orders.
/// @param submitter The address to be authorized.
function authorize(address submitter) external;
/// @notice Deauthorizes an address to finalize offramp orders.
/// @param submitter The address to be deauthorized.
function deauthorize(address submitter) external;
/// @notice Updates the protocol fee details. The fee amount is in bps (e.g., 500 = 5%). Lowest nonzero fee is 1 (0.01%).
/// @param protocolFeeDetails The new fee details (amount in bps and recipient address).
function setProtocolFee(FeeDetails memory protocolFeeDetails) external;
/// @notice Updates the txProofDifficultyFactor used for validating bitcoin transactions.
/// @param txProofDifficultyFactor The required number of BTC confirmations.
function setTxProofDifficultyFactor(uint64 txProofDifficultyFactor) external;
/// @notice Updates the refund delay for active orders.
/// @param refundDelay Lock duration before the contract owner can refund, between MIN_REFUND_DELAY and MAX_REFUND_DELAY.
function setRefundDelay(uint64 refundDelay) external;
/// @notice Sets the solver payout address and minimum sats to bridge.
/// @param recipient The address to receive solver payouts.
/// @param _minSatToBridge The minimum required amount to bridge in sats.
function setSolver(address recipient, uint256 _minSatToBridge) external;
/// @notice Updates the address authorized to sign offramp order approvals.
/// @param signer The new order signer.
function setOrderSigner(address signer) external;
/// @notice Adds a token to the allowlist and calculates its scaling divider based on token decimals.
/// @param token The token to be allowed.
function allowToken(IERC20Ext token) external;
/// @notice Creates a new offramp order.
/// @param offrampOrderArgs The order arguments.
/// @param solverSignature EIP-712 signature from `orderSigner()` over the `OfframpOrderSignedData`
function createOrder(OfframpOrderArgs calldata offrampOrderArgs, bytes calldata solverSignature) external;
/// @notice Refunds an active offramp order after the refund delay has passed. Callable only by the contract owner.
/// This is a trusted mechanism that allows the contract owner to withdraw and manually refund an order to a user.
/// @param orderId The ID of the order.
/// @param receiver The address to receive the funds.
function refundOrder(uint256 orderId, address receiver) external;
/// @notice Finalizes an offramp order by verifying the bitcoin transaction containing the order.
/// @param finalizeOfframpOrderArgs Arguments wrapped into a struct for finalizeOfframpOrder.
function finalizeOfframpOrder(FinalizeOfframpOrderArgs calldata finalizeOfframpOrderArgs) external;
/// @notice Pauses the contract, which prevents creating orders.
function pause() external;
/// @notice Unpauses the contract.
function unpause() external;
}
src/interfaces/IBungeeExecutor.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/**
* @title IBungeeExecutor
* @dev Single-output executor the Socket v3 BungeeReceiver calls after a destination delivery.
* The receiver pre-approves `amount` of `token` to the executor before the call.
*/
interface IBungeeExecutor {
/**
* @param quoteId Socket quote id of the route that delivered the funds
* @param amount Amount of `token` delivered
* @param token Token delivered
* @param callData The `destinationPayload` passed at quote time, verbatim
*/
function executeData(bytes32 quoteId, uint256 amount, address token, bytes calldata callData) external;
}
src/strategy/IStrategy.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Strategy Interface
interface IStrategy {
event TokenOutput(address tokenReceived, uint256 amountOut);
function handleGatewayMessage(IERC20 tokenSent, uint256 amountIn, bytes32 recipient, bytes memory message) external;
}
abstract contract IStrategyWithSlippageArgs is IStrategy {
function handleGatewayMessageWithSlippageArgs(
IERC20 tokenSent,
uint256 amountIn,
bytes32 recipient,
StrategySlippageArgs memory args
) public virtual;
function handleGatewayMessage(IERC20 tokenSent, uint256 amountIn, bytes32 recipient, bytes memory message)
external
{
StrategySlippageArgs memory args = abi.decode(message, (StrategySlippageArgs));
handleGatewayMessageWithSlippageArgs(tokenSent, amountIn, recipient, args);
}
}
struct StrategySlippageArgs {
uint256 amountOutMin;
}
src/swapper/ISwapper.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
/**
* @title ISwapper interface
* @dev This interface allows the easy integration of AMMs from different vendors for the purpose of swapping.
* For each vendor a new contract has to be written implementing the ISwapper interface.
*/
interface ISwapper {
function swapExactTokensForNative(IERC20 _token, uint256 _amountIn, uint256 _amountOutMin)
external
returns (uint256 outAmount);
function swapTokensForExactNative(IERC20 token, uint256 amountOut, uint256 amountInMax)
external
returns (uint256 amountIn);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@0x/settler-v1/=dependencies/@0x-settler-v1/",
"@ERC4337/=dependencies/@rhinestone-core-modules-v1/node_modules/@ERC4337/",
"@bob-collective/bitcoin-spv/=dependencies/@bob-collective-bitcoin-spv-v1/src/",
"@bob-collective/bob/=dependencies/@bob-collective-bob-v1/contracts/src/",
"@layerzerolabs/lz-evm-messagelib-v2/=dependencies/@layerzerolabs-layerzero-v2-v1/packages/layerzero-v2/evm/messagelib/",
"@layerzerolabs/lz-evm-protocol-v2/=dependencies/@layerzerolabs-layerzero-v2-v1/packages/layerzero-v2/evm/protocol/",
"@layerzerolabs/oapp/=dependencies/@layerzerolabs-layerzero-v2-v1/packages/layerzero-v2/evm/oapp/",
"@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.5.0/",
"@prb/math/=dependencies/@rhinestone-core-modules-v1/node_modules/@prb/math/src/",
"@rhinestone/core-modules/=dependencies/@rhinestone-core-modules-v1/",
"@rhinestone/modulekit-v1/=dependencies/@rhinestone-modulekit-v1/",
"@rhinestone/modulekit/=dependencies/@rhinestone-core-modules-v1/node_modules/@rhinestone/modulekit/src/",
"@uniswap/swap-router-contracts/=dependencies/@uniswap-swap-router-contracts-v1/",
"@uniswap/v3-core/=dependencies/@uniswap-v3-core-v1/",
"@uniswap/v3-periphery/=dependencies/@uniswap-v3-periphery-v1/",
"ExcessivelySafeCall/=dependencies/@rhinestone-core-modules-v1/node_modules/excessively-safe-call/src/",
"account-abstraction-v0.6/=dependencies/@rhinestone-core-modules-v1/node_modules/@ERC4337/account-abstraction-v0.6/contracts/",
"account-abstraction/=dependencies/@rhinestone-core-modules-v1/node_modules/@ERC4337/account-abstraction/contracts/",
"erc4337-validation/=dependencies/@rhinestone-core-modules-v1/node_modules/@rhinestone/erc4337-validation/src/",
"erc7579-implementation/=dependencies/@erc7579-implementation-v1/",
"forge-std/=dependencies/forge-std-1.14.0/src/",
"modulekit/=dependencies/@rhinestone-core-modules-v1/node_modules/@rhinestone/modulekit/src/",
"sentinellist/=dependencies/@rhinestone-core-modules-v1/node_modules/@rhinestone/sentinellist/src/",
"solady/=dependencies/@rhinestone-core-modules-v1/node_modules/solady/src/",
"solarray/=dependencies/@rhinestone-core-modules-v1/node_modules/solarray/src/",
"solidity-bytes-utils/=dependencies/@solidity-bytes-utils-v1/",
"node_modules/webauthn-sol/src/:openzeppelin-contracts/=dependencies/@rhinestone-core-modules-v1/node_modules/@openzeppelin/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/lib/openzeppelin-contracts/:erc4626-tests/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/lib/openzeppelin-contracts/lib/erc4626-tests/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/lib/openzeppelin-contracts/:erc4626-tests/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/lib/openzeppelin-contracts/lib/erc4626-tests/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/solmate/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/solmate/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/solmate/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/solmate/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/solmate/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/solmate/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/openzeppelin-contracts/:erc4626-tests/=dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/openzeppelin-contracts/lib/erc4626-tests/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/openzeppelin-contracts/:erc4626-tests/=dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/openzeppelin-contracts/lib/erc4626-tests/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/lib/openzeppelin-contracts/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/lib/openzeppelin-contracts/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/openzeppelin-contracts/:erc4626-tests/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/openzeppelin-contracts/lib/erc4626-tests/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/openzeppelin-contracts/:erc4626-tests/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/openzeppelin-contracts/lib/erc4626-tests/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/:solmate/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/solmate/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/:solmate/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/solmate/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/:forge-gas-snapshot/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/forge-gas-snapshot/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/:forge-gas-snapshot/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/forge-gas-snapshot/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/openzeppelin-contracts/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/lib/openzeppelin-contracts/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/:solmate/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/solmate/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/:solmate/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/solmate/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/:forge-gas-snapshot/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/:forge-gas-snapshot/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/:solmate/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/solmate/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/:solmate/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/solmate/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"dependencies/@0x-settler-v1/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/openzeppelin-contracts/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/openzeppelin-contracts/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/:ethereum-vault-connector/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/:ethereum-vault-connector/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/ethereum-vault-connector/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/openzeppelin-contracts/contracts/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/openzeppelin-contracts/contracts/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/:permit2/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/:permit2/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/lib/permit2/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/openzeppelin-contracts/:erc4626-tests/=dependencies/@0x-settler-v1/lib/euler-swap/lib/openzeppelin-contracts/lib/erc4626-tests/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/openzeppelin-contracts/:erc4626-tests/=dependencies/@0x-settler-v1/lib/euler-swap/lib/openzeppelin-contracts/lib/erc4626-tests/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/openzeppelin-contracts/:halmos-cheatcodes/=dependencies/@0x-settler-v1/lib/euler-swap/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/openzeppelin-contracts/:halmos-cheatcodes/=dependencies/@0x-settler-v1/lib/euler-swap/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/:permit2/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/:permit2/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/permit2/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/:v4-core/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/:v4-core/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/src/",
"dependencies/@0x-settler-v1/lib/permit2/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/permit2/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/permit2/lib/forge-std/:ds-test/=dependencies/@0x-settler-v1/lib/permit2/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/permit2/lib/solmate/:ds-test/=dependencies/@0x-settler-v1/lib/permit2/lib/solmate/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/permit2/lib/solmate/:ds-test/=dependencies/@0x-settler-v1/lib/permit2/lib/solmate/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=dependencies/@0x-settler-v1/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"dependencies/@0x-settler-v1/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=dependencies/@0x-settler-v1/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"dependencies/@0x-settler-v1/lib/v4-core/lib/solmate/:ds-test/=dependencies/@0x-settler-v1/lib/v4-core/lib/solmate/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/v4-core/lib/solmate/:ds-test/=dependencies/@0x-settler-v1/lib/v4-core/lib/solmate/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/euler-swap/lib/openzeppelin-contracts/contracts/",
"dependencies/@0x-settler-v1/lib/euler-swap/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/euler-swap/lib/openzeppelin-contracts/contracts/",
"dependencies/@0x-settler-v1/lib/euler-swap/:ethereum-vault-connector/=dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/src/",
"dependencies/@0x-settler-v1/lib/euler-swap/:ethereum-vault-connector/=dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/src/",
"dependencies/@0x-settler-v1/lib/openzeppelin-contracts/:erc4626-tests/=dependencies/@0x-settler-v1/lib/openzeppelin-contracts/lib/erc4626-tests/",
"dependencies/@0x-settler-v1/lib/openzeppelin-contracts/:erc4626-tests/=dependencies/@0x-settler-v1/lib/openzeppelin-contracts/lib/erc4626-tests/",
"dependencies/@0x-settler-v1/lib/openzeppelin-contracts/:halmos-cheatcodes/=dependencies/@0x-settler-v1/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"dependencies/@0x-settler-v1/lib/openzeppelin-contracts/:halmos-cheatcodes/=dependencies/@0x-settler-v1/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"dependencies/@0x-settler-v1/lib/permit2/:solmate/=dependencies/@0x-settler-v1/lib/permit2/lib/solmate/",
"dependencies/@0x-settler-v1/lib/permit2/:solmate/=dependencies/@0x-settler-v1/lib/permit2/lib/solmate/",
"dependencies/@0x-settler-v1/lib/permit2/:forge-gas-snapshot/=dependencies/@0x-settler-v1/lib/permit2/lib/forge-gas-snapshot/src/",
"dependencies/@0x-settler-v1/lib/permit2/:forge-gas-snapshot/=dependencies/@0x-settler-v1/lib/permit2/lib/forge-gas-snapshot/src/",
"dependencies/@0x-settler-v1/lib/permit2/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/permit2/lib/openzeppelin-contracts/",
"dependencies/@0x-settler-v1/lib/permit2/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/permit2/lib/openzeppelin-contracts/",
"dependencies/@0x-settler-v1/lib/solmate/:ds-test/=dependencies/@0x-settler-v1/lib/solmate/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/solmate/:ds-test/=dependencies/@0x-settler-v1/lib/solmate/lib/ds-test/src/",
"dependencies/@0x-settler-v1/lib/v4-core/:solmate/=dependencies/@0x-settler-v1/lib/v4-core/lib/solmate/",
"dependencies/@0x-settler-v1/lib/v4-core/:solmate/=dependencies/@0x-settler-v1/lib/v4-core/lib/solmate/",
"dependencies/@0x-settler-v1/lib/v4-core/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/v4-core/lib/openzeppelin-contracts/",
"dependencies/@0x-settler-v1/lib/v4-core/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/v4-core/lib/openzeppelin-contracts/",
"dependencies/@bob-collective-bitcoin-spv-v1/lib/forge-std/:ds-test/=dependencies/@bob-collective-bitcoin-spv-v1/lib/forge-std/lib/ds-test/src/",
"dependencies/@bob-collective-bitcoin-spv-v1/lib/forge-std/:ds-test/=dependencies/@bob-collective-bitcoin-spv-v1/lib/forge-std/lib/ds-test/src/",
"dependencies/@layerzerolabs-layerzero-v2-v1/lib/forge-std/:ds-test/=dependencies/@layerzerolabs-layerzero-v2-v1/lib/forge-std/lib/ds-test/src/",
"dependencies/@layerzerolabs-layerzero-v2-v1/lib/forge-std/:ds-test/=dependencies/@layerzerolabs-layerzero-v2-v1/lib/forge-std/lib/ds-test/src/",
"dependencies/@solidity-bytes-utils-v1/lib/forge-std/:ds-test/=dependencies/@solidity-bytes-utils-v1/lib/forge-std/lib/ds-test/src/",
"dependencies/@solidity-bytes-utils-v1/lib/forge-std/:ds-test/=dependencies/@solidity-bytes-utils-v1/lib/forge-std/lib/ds-test/src/",
"dependencies/@0x-settler-v1/:solmate/=dependencies/@0x-settler-v1/lib/solmate/",
"dependencies/@0x-settler-v1/:solmate/=dependencies/@0x-settler-v1/lib/solmate/",
"dependencies/@0x-settler-v1/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/openzeppelin-contracts/contracts/",
"dependencies/@0x-settler-v1/:openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/openzeppelin-contracts/contracts/",
"dependencies/@0x-settler-v1/:forge-gas-snapshot/=dependencies/@0x-settler-v1/lib/forge-gas-snapshot/",
"dependencies/@0x-settler-v1/:forge-gas-snapshot/=dependencies/@0x-settler-v1/lib/forge-gas-snapshot/",
"dependencies/@0x-settler-v1/:permit2/=dependencies/@0x-settler-v1/lib/permit2/",
"dependencies/@0x-settler-v1/:permit2/=dependencies/@0x-settler-v1/lib/permit2/",
"dependencies/@0x-settler-v1/:v4-core/=dependencies/@0x-settler-v1/lib/v4-core/src/",
"dependencies/@0x-settler-v1/:v4-core/=dependencies/@0x-settler-v1/lib/v4-core/src/",
"dependencies/@rhinestone-core-modules-v1/:@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.5.0/",
"dependencies/@rhinestone-core-modules-v1/:@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.5.0/",
"dependencies/@rhinestone-core-modules-v1/:@openzeppelin/=dependencies/@rhinestone-core-modules-v1/node_modules/@openzeppelin/",
"dependencies/@rhinestone-core-modules-v1/:@openzeppelin/=dependencies/@rhinestone-core-modules-v1/node_modules/@openzeppelin/",
"dependencies/@rhinestone-core-modules-v1/:ds-test/=dependencies/@rhinestone-core-modules-v1/node_modules/ds-test/src/",
"dependencies/@rhinestone-core-modules-v1/:ds-test/=dependencies/@rhinestone-core-modules-v1/node_modules/ds-test/src/",
"dependencies/@rhinestone-core-modules-v1/:solmate/=dependencies/@rhinestone-core-modules-v1/node_modules/solmate/src/",
"dependencies/@rhinestone-core-modules-v1/:solmate/=dependencies/@rhinestone-core-modules-v1/node_modules/solmate/src/",
"@0x-settler-v1/=dependencies/@0x-settler-v1/",
"@bob-collective-bitcoin-spv-v1/=dependencies/@bob-collective-bitcoin-spv-v1/",
"@bob-collective-bob-v1/=dependencies/@bob-collective-bob-v1/",
"@ensdomains/=dependencies/@0x-settler-v1/lib/v4-core/node_modules/@ensdomains/",
"@erc7579-implementation-v1/=dependencies/@erc7579-implementation-v1/src/",
"@erc7579/=dependencies/@rhinestone-core-modules-v1/node_modules/@erc7579/enumerablemap4337/src/",
"@eulerswap/=dependencies/@0x-settler-v1/lib/euler-swap/src/",
"@forge-gas-snapshot/=dependencies/@0x-settler-v1/lib/forge-gas-snapshot/src/",
"@forge-std/=dependencies/@0x-settler-v1/lib/forge-std/src/",
"@gnosis.pm/=dependencies/@rhinestone-core-modules-v1/node_modules/@gnosis.pm/",
"@layerzerolabs-layerzero-v2-v1/=dependencies/@layerzerolabs-layerzero-v2-v1/",
"@openzeppelin-contracts-5.5.0/=dependencies/@openzeppelin-contracts-5.5.0/",
"@openzeppelin/=dependencies/@erc7579-implementation-v1/node_modules/@openzeppelin/",
"@permit2/=dependencies/@0x-settler-v1/lib/permit2/src/",
"@prb/=dependencies/@rhinestone-core-modules-v1/node_modules/@prb/math/src/",
"@rhinestone-core-modules-v1/=dependencies/@rhinestone-core-modules-v1/",
"@rhinestone-modulekit-v1/=dependencies/@rhinestone-modulekit-v1/src/",
"@rhinestone/=dependencies/@rhinestone-core-modules-v1/node_modules/@rhinestone/",
"@safe-global/=dependencies/@rhinestone-core-modules-v1/node_modules/@safe-global/",
"@solidity-bytes-utils-v1/=dependencies/@solidity-bytes-utils-v1/contracts/",
"@solmate/=dependencies/@0x-settler-v1/lib/solmate/src/",
"@uniswap-swap-router-contracts-v1/=dependencies/@uniswap-swap-router-contracts-v1/contracts/",
"@uniswap-v3-core-v1/=dependencies/@uniswap-v3-core-v1/",
"@uniswap-v3-periphery-v1/=dependencies/@uniswap-v3-periphery-v1/contracts/",
"@uniswap/v4-core/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/lib/v4-core/",
"@uniswapv4/=dependencies/@0x-settler-v1/lib/v4-core/src/",
"@webauthn/=dependencies/@rhinestone-core-modules-v1/node_modules/webauthn-sol/src/",
"FreshCryptoLib/=dependencies/@rhinestone-core-modules-v1/node_modules/FreshCryptoLib/solidity/src/",
"checknsignatures/=dependencies/@rhinestone-core-modules-v1/node_modules/@rhinestone/checknsignatures/src/",
"ds-test/=dependencies/@erc7579-implementation-v1/node_modules/ds-test/src/",
"erc4626-tests/=dependencies/@0x-settler-v1/lib/openzeppelin-contracts/lib/erc4626-tests/",
"ethereum-vault-connector/=dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/",
"euler-swap/=dependencies/@0x-settler-v1/lib/euler-swap/",
"euler-vault-kit/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/",
"evc/=dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/src/",
"evk-test/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/test/",
"evk/=dependencies/@0x-settler-v1/lib/euler-swap/lib/euler-vault-kit/src/",
"excessively-safe-call/=dependencies/@rhinestone-core-modules-v1/node_modules/excessively-safe-call/src/",
"flatbytes/=dependencies/@rhinestone-core-modules-v1/node_modules/@rhinestone/flatbytes/src/",
"forge-gas-snapshot/=dependencies/@0x-settler-v1/lib/permit2/lib/forge-gas-snapshot/src/",
"forge-std-1.14.0/=dependencies/forge-std-1.14.0/src/",
"halmos-cheatcodes/=dependencies/@0x-settler-v1/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat-deploy/=dependencies/@rhinestone-core-modules-v1/node_modules/hardhat-deploy/",
"hardhat/=dependencies/@rhinestone-core-modules-v1/node_modules/hardhat/",
"openzeppelin-contracts/=dependencies/@0x-settler-v1/lib/openzeppelin-contracts/",
"openzeppelin/=dependencies/@0x-settler-v1/lib/euler-swap/lib/ethereum-vault-connector/lib/openzeppelin-contracts/contracts/",
"permit2/=dependencies/@0x-settler-v1/lib/permit2/",
"solmate/=dependencies/@0x-settler-v1/lib/solmate/",
"v4-core/=dependencies/@0x-settler-v1/lib/v4-core/src/",
"v4-periphery/=dependencies/@0x-settler-v1/lib/euler-swap/lib/v4-periphery/",
"webauthn-sol/=dependencies/@rhinestone-core-modules-v1/node_modules/webauthn-sol/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.