Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/bridge/BitVMBridgeV4.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "./interface/IBridge.sol";
import "./interface/IVaultRouter.sol";
import "@layerzerolabs/oft-evm/contracts/interfaces/IMintableBurnable.sol";
import "../liquidity_provider/interface/ILPManager.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@btc-light-client/packages/contracts/src/interfaces/IBtcTxVerifier.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title BitVMBridgeV4
* @notice A bridge contract that facilitates the minting and burning of BTC-pegged tokens
* @dev This contract implements a Bitcoin bridge using BitVM technology, allowing users to
* mint tokens by proving Bitcoin transactions and burn tokens to initiate Bitcoin withdrawals.
* The contract is upgradeable and includes reentrancy protection.
* @custom:security Uses role-based access control for different operational functions
* @custom:security-contact security@fiammalabs.io
*/
/// @custom:oz-upgrades-from BitVMBridgeV3
contract BitVMBridgeV4 is IBitVMBridge, IInvest, AccessControlUpgradeable, ReentrancyGuardUpgradeable {
/// @notice Role for business operations including minting and LP management
bytes32 public constant BUSINESS_ROLE = keccak256("BUSINESS_ROLE");
/// @notice BTC Peg contract interface for minting and burning operations
IMintableBurnable public btcPeg;
/// @notice BTC Tx Verifier contract interface for Bitcoin transaction verification
IBtcTxVerifier public btcTxVerifier;
/// @notice Minimum number of Bitcoin block confirmations required for a transaction to be considered valid
uint256 public minConfirmations;
/// @notice Mapping to track used inclusion proofs to prevent double-spending
mapping(bytes32 txid => bool isMinted) private minted;
/// @notice Maximum number of pegs allowed in a single mint transaction
uint256 public maxPegsPerMint;
/// @notice Maximum amount of BTC (in satoshis) that can be minted in a single peg
uint256 public maxBtcPerMint;
/// @notice Minimum amount of BTC (in satoshis) that can be minted in a single peg
uint256 public minBtcPerMint;
/// @notice Maximum amount of BTC (in satoshis) that can be burned in a single transaction
uint256 public maxBtcPerBurn;
/// @notice Minimum amount of BTC (in satoshis) that can be burned in a single transaction
uint256 public minBtcPerBurn;
/// @notice Burn pause status
bool public burnPaused;
/// @notice Maximum fee rate for burn transactions
uint256 public maxFeeRate;
/// @notice Vault router contract interface
IVaultRouter public vaultRouter;
/// @notice Chain name, used for intent commitment
string public chainName;
/// @notice LP manager contract
ILPManager public lpManager;
/// @notice Mapping to track LP withdrawals
mapping(uint256 => LPWithdraw) public lpWithdraws;
/// @notice Timeout period in seconds after which LP withdrawals can be refunded, used for refunding LP withdrawals
uint256 public lpWithdrawTimeout;
/// @notice Two intent type, used for intent commitment
bytes32 constant HASH_DEPOSIT = keccak256("deposit");
bytes32 constant HASH_SWITCH = keccak256("switch");
/// @dev Custom errors
error TooManyPegs();
error InvalidPegAddress();
error InvalidPegAmount();
error InvalidPeginAmount();
error InvalidBurnAmount();
error InvalidBtcAddress();
error InvalidBtcPegAddress();
error BurnPaused();
error InvalidInclusionProof();
error MismatchBtcAmount(uint256 _provided, uint256 _btcAmount);
error InvalidFeeRate();
error InvalidBurnTime();
error InvalidVaultRouter();
error InvalidIntentType();
error InvalidLPID();
error InvalidLPWithdrawID();
error InsufficientAllowance();
error InvalidLPWithdrawTimeout();
error InvalidLPWithdrawAmount();
/// @notice Modifier to check if burn is not paused
modifier whenBurnNotPaused() {
if (burnPaused) revert BurnPaused();
_;
}
/// @notice State change events for monitoring and indexing
/**
* @notice Emitted when bridge parameters are updated
* @param maxPegsPerMint New maximum number of pegs per mint operation
* @param maxBtcPerMint New maximum BTC amount per mint (in satoshis)
* @param minBtcPerMint New minimum BTC amount per mint (in satoshis)
* @param maxBtcPerBurn New maximum BTC amount per burn (in satoshis)
* @param minBtcPerBurn New minimum BTC amount per burn (in satoshis)
*/
event ParametersChanged(
uint256 maxPegsPerMint,
uint256 maxBtcPerMint,
uint256 minBtcPerMint,
uint256 maxBtcPerBurn,
uint256 minBtcPerBurn
);
/**
* @notice Constructor for the logic contract
* @dev Disables initializers to prevent direct initialization of the logic contract.
* This is a security measure for upgradeable contracts deployed behind proxies.
* The logic contract should only be initialized through the proxy.
* @custom:oz-upgrades-unsafe-allow constructor
*/
constructor() {
_disableInitializers();
}
/**
* @notice Initializes the BitVMBridge contract with required parameters
* @dev This function replaces the constructor for upgradeable contracts.
* Can only be called once due to the initializer modifier.
* Sets up access control, reentrancy protection, and validates all input parameters.
* @param _admin Address that will become the contract admin
* @param _btcPegAddr Address of the BTC Peg contract for token operations
* @param _btcTxVerifierAddr Address of the BTC transaction verifier contract
* @param _minConfirmations Minimum number of Bitcoin confirmations required
* @param _lpManager Address of the LP manager contract
* @param _lpWithdrawTimeout Timeout period in seconds for LP withdrawals
* @param _chainName Name of the chain
* @custom:security Must validate all addresses are non-zero to prevent deployment issues
* @custom:security Uses role-based access control for granular permission management
* @custom:security Uses setter functions for consistent parameter validation
*/
function initialize(
address _admin,
address _btcPegAddr,
address _btcTxVerifierAddr,
address _lpManager,
uint256 _lpWithdrawTimeout,
uint256 _minConfirmations,
string calldata _chainName
) external initializer {
if (_admin == address(0)) revert InvalidPegAddress();
if (_btcPegAddr == address(0)) revert InvalidBtcPegAddress();
__AccessControl_init();
__ReentrancyGuard_init();
// Grant all roles to the admin initially
_grantRole(DEFAULT_ADMIN_ROLE, _admin);
_grantRole(BUSINESS_ROLE, _admin);
btcPeg = IMintableBurnable(_btcPegAddr);
btcTxVerifier = IBtcTxVerifier(_btcTxVerifierAddr);
minConfirmations = _minConfirmations;
chainName = _chainName;
lpManager = ILPManager(_lpManager);
lpWithdrawTimeout = _lpWithdrawTimeout;
}
/**
* @notice Updates the bridge operational parameters
* @dev Only callable by addresses with DEFAULT_ADMIN_ROLE. Validates parameter consistency before updating
* @param _maxPegsPerMint Maximum number of pegs allowed in a single mint transaction
* @param _maxBtcPerMint Maximum BTC amount per individual mint operation (in satoshis)
* @param _minBtcPerMint Minimum BTC amount per individual mint operation (in satoshis)
* @param _maxBtcPerBurn Maximum BTC amount per burn operation (in satoshis)
* @param _minBtcPerBurn Minimum BTC amount per burn operation (in satoshis)
* @custom:security Validates that min values don't exceed max values to prevent logical errors
*/
function setParameters(
uint256 _maxPegsPerMint,
uint256 _maxBtcPerMint,
uint256 _minBtcPerMint,
uint256 _maxBtcPerBurn,
uint256 _minBtcPerBurn
) external onlyRole(DEFAULT_ADMIN_ROLE) {
// basic parameter check
if (_minBtcPerMint > _maxBtcPerMint) revert InvalidPeginAmount();
if (_minBtcPerBurn > _maxBtcPerBurn) revert InvalidBurnAmount();
if (_maxPegsPerMint == 0) revert InvalidPegAmount();
maxPegsPerMint = _maxPegsPerMint;
maxBtcPerMint = _maxBtcPerMint;
minBtcPerMint = _minBtcPerMint;
maxBtcPerBurn = _maxBtcPerBurn;
minBtcPerBurn = _minBtcPerBurn;
emit ParametersChanged(_maxPegsPerMint, _maxBtcPerMint, _minBtcPerMint, _maxBtcPerBurn, _minBtcPerBurn);
}
function setChainName(string calldata _chainName) external onlyRole(DEFAULT_ADMIN_ROLE) {
chainName = _chainName;
}
/// @notice Pause burn functionality
function pauseBurn() external onlyRole(DEFAULT_ADMIN_ROLE) {
burnPaused = true;
}
/// @notice Unpause burn functionality
function unpauseBurn() external onlyRole(DEFAULT_ADMIN_ROLE) {
burnPaused = false;
}
function setLPManager(address _lpManager) external onlyRole(DEFAULT_ADMIN_ROLE) {
lpManager = ILPManager(_lpManager);
emit LPManagerUpdated(_lpManager);
}
function setLPWithdrawTimeout(uint256 _lpWithdrawTimeout) external onlyRole(DEFAULT_ADMIN_ROLE) {
lpWithdrawTimeout = _lpWithdrawTimeout;
emit PWithdrawTimeoutUpdated(_lpWithdrawTimeout);
}
function getMinted(bytes32 _txid) public view returns (bool) {
return minted[_txid];
}
/// @notice Internal function to validate Bitcoin transaction from calldata
/// @param value Transaction value
/// @param blockNum Block number
/// @param inclusionProof Bitcoin transaction proof
/// @param txOutIx Transaction output index
/// @param destScriptHash Destination script sha256 hash
/// @param amountSats Amount in satoshis
function _validateBtcTransaction(
uint256 value,
uint256 blockNum,
BtcTxProof calldata inclusionProof,
uint256 txOutIx,
bytes32 destScriptHash,
uint256 amountSats,
bool checkOpReturn,
uint256 opReturnOutIx,
bytes32 opReturnData
) internal view {
if (amountSats != value) {
revert MismatchBtcAmount(value, amountSats);
}
if (value < minBtcPerMint || value > maxBtcPerMint) {
revert InvalidPeginAmount();
}
bool isValid = btcTxVerifier.verifyPayment(
minConfirmations,
blockNum,
inclusionProof,
txOutIx,
destScriptHash,
amountSats,
checkOpReturn,
opReturnOutIx,
opReturnData
);
if (!isValid) revert InvalidInclusionProof();
}
/// @notice Calculate intent hash for investment
/// @param sidechainUser User's sidechain address
/// @param amount Amount in satoshis
/// @param vaultAddress Vault contract address
/// @param intentType Intent type identifier ("deposit" or "switch")
/// @return hash SHA256 hash of the intent
function calculateIntentHash(
address sidechainUser,
uint256 amount,
address vaultAddress,
string calldata intentType
) public view returns (bytes32 hash) {
hash = sha256(abi.encodePacked(sidechainUser, amount, vaultAddress, chainName, intentType));
}
/// @notice Check if the intent type is valid
/// @param _intentType Intent type identifier ("deposit" or "switch")
/// @return isValid True if the intent type is valid, false otherwise
/// @dev This function is used to validate the intent type
/// @custom:security Prevents invalid intent types from being used
function isValidIntentType(string memory _intentType) public pure returns (bool) {
bytes32 intentTypeHash = keccak256(abi.encodePacked(_intentType));
return intentTypeHash == HASH_DEPOSIT || intentTypeHash == HASH_SWITCH;
}
/**
* @notice Mints tokens by verifying Bitcoin transaction inclusion proofs
* @dev Critical function that validates Bitcoin payments and mints corresponding tokens.
* @param pegs Array of peg data containing Bitcoin transaction proofs and recipient information
* @custom:security Verifies each Bitcoin transaction proof before minting
* @custom:security Prevents double-spending by tracking used inclusion proofs
* @custom:security Validates amounts are within configured limits
*/
function mint(Peg[] calldata pegs) public onlyRole(BUSINESS_ROLE) nonReentrant {
if (pegs.length > maxPegsPerMint) revert TooManyPegs();
if (pegs.length == 0) revert InvalidPegAmount();
for (uint256 i = 0; i < pegs.length; i++) {
Peg calldata peg = pegs[i];
bytes32 txid = peg.inclusionProof.txId;
// Skip if already processed
if (minted[txid]) {
continue;
}
// Mark as minted in outer scope
minted[txid] = true;
_validateBtcTransaction(
peg.value,
peg.blockNum,
peg.inclusionProof,
peg.txOutIx,
peg.destScriptHash,
peg.amountSats,
false,
0,
0
);
btcPeg.mint(peg.to, peg.value);
emit Mint(peg.to, peg.value);
}
}
/**
* @notice Mints tokens for investment
* @dev Validates investment transactions and mints corresponding tokens.
* Only callable by addresses with BUSINESS_ROLE.
* @param invests Array of investment data containing transaction proofs and recipient information
* @custom:security Validates all investment transactions before minting
* @custom:security Prevents double-spending by tracking used inclusion proofs
* @custom:security Validates amounts are within configured limits
*/
function mint_for_invest(Invest[] calldata invests) public onlyRole(BUSINESS_ROLE) nonReentrant {
if (invests.length > maxPegsPerMint) revert TooManyPegs();
if (invests.length == 0) revert InvalidPegAmount();
if (address(vaultRouter) == address(0)) revert InvalidVaultRouter();
// Track which transactions to skip
bool[] memory shouldSkip = new bool[](invests.length);
// Validate all transactions and calculate total amount
uint256 totalAmount = 0;
for (uint256 i = 0; i < invests.length; i++) {
Invest calldata invest = invests[i];
bytes32 txid = invest.inclusionProof.txId;
// Skip if already processed
if (minted[txid]) {
shouldSkip[i] = true;
continue;
}
// Mark as minted in outer scope
minted[txid] = true;
if (!isValidIntentType(invest.intentType)) {
revert InvalidIntentType();
}
bytes32 intentHash =
calculateIntentHash(invest.sidechainUser, invest.value, invest.vault, invest.intentType);
_validateBtcTransaction(
invest.value,
invest.blockNum,
invest.inclusionProof,
invest.txOutIx,
invest.destScriptHash,
invest.amountSats,
true,
invest.opReturnOutIx,
intentHash
);
totalAmount += invest.value;
}
// Only mint if there's a positive total amount
if (totalAmount > 0) {
// Mint total amount once
btcPeg.mint(address(this), totalAmount);
// Check and update allowance once for total amount
address token = address(btcPeg);
uint256 currentAllowance = IERC20(token).allowance(address(this), address(vaultRouter));
if (currentAllowance < totalAmount) {
SafeERC20.safeIncreaseAllowance(IERC20(token), address(vaultRouter), totalAmount - currentAllowance);
}
}
// Process deposits and emit events
for (uint256 i = 0; i < invests.length; i++) {
if (shouldSkip[i]) {
continue;
}
Invest calldata invest = invests[i];
vaultRouter.depositNative(invest.sidechainUser, invest.vault, invest.value);
emit InvestMinted(invest.sidechainUser, invest.inclusionProof.txId, invest.value, invest.vault);
}
}
/**
* @notice Burns tokens to initiate a Bitcoin withdrawal
* @dev Burns tokens from the caller's balance and emits an event for off-chain processing.
* Protected against reentrancy attacks.
* @param _btc_addr Bitcoin address where the withdrawn funds should be sent
* @param _value Amount of tokens to burn (in satoshis)
* @custom:security Validates burn amount is within allowed limits
* @custom:security The actual Bitcoin transaction must be processed off-chain
*/
function burn(string calldata _btc_addr, uint256 _fee_rate, uint256 _value, uint256 _operator_id)
public
nonReentrant
whenBurnNotPaused
{
_validateBurnRestrictions(_value, _fee_rate);
LPInfo memory lpInfo = lpManager.getLPInfo(_operator_id);
if (lpInfo.evm_addr != msg.sender) revert InvalidLPID();
btcPeg.burn(msg.sender, _value);
emit Burn(msg.sender, _btc_addr, _fee_rate, _value, _operator_id);
}
/**
* @notice Withdraws tokens through the LP mode
* @dev Validates LP withdrawal parameters and processes the withdrawal.
* Only callable when burn is not paused.
* @param _withdraw_id Unique identifier for the withdrawal
* @param _btc_addr Bitcoin address where the withdrawn funds should be sent
* @param _receiver_script_hash Script sha256 hash of the receiver
* @param _receive_min_amount Minimum amount of BTC to receive (in satoshis)
* @param _lp_id LP ID to which the withdrawal belongs
* @param _value Amount of tokens to withdraw (in satoshis)
* @param _fee_rate Fee rate for the withdrawal
* @custom:security Validates withdrawal parameters
* @custom:security Prevents double-spending by tracking used inclusion proofs
* @custom:security Validates amounts are within configured limits
*/
function withdrawByLP(
uint256 _withdraw_id,
string calldata _btc_addr,
bytes32 _receiver_script_hash,
uint256 _receive_min_amount,
uint256 _lp_id,
uint256 _value,
uint256 _fee_rate
) external nonReentrant whenBurnNotPaused {
_validateBurnRestrictions(_value, _fee_rate);
if (_withdraw_id == 0 || lpWithdraws[_withdraw_id].id != 0) {
revert InvalidLPWithdrawID();
}
LPInfo memory lpInfo = lpManager.getLPInfo(_lp_id);
if (lpInfo.status != LPStatus.ACTIVE) revert InvalidLPID();
lpWithdraws[_withdraw_id] = LPWithdraw({
id: _withdraw_id,
withdraw_amount: _value,
receiver_addr: _btc_addr,
receiver_script_hash: _receiver_script_hash,
receive_min_amount: _receive_min_amount,
fee_rate: _fee_rate,
timestamp: block.timestamp,
lp_id: _lp_id
});
SafeERC20.safeTransferFrom(IERC20(address(btcPeg)), msg.sender, address(this), _value);
emit WithdrawByLP(msg.sender, _withdraw_id, _btc_addr, _fee_rate, _value, _lp_id, _receive_min_amount);
}
/**
* @notice Claims an LP withdrawal
* @dev Validates the LP withdrawal parameters and processes the claim.
* Only callable by addresses with BUSINESS_ROLE.
* @param _lp_claim_infos Information about the LP withdrawals to claim
* @custom:security Validates the LP withdrawal parameters
* @custom:security Prevents double-spending by tracking used inclusion proofs
*/
function claimLPWithdraw(LPClaimInfo[] calldata _lp_claim_infos) external nonReentrant onlyRole(BUSINESS_ROLE) {
for (uint256 i = 0; i < _lp_claim_infos.length; i++) {
LPClaimInfo calldata _lp_claim_info = _lp_claim_infos[i];
LPWithdraw memory lpWithdraw = lpWithdraws[_lp_claim_info.withdraw_id];
if (lpWithdraw.id == 0) revert InvalidLPWithdrawID();
if (lpWithdraw.receive_min_amount > _lp_claim_info.amountSats) revert InvalidLPWithdrawAmount();
bool isValid = btcTxVerifier.verifyPayment(
minConfirmations,
_lp_claim_info.blockNum,
_lp_claim_info.inclusionProof,
_lp_claim_info.txOutIx,
lpWithdraw.receiver_script_hash,
_lp_claim_info.amountSats,
false,
0,
0
);
if (!isValid) revert InvalidInclusionProof();
delete lpWithdraws[_lp_claim_info.withdraw_id];
LPInfo memory lpInfo = lpManager.getLPInfo(lpWithdraw.lp_id);
SafeERC20.safeTransfer(IERC20(address(btcPeg)), lpInfo.evm_addr, lpWithdraw.withdraw_amount);
emit ClaimLPWithdraw(lpWithdraw.id, lpInfo.id, lpInfo.evm_addr, lpWithdraw.withdraw_amount);
}
}
/**
* @notice Refunds an LP withdrawal
* @dev Validates the LP withdrawal parameters and processes the refund.
* Only callable by addresses with BUSINESS_ROLE.
* @param _withdraw_id Unique identifier for the withdrawal
* @param _receiver Address to which the withdrawn funds should be sent
* @custom:security Validates the LP withdrawal parameters
*/
function refundLPWithdraw(uint256 _withdraw_id, address _receiver) external nonReentrant onlyRole(BUSINESS_ROLE) {
LPWithdraw memory lpWithdraw = lpWithdraws[_withdraw_id];
if (lpWithdraw.id == 0) revert InvalidLPWithdrawID();
if (lpWithdraw.timestamp + lpWithdrawTimeout > block.timestamp) {
revert InvalidLPWithdrawTimeout();
}
delete lpWithdraws[_withdraw_id];
SafeERC20.safeTransfer(IERC20(address(btcPeg)), _receiver, lpWithdraw.withdraw_amount);
emit RefundLPWithdraw(lpWithdraw.id, _receiver, lpWithdraw.withdraw_amount);
}
/// @notice Set the maximum fee rate for burn transactions
function setMaxFeeRate(uint256 _maxFeeRate) external onlyRole(DEFAULT_ADMIN_ROLE) {
maxFeeRate = _maxFeeRate;
}
/// @notice Set the minimum number of confirmations required for a Bitcoin transaction to be considered valid
function setMinConfirmations(uint256 _minConfirmations) external onlyRole(DEFAULT_ADMIN_ROLE) {
minConfirmations = _minConfirmations;
}
/// @notice Set the address of the BTC transaction verifier contract
function setBtcTxVerifier(address _btcTxVerifierAddr) external onlyRole(DEFAULT_ADMIN_ROLE) {
btcTxVerifier = IBtcTxVerifier(_btcTxVerifierAddr);
}
/// @notice Set the address of the vault router contract
function setVaultRouter(address _vaultRouter) external onlyRole(DEFAULT_ADMIN_ROLE) {
vaultRouter = IVaultRouter(_vaultRouter);
}
function setBtcPeg(address _btcPeg) external onlyRole(DEFAULT_ADMIN_ROLE) {
btcPeg = IMintableBurnable(_btcPeg);
}
/**
* @notice Grant business role to an address
* @dev Only callable by addresses with DEFAULT_ADMIN_ROLE
* @param _business Address to grant the business role to
*/
function grantBusinessRole(address _business) external onlyRole(DEFAULT_ADMIN_ROLE) {
_grantRole(BUSINESS_ROLE, _business);
}
/**
* @notice Revoke business role from an address
* @dev Only callable by addresses with DEFAULT_ADMIN_ROLE
* @param _business Address to revoke the business role from
*/
function revokeBusinessRole(address _business) external onlyRole(DEFAULT_ADMIN_ROLE) {
_revokeRole(BUSINESS_ROLE, _business);
}
/// @notice Validate burn/withdraw parameters for restricted users
function _validateBurnRestrictions(uint256 _value, uint256 _fee_rate) internal view {
if (_value < minBtcPerBurn || _value > maxBtcPerBurn) {
revert InvalidBurnAmount();
}
if (_fee_rate == 0 || _fee_rate > maxFeeRate) {
revert InvalidFeeRate();
}
}
}
"
},
"src/bridge/interface/IBridge.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "@btc-light-client/packages/contracts/src/interfaces/BtcTxProof.sol";
/// @notice Base structure containing common fields for Bitcoin transactions
struct BaseTx {
uint256 value;
uint256 blockNum;
BtcTxProof inclusionProof;
uint256 txOutIx;
bytes32 destScriptHash;
uint256 amountSats;
}
struct Peg {
address to;
uint256 value;
uint256 blockNum;
BtcTxProof inclusionProof;
uint256 txOutIx;
bytes32 destScriptHash;
uint256 amountSats;
}
struct Invest {
uint256 value;
uint256 blockNum;
BtcTxProof inclusionProof;
uint256 txOutIx;
bytes32 destScriptHash;
uint256 amountSats;
address sidechainUser;
address vault;
uint256 opReturnOutIx;
string intentType;
}
interface IBitVMBridge {
function mint(Peg[] calldata pegs) external;
function burn(string calldata _btc_addr, uint256 fee_rate, uint256 _value, uint256 _operator_id) external;
event Mint(address indexed to, uint256 value);
event Burn(address indexed from, string btc_addr, uint256 fee_rate, uint256 value, uint256 operator_id);
event WithdrawByLP(
address indexed from,
uint256 withdraw_id,
string btc_addr,
uint256 fee_rate,
uint256 value,
uint256 lp_id,
uint256 receive_min_amount
);
event ClaimLPWithdraw(uint256 indexed withdraw_id, uint256 indexed lp_id, address evm_addr, uint256 value);
event RefundLPWithdraw(uint256 indexed withdraw_id, address receiver, uint256 value);
event PWithdrawTimeoutUpdated(uint256 lp_withdraw_timeout);
event LPManagerUpdated(address lp_manager);
}
interface IInvest {
function mint_for_invest(Invest[] calldata invests) external;
event InvestMinted(address sidechainUser, bytes32 tx_hash, uint256 value, address vault);
}
"
},
"src/bridge/interface/IVaultRouter.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
interface IVaultRouter {
function depositNative(address sidechainUser, address vault, uint256 amount) external;
}
"
},
"lib/devtools/packages/oft-evm/contracts/interfaces/IMintableBurnable.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
/// @title Interface for mintable and burnable tokens
interface IMintableBurnable {
/**
* @notice Burns tokens from a specified account
* @param _from Address from which tokens will be burned
* @param _amount Amount of tokens to be burned
* @return success Indicates whether the operation was successful
*/
function burn(address _from, uint256 _amount) external returns (bool success);
/**
* @notice Mints tokens to a specified account
* @param _to Address to which tokens will be minted
* @param _amount Amount of tokens to be minted
* @return success Indicates whether the operation was successful
*/
function mint(address _to, uint256 _amount) external returns (bool success);
}"
},
"src/liquidity_provider/interface/ILPManager.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
import "lib/btc-light-client/packages/contracts/src/interfaces/BtcTxProof.sol";
enum LPStatus {
UNREGISTERED,
ACTIVE,
SUSPENDED,
TERMINATED
}
struct LPRegister {
uint256 lp_id;
string bitcoin_addr;
address evm_addr;
uint256 fee;
}
struct LPInfo {
uint256 id;
string bitcoin_addr;
address evm_addr;
uint256 fee;
LPStatus status;
}
struct LPWithdraw {
uint256 id;
uint256 withdraw_amount;
string receiver_addr;
bytes32 receiver_script_hash;
uint256 receive_min_amount;
uint256 fee_rate;
uint256 timestamp;
uint256 lp_id;
}
struct LPClaimInfo {
uint256 withdraw_id;
uint256 blockNum;
BtcTxProof inclusionProof;
uint256 txOutIx;
uint256 amountSats;
}
interface ILPManager {
function registerLP(LPRegister calldata _lp_register) external;
function updateLPStatus(uint256 _lp_id, LPStatus _newStatus) external;
function isLPActive(uint256 _lp_id) external view returns (bool);
function getLPInfo(uint256 _lp_id) external view returns (LPInfo memory);
function getLPStatus(uint256 _lp_id) external view returns (LPStatus);
event LPRegistered(uint256 indexed id, address indexed evm_addr, string bitcoin_addr, uint256 fee);
event LPStatusUpdated(uint256 indexed id, LPStatus indexed newStatus);
}
"
},
"lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
"
},
"lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
"
},
"lib/btc-light-client/packages/contracts/src/interfaces/IBtcTxVerifier.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "./BtcTxProof.sol";
import "./IBtcMirror.sol";
/**
* @notice Verifies Bitcoin transaction proofs.
*/
interface IBtcTxVerifier {
/**
* @notice Verifies that the a transaction cleared, paying a given amount to
* a given address. Specifically, verifies a proof that the tx was
* in block N, and that block N has at least M confirmations.
*
* Also verifies that if checkOpReturn is true, the transaction has an OP_RETURN output
* with the given data, and that the output is at the given index.
*/
function verifyPayment(
uint256 minConfirmations,
uint256 blockNum,
BtcTxProof calldata inclusionProof,
uint256 txOutIx,
bytes32 destScriptHash,
uint256 amountSats,
bool checkOpReturn,
uint256 opReturnOutIx,
bytes32 opReturnData
) external view returns (bool);
/**
* @notice Returns the underlying mirror associated with this verifier.
*/
function mirror() external view returns (IBtcMirror);
/**
* @notice Verifies that the a transaction is included in a given block.
*
* @param minConfirmations The minimum number of confirmations required for the block to be considered valid.
* @param blockNum The block number to verify inclusion in.
* @param inclusionProof The proof of inclusion of the transaction in the block.
*
* @return True if the transaction is included in the block, false otherwise.
*/
function verifyInclusion(uint256 minConfirmations, uint256 blockNum, TxInclusionProof calldata inclusionProof)
external
view
returns (bool);
}
"
},
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
"content": "// 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);
}
"
},
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 rely 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 rely 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}.
* Opposedly, 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, 0, 0x44, 0, 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, 0, 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, 0, 0x64, 0, 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, 0, 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, 0, 0x44, 0, 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, 0, 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)
}
}
}
"
},
"lib/btc-light-client/packages/contracts/src/interfaces/BtcTxProof.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/**
* @notice Proof that a transaction (rawTx) is in a given block.
*/
struct BtcTxProof {
/**
* @notice 80-byte block header.
*/
bytes blockHeader;
/**
* @notice Bitcoin transaction ID, equal to SHA256(SHA256(rawTx))
*/
// This is not gas-optimized--we could omit it and compute from rawTx. But
//s the cost is minimal, and keeping it allows better revert messages.
bytes32 txId;
/**
* @notice Index of transaction within the block.
*/
uint256 txIndex;
/**
* @notice Merkle proof. Concatenated sibling hashes, 32*n bytes.
*/
bytes txMerkleProof;
/**
* @notice Raw transaction, HASH-SERIALIZED, no witnesses.
*/
bytes rawTx;
}
/**
* @notice Proof that a transaction (rawTx) is in a given block.
*/
struct TxInclusionProof {
/**
* @notice 80-byte block header.
*/
bytes blockHeader;
/**
* @notice Index of transaction within the block.
*/
uint256 txIndex;
/**
* @notice Merkle proof. Concatenated sibling hashes, 32*n bytes.
*/
bytes txMerkleProof;
/**
* @notice Raw transaction, HASH-SERIALIZED, no witnesses.
*/
bytes rawTx;
}
"
},
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted to signal this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin
Submitted on: 2025-10-18 10:31:26
Comments
Log in to comment.
No comments yet.