Forkchoice Ethereum Mainnet

Address Contract Verified

Address 0x91d32d77e01a8165e162600a05FF5f9Cfee199dd
Balance 0 ETH
Nonce 1
Code Size 8405 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

8405 bytes
0x604060808152600480361015610013575f80fd5b5f3560e01c806301dc937e1461174c57806301ffc9a7146116f957806309d2d0bc146116d1578063123ccd7f146116b3578063183590e5146116955780631d57042c146114ea578063230ed44a146114b0578063248a9ca3146114795780632643d6271461145d5780632f2ff15d1461143457806336568abe146113ef57806339a51be5146113c757806341cd02661461132657806346877b1a146112d85780634a7d0369146112025780634f1ef28614610fa65780635225dcc014610f7e57806352d1902d14610f065780635537a2c914610ee4578063634252dc14610eaa5780636817031b14610dfa5780636d127cfb14610dd257806370a1c1ff14610db05780637486caee14610cb8578063787dce3d14610c6557806391d1485414610c1457806397ede1d414610bea578063a217fddf14610bd0578063a2dc3b591461099b578063ad3cb1cc14610921578063ae35f640146108d9578063b0e21e8a146108bb578063bfca36271461089d578063cc08b83414610880578063d547741f14610839578063df269166146106bf578063e9cbd82214610697578063f00111861461067a578063f0bd87cc14610640578063f63220a5146105f2578063fbe984a3146105d4578063fbf00e02146104a1578063fbfa77cf14610479578063fc13001a1461041a5763ff9935cb1461020a575f80fd5b346104165760c036600319011261041657610223611884565b61022b61186e565b6001600160a01b03929091906044356064358581168103610416576084359186831683036104165760a435938785168503610416577ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a009788549760ff898c1c16159867ffffffffffffffff81168015908161040e575b6001149081610404575b1590816103fb575b506103eb5767ffffffffffffffff1981166001178b55896103cc575b50818816156103bc57169081156103ae5761271083116103a057509261034d61035c9695936103486103529461035797610307611f8c565b61030f611f8c565b610317611f8c565b61031f611f8c565b60015f80516020612080833981519152556001600160601b0360a01b600d541617600d55611d25565b611bef565b611e57565b611e07565b611a49565b5061036357005b805468ff00000000000000001916905551600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d290602090a1005b8951631f3b85d360e01b8152fd5b89516302b6392d60e41b8152fd5b8a516302b6392d60e41b81528390fd5b68ffffffffffffffffff191668010000000000000001178a555f6102cf565b8b5163f92ee8a960e01b81528490fd5b9050155f6102b3565b303b1591506102ab565b8b91506102a1565b5f80fd5b50903461041657602036600319011261041657610435611884565b905f80525f80516020612060833981519152602052805f20335f5260205260ff815f2054161561046a5761046882611e57565b005b5163088f2b9960e21b81529050fd5b8234610416575f36600319011261041657600e5490516001600160a01b039091168152602090f35b509034610416575f366003190112610416576104bb611c51565b7ffbd454f36a7e1a388bd6fc3ab10d434aa4578f811acbbcf33afb1c697486313c805f525f80516020612060833981519152602052815f20335f5260205260ff825f205416156105b8575060025490610517600354809361193a565b9182156105a8576007546001600160a01b0390811694909190851561059a575083602095610548826105559461195b565b60035583600d5416611c80565b6007541681518381527f9f7cc52df9250aa9229acc4f3ddc7ffade2f8865c041b7df9237b0515c532320853392a360015f805160206120808339815191525551908152f35b83516302b6392d60e41b8152fd5b815163162908e360e11b81528490fd5b60449291519163e2517d3f60e01b835233908301526024820152fd5b8234610416575f366003190112610416576020906003549051908152f35b5090346104165760203660031901126104165761060d611884565b905f80525f80516020612060833981519152602052805f20335f5260205260ff815f2054161561046a5761046882611e07565b8234610416575f36600319011261041657602090517ffbd454f36a7e1a388bd6fc3ab10d434aa4578f811acbbcf33afb1c697486313c8152f35b509034610416575f36600319011261041657602091549051908152f35b8234610416575f36600319011261041657600d5490516001600160a01b039091168152602090f35b503461041657608036600319011261041657600e546064359290602435906001600160a01b0316330361082b57801561081d576106ff9060443590611d71565b91606083019081519485811061080157602095505f92518082116107c7575b507f82ed9537252af1020b37b0ebe76def5b87ee0835b039a569befe4f7ca594cb6a916060916107b0888801956107a961076b6127106107628a516009549061198c565b0480995161193a565b93610777895f5461195b565b5f556107858560025461195b565b60025561079d610796848d5161195b565b875461195b565b8655898b01519061193a565b985161195b565b90865195865288860152858501523592a251908152f35b819350916107f87f82ed9537252af1020b37b0ebe76def5b87ee0835b039a569befe4f7ca594cb6a9360609361193a565b9391509161071e565b83516311e9ebaf60e31b81529182015260248101859052604490fd5b505163162908e360e11b8152fd5b505163ea8e4eb560e01b8152fd5b509034610416578060031936011261041657610468913561087b600161085d61186e565b93835f525f805160206120608339815191526020525f2001546119fd565b611b70565b8234610416575f366003190112610416576020905f549051908152f35b8234610416575f366003190112610416576020906001549051908152f35b8234610416575f366003190112610416576020906009549051908152f35b82346104165760809060606108ff6108f03661189a565b906108f9611968565b50611d71565b8251928151845260208201516020850152808201519084015201516060820152f35b8234610416575f3660031901126104165780519061093e826118b0565b600582526020640352e302e360dc1b60208401528151928391602083528151918260208501525f5b8381106109855750505f83830185015250601f01601f19168101030190f35b8181018301518782018701528694508201610966565b5034610416576109aa36611823565b949091935f805260205f80516020612060833981519152602052825f20335f5260205260ff835f20541615610bc15785158015610bb9575b610baa57868603610b9b57600b80545f600b5580610b2b575b505f91825b888410610a3e5785517f23a625679c8288e09f292d561dc4cea0cb5c08447e166855df9be5d6f4998f809080610a398d8b8e8e856119d3565b0390a1005b8315159081610b15575b50610b0557612710610a5b848b8961199f565b3511610af557610a6c83898961199f565b3592610a79818a8a61199f565b35610a85828c8a61199f565b35875191610a92836118b0565b8252838201908152845490600160401b821015610ae257610ab9600192838101885561176e565b939093610ad0575183555191015560010192610a00565b5f89634e487b7160e01b82525260245ffd5b604188634e487b7160e01b5f525260245ffd5b8451631f3b85d360e01b81528490fd5b845163162908e360e11b81528490fd5b9050610b22848a8a61199f565b3511155f610a48565b60016001600160ff1b0382168203610b8857600b5f527f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db99160011b8201915b828110610b785750506109fb565b5f80825582820155600201610b6a565b601185634e487b7160e01b5f525260245ffd5b509051631dc0052360e11b8152fd5b50905163521299a960e01b8152fd5b5086156109e2565b50905163088f2b9960e21b8152fd5b8234610416575f36600319011261041657602090515f8152f35b8234610416575f36600319011261041657602090610c0d6002546003549061193a565b9051908152f35b509034610416578060031936011261041657602091610c3161186e565b90355f525f805160206120608339815191528352815f209060018060a01b03165f52825260ff815f20541690519015158152f35b509034610416576020366003190112610416575f80525f80516020612060833981519152602052805f20335f5260205260ff815f20541615610cab576104688235611d25565b5163088f2b9960e21b8152fd5b509034610416575f36600319011261041657610cd2611c51565b7ff1b411d6abb365480ac902cc153c45e9ded5847a2265ce6d01945d253edb6bc7805f525f80516020612060833981519152602052815f20335f5260205260ff825f205416156105b85750815490610d2d600554809361193a565b9182156105a8576008546001600160a01b0390811694909190851561059a575083602095610d5e82610d6b9461195b565b60055583600d5416611c80565b6008541681518381527f369356fb24129571814a6e8c0bca61325dff57706be46b7e127a96388920bc34853392a360015f805160206120808339815191525551908152f35b8234610416575f36600319011261041657602090610c0d5f546001549061193a565b50903461041657602036600319011261041657602091355f52600c8252805f20549051908152f35b50903461041657602036600319011261041657610e15611884565b5f80525f80516020612060833981519152602052815f20335f5260205260ff825f20541615610e9c576001600160a01b0316918215610e8e577fe7ae49f883c825b05681b3e00e8be6fdea9ed2a8a45e4c6ecb9390fc44cce61560208484816001600160601b0360a01b600e541617600e5551908152a1005b90516302b6392d60e41b8152fd5b505163088f2b9960e21b8152fd5b8234610416575f36600319011261041657602090517ff1b411d6abb365480ac902cc153c45e9ded5847a2265ce6d01945d253edb6bc78152f35b509034610416575f36600319011261041657610c0d602092546005549061193a565b509034610416575f366003190112610416577f00000000000000000000000091d32d77e01a8165e162600a05ff5f9cfee199dd6001600160a01b03163003610f7157602090517f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8152f35b5163703e46dd60e11b8152fd5b8234610416575f3660031901126104165760085490516001600160a01b039091168152602090f35b508160031936011261041657610fba611884565b602492833567ffffffffffffffff81116104165736602382011215610416578084013592610fe78461191e565b610ff3845191826118fc565b848152602094858201933689838301011161041657815f928a8993018737830101526001600160a01b037f00000000000000000000000091d32d77e01a8165e162600a05ff5f9cfee199dd81163081149081156111d4575b506111c4575f80525f805160206120608339815191528652845f20335f52865260ff855f205416156111b45784516352d1902d60e01b815290831695808289818a5afa9182915f93611184575b50506110b357505050505191634c9c8ce360e01b8352820152fd5b858588928a7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc9182810361116f5750863b1561115b575080546001600160a01b0319168317905551907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a28251156111435750505f6104689381925190845af461113d611fcd565b91611ffc565b92509250503461114f57005b63b398979f60e01b8152fd5b9450505191634c9c8ce360e01b8352820152fd5b8351632a87526960e21b815280870191909152fd5b9080929350813d83116111ad575b61119c81836118fc565b810103126104165751905f80611098565b503d611192565b845163088f2b9960e21b81528790fd5b845163703e46dd60e11b81528790fd5b9050817f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc541614155f61104b565b509034610416575f3660031901126104165761121c611c51565b5f80525f80516020612060833981519152602052805f20335f5260205260ff815f20541615610cab575f5490611255600154809361193a565b9182156105a8576006546001600160a01b0390811694909190851561059a575083602095611286826112939461195b565b60015583600d5416611c80565b6006541681518381527f4f8a50ec1fe3d316970fdadd1f94e0b822f92d31e2bac3c9dc2c6c287de07107853392a360015f805160206120808339815191525551908152f35b509034610416576020366003190112610416576112f3611884565b905f80525f80516020612060833981519152602052805f20335f5260205260ff815f2054161561046a5761046882611bef565b509034610416576113363661189a565b925f80525f80516020612060833981519152602052825f20335f5260205260ff835f205416156113b9574682146113a457507fa7cf6513c602d93075d7a186d6a378c1bbe0fb1274680c2d93d6b2451fbc641192815f52600c60205280835f205582519182526020820152a1005b915163f63d5f4760e01b815291820152602490fd5b825163088f2b9960e21b8152fd5b8234610416575f3660031901126104165760065490516001600160a01b039091168152602090f35b50903461041657806003193601126104165761140961186e565b90336001600160a01b0383160361142557506104689135611b70565b5163334bd91960e11b81529050fd5b5090346104165780600319360112610416576104689135611458600161085d61186e565b611ae6565b8234610416575f36600319011261041657602090516127108152f35b50903461041657602036600319011261041657602091355f525f8051602061206083398151915282526001815f2001549051908152f35b50346104165760203660031901126104165735600a54811015610416576114d6906117ba565b506001815491015482519182526020820152f35b5034610416576114f936611823565b949091935f805260205f80516020612060833981519152602052825f20335f5260205260ff835f20541615610bc1578515801561168d575b610baa57868603610b9b57600a80545f600a5580611630575b505f91825b8884106115885785517f972e8b577cfe35c15038a3117742b96a8dcf69946661b74edc0f25520685322d9080610a398d8b8e8e856119d3565b831515908161161a575b50610b05576127106115a5848b8961199f565b3511610af5576115b683898961199f565b35926115c3818a8a61199f565b356115cf828c8a61199f565b358751916115dc836118b0565b8252838201908152845490600160401b821015610ae25761160360019283810188556117ba565b939093610ad057518355519101556001019261154f565b9050611627848a8a61199f565b3511155f611592565b60016001600160ff1b0382168203610b8857600a5f527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a89160011b8201915b82811061167d57505061154a565b5f8082558282015560020161166f565b508615611531565b8234610416575f366003190112610416576020906005549051908152f35b8234610416575f366003190112610416576020906002549051908152f35b8234610416575f3660031901126104165760075490516001600160a01b039091168152602090f35b5034610416576020366003190112610416573563ffffffff60e01b811680910361041657602091637965db0b60e01b821491821561173b575b50519015158152f35b6301ffc9a760e01b1491505f611732565b50346104165760203660031901126104165735600b54811015610416576114d6905b600b548110156117a657600b5f5260011b7f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db901905f90565b634e487b7160e01b5f52603260045260245ffd5b600a548110156117a657600a5f5260011b7fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a801905f90565b9181601f840112156104165782359167ffffffffffffffff8311610416576020808501948460051b01011161041657565b60406003198201126104165767ffffffffffffffff916004358381116104165782611850916004016117f2565b939093926024359182116104165761186a916004016117f2565b9091565b602435906001600160a01b038216820361041657565b600435906001600160a01b038216820361041657565b6040906003190112610416576004359060243590565b6040810190811067ffffffffffffffff8211176118cc57604052565b634e487b7160e01b5f52604160045260245ffd5b6080810190811067ffffffffffffffff8211176118cc57604052565b90601f8019910116810190811067ffffffffffffffff8211176118cc57604052565b67ffffffffffffffff81116118cc57601f01601f191660200190565b9190820391821161194757565b634e487b7160e01b5f52601160045260245ffd5b9190820180921161194757565b60405190611975826118e0565b5f6060838281528260208201528260408201520152565b8181029291811591840414171561194757565b91908110156117a65760051b0190565b81835290916001600160fb1b0383116104165760209260051b809284830137010190565b92906119ec906119fa95936040865260408601916119af565b9260208185039101526119af565b90565b805f525f8051602061206083398151915260205260405f20335f5260205260ff60405f20541615611a2b5750565b6044906040519063e2517d3f60e01b82523360048301526024820152fd5b6001600160a01b03165f8181527fb7db2dd08fcb62d0c9e08c51941cae53c267786a0b75803fb7960902fc8ef97d60205260409020545f805160206120608339815191529060ff16611ae0575f805260205260405f20815f5260205260405f20600160ff1982541617905533905f7f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d8180a4600190565b50505f90565b90815f525f805160206120608339815191528060205260405f209160018060a01b031691825f5260205260ff60405f205416155f14611b6957825f5260205260405f20815f5260205260405f20600160ff1982541617905533917f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d5f80a4600190565b5050505f90565b90815f525f805160206120608339815191528060205260405f209160018060a01b031691825f5260205260ff60405f2054165f14611b6957825f5260205260405f20815f5260205260405f2060ff19815416905533917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b5f80a4600190565b6001600160a01b03168015611c3f576020817f1a2b7633469609bf03c8dec2e21d406058762579808418889ea62828c177f5a6926001600160601b0360a01b6006541617600655604051908152a1565b6040516302b6392d60e41b8152600490fd5b5f805160206120808339815191526002815414611c6e5760029055565b604051633ee5aeb560e01b8152600490fd5b915f8091611cd39360405195602087019263a9059cbb60e01b845260018060a01b038093166024890152604488015260448752611cbc876118e0565b1694519082865af1611ccc611fcd565b9083611ffc565b8051908115159182611d01575b5050611ce95750565b60249060405190635274afe760e01b82526004820152fd5b81925090602091810103126104165760200151801590811503610416575f80611ce0565b6127108111611d5f576020817fd10d75876659a287a59a6ccfa2e3fff42f84d94b542837acd30bc184d562de4092600955604051908152a1565b604051631f3b85d360e01b8152600490fd5b611d79611968565b50815f52600c60205260405f2054918215611def5750612710611db981611da8611da285611ea7565b8561198c565b0492611db381611f1d565b9061198c565b04611dcd81611dc8848661195b565b61195b565b9160405193611ddb856118e0565b845260208401526040830152606082015290565b6024906040519063f63d5f4760e01b82526004820152fd5b6001600160a01b03168015611c3f576020817feb72ae0cfddfa7bcdd5bad22f400074ba1d93d5588d49dadff45f81a24e5ccc6926001600160601b0360a01b6008541617600855604051908152a1565b6001600160a01b03168015611c3f576020817fbab3f28895988051705d1f76f82bf1b6eefb2470598e6502f4fe06c3bed4101a926001600160601b0360a01b6007541617600755604051908152a1565b600a54908115611ae05790600a5f527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a954915f905b828210611eea575b50505090565b909192611ef6836117ba565b50548210611f175750600180611f0b846117ba565b50015493920190611edc565b92611ee4565b600b54908115611ae05790600b5f527f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01dba54915f905b828210611f5f5750505090565b909192611f6b8361176e565b50548210611f175750600180611f808461176e565b50015493920190611f52565b60ff7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a005460401c1615611fbb57565b604051631afcd79f60e31b8152600490fd5b3d15611ff7573d90611fde8261191e565b91611fec60405193846118fc565b82523d5f602084013e565b606090565b90612023575080511561201157805190602001fd5b604051630a12f52160e11b8152600490fd5b81511580612056575b612034575090565b604051639996b31560e01b81526001600160a01b039091166004820152602490fd5b50803b1561202c56fe02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b6268009b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00a2646970667358221220e3ebd0a50cd6de78cf666c69e8abc9c3c6bcce488c5fb06bdb32e3ee5ae3e46964736f6c63430008180033

Verified Source Code Full Match

Compiler: v0.8.24+commit.e11b9ed9 EVM: cancun Optimization: Yes (200 runs)
FeeCollector.sol 612 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {GeniusErrors} from "../libs/GeniusErrors.sol";
import {IFeeCollector} from "../interfaces/IFeeCollector.sol";

/**
 * @title FeeCollector
 * @notice Handles the calculation, collection, and distribution of fees in the Genius protocol
 * @dev This contract is upgradeable and receives fees from the vault
 */
contract FeeCollector is
    IFeeCollector,
    UUPSUpgradeable,
    AccessControlUpgradeable,
    ReentrancyGuardUpgradeable
{
    using SafeERC20 for IERC20;

    bytes32 public constant DISTRIBUTOR_ROLE = keccak256("DISTRIBUTOR_ROLE");
    bytes32 public constant WORKER_ROLE = keccak256("WORKER_ROLE");
    uint256 public constant BASE_PERCENTAGE = 10_000;

    // Protocol/LP/Operator fees accounting
    uint256 public protocolFeesCollected;
    uint256 public protocolFeesClaimed;
    uint256 public lpFeesCollected;
    uint256 public lpFeesClaimed;
    uint256 public operatorFeesCollected;
    uint256 public operatorFeesClaimed;

    // Fee receivers for each fee type
    address public protocolFeeReceiver;
    address public lpFeeReceiver;
    address public operatorFeeReceiver;

    // Fee settings
    uint256 public protocolFee; // What percentage of the bps fees goes to protocol

    // Fee tiers for order size (sorted from smallest to largest threshold)
    FeeTier[] public feeTiers;
    FeeTier[] public insuranceFeeTiers;

    // Minimum fees per chain (token => chainId => minFee)
    mapping(uint256 => uint256) public targetChainMinFee;

    // The token (stablecoin) used for fees
    IERC20 public stablecoin;

    // Only the vault can add fees
    address public vault;

    modifier onlyAdmin() {
        if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender))
            revert GeniusErrors.IsNotAdmin();
        _;
    }

    // Constructor disables initialization for implementation contract
    constructor() {
        _disableInitializers();
    }

    /**
     * @notice Initializes the FeeCollector contract
     * @param _admin Admin address that can manage fee settings
     * @param _stablecoin The stablecoin used for fee payments
     * @param _protocolFee The percentage of the bps fees allocated to protocol
     */
    function initialize(
        address _admin,
        address _stablecoin,
        uint256 _protocolFee,
        address _protocolFeeReceiver,
        address _lpFeeReceiver,
        address _operatorFeeReceiver
    ) external initializer {
        if (_admin == address(0)) revert GeniusErrors.NonAddress0();
        if (_stablecoin == address(0)) revert GeniusErrors.NonAddress0();

        // Protocol + LP fees cannot exceed 100%
        if (_protocolFee > BASE_PERCENTAGE)
            revert GeniusErrors.InvalidPercentage();

        __AccessControl_init();
        __UUPSUpgradeable_init();
        __ReentrancyGuard_init();

        _setStablecoin(_stablecoin);
        _setProtocolFee(_protocolFee);

        // Set default receivers to admin
        _setProtocolFeeReceiver(_protocolFeeReceiver);
        _setLPFeeReceiver(_lpFeeReceiver);
        _setOperatorFeeReceiver(_operatorFeeReceiver);

        _grantRole(DEFAULT_ADMIN_ROLE, _admin);
    }

    /**
     * @notice Collects and processes fees for an order
     * @dev Can only be called by the vault
     * @param _orderHash The hash of the order
     * @param _amountIn The order amount
     * @param _destChainId The destination chain ID
     * @param _orderFee The total fee amount provided with the order
     * @return amountToTransfer The amount of fees to transfer to the fee collector
     */
    function collectFromVault(
        bytes32 _orderHash,
        uint256 _amountIn,
        uint256 _destChainId,
        uint256 _orderFee
    ) external returns (uint256 amountToTransfer) {
        if (msg.sender != vault) revert GeniusErrors.NotAuthorized();
        if (_amountIn == 0) revert GeniusErrors.InvalidAmount();

        // Calculate fee breakdown
        FeeBreakdown memory feeBreakdown = _calculateFeeBreakdown(
            _amountIn,
            _destChainId
        );

        // Check if the provided fee is sufficient
        if (_orderFee < feeBreakdown.totalFee)
            revert GeniusErrors.InsufficientFees(
                _orderFee,
                feeBreakdown.totalFee
            );

        // Calculate any surplus fee over the required minimum
        uint256 feeSurplus = 0;
        if (_orderFee > feeBreakdown.totalFee) {
            feeSurplus = _orderFee - feeBreakdown.totalFee;
        }

        // Calculate fee distribution based on percentages
        uint256 protocolFeeAmount = (feeBreakdown.bpsFee * protocolFee) /
            BASE_PERCENTAGE;
        uint256 lpFee = feeBreakdown.bpsFee - protocolFeeAmount;

        // Add fees to their respective buckets
        protocolFeesCollected += protocolFeeAmount;
        lpFeesCollected += lpFee;

        // Add base fee plus any surplus to the operator fees
        operatorFeesCollected += feeBreakdown.baseFee + feeSurplus;

        // The vault should transfer the total fee minus insurance fee to the fee collector
        amountToTransfer = _orderFee - feeBreakdown.insuranceFee;

        emit FeesCollectedFromVault(
            _orderHash,
            protocolFeeAmount,
            lpFee,
            feeBreakdown.baseFee + feeSurplus
        );
        return amountToTransfer;
    }

    /**
     * @notice Allows admins to claim protocol fees for the designated receiver
     * @return amount The amount of fees claimed
     */
    function claimProtocolFees()
        external
        nonReentrant
        onlyAdmin
        returns (uint256 amount)
    {
        amount = protocolFeesCollected - protocolFeesClaimed;
        if (amount == 0) revert GeniusErrors.InvalidAmount();
        if (protocolFeeReceiver == address(0))
            revert GeniusErrors.NonAddress0();

        protocolFeesClaimed += amount;
        stablecoin.safeTransfer(protocolFeeReceiver, amount);

        emit ProtocolFeesClaimed(msg.sender, protocolFeeReceiver, amount);
        return amount;
    }

    /**
     * @notice Allows LP fee distributors to claim LP fees for the designated receiver
     * @return amount The amount of fees claimed
     */
    function claimLPFees()
        external
        nonReentrant
        onlyRole(DISTRIBUTOR_ROLE)
        returns (uint256 amount)
    {
        amount = lpFeesCollected - lpFeesClaimed;
        if (amount == 0) revert GeniusErrors.InvalidAmount();
        if (lpFeeReceiver == address(0)) revert GeniusErrors.NonAddress0();

        lpFeesClaimed += amount;
        stablecoin.safeTransfer(lpFeeReceiver, amount);

        emit LPFeesClaimed(msg.sender, lpFeeReceiver, amount);
        return amount;
    }

    /**
     * @notice Allows workers to claim operator fees for the designated receiver
     * @return amount The amount of fees claimed
     */
    function claimOperatorFees()
        external
        nonReentrant
        onlyRole(WORKER_ROLE)
        returns (uint256 amount)
    {
        amount = operatorFeesCollected - operatorFeesClaimed;
        if (amount == 0) revert GeniusErrors.InvalidAmount();
        if (operatorFeeReceiver == address(0))
            revert GeniusErrors.NonAddress0();

        operatorFeesClaimed += amount;
        stablecoin.safeTransfer(operatorFeeReceiver, amount);

        emit OperatorFeesClaimed(msg.sender, operatorFeeReceiver, amount);
        return amount;
    }

    /**
     * @notice Sets the protocol fee receiver address
     * @param _receiver The address to receive protocol fees
     */
    function setProtocolFeeReceiver(address _receiver) external onlyAdmin {
        _setProtocolFeeReceiver(_receiver);
    }

    /**
     * @notice Sets the LP fee receiver address
     * @param _receiver The address to receive LP fees
     */
    function setLPFeeReceiver(address _receiver) external onlyAdmin {
        _setLPFeeReceiver(_receiver);
    }

    /**
     * @notice Sets the operator fee receiver address
     * @param _receiver The address to receive operator fees
     */
    function setOperatorFeeReceiver(address _receiver) external onlyAdmin {
        _setOperatorFeeReceiver(_receiver);
    }

    /**
     * @notice Sets the vault address that can update fees
     * @param _vault The vault contract address
     */
    function setVault(address _vault) external onlyAdmin {
        _setVault(_vault);
    }

    /**
     * @notice Sets the protocol fee percentage
     * @param _protocolFee Percentage of the BPS fees allocated to protocol
     */
    function setProtocolFee(uint256 _protocolFee) external onlyAdmin {
        _setProtocolFee(_protocolFee);
    }

    /**
     * @notice Sets the minimum fee for a target chain
     * @param _targetChainId The id of the target chain
     * @param _minFee The new minimum fee for the target chain
     */
    function setTargetChainMinFee(
        uint256 _targetChainId,
        uint256 _minFee
    ) external onlyAdmin {
        _setTargetChainMinFee(_targetChainId, _minFee);
    }

    /**
     * @notice Sets the fee tiers based on order size
     * @param _thresholdAmounts Array of threshold amounts for each tier (minimum order size)
     * @param _bpsFees Array of basis point fees for each tier
     */
    function setFeeTiers(
        uint256[] calldata _thresholdAmounts,
        uint256[] calldata _bpsFees
    ) external onlyAdmin {
        _setFeeTiers(_thresholdAmounts, _bpsFees);
    }

    /**
     * @notice Sets the tiered insurance fee structure based on order size
     * @param _thresholdAmounts Array of threshold amounts for each tier
     * @param _bpsFees Array of basis point fees for each tier
     */
    function setInsuranceFeeTiers(
        uint256[] calldata _thresholdAmounts,
        uint256[] calldata _bpsFees
    ) external onlyAdmin {
        _setInsuranceFeeTiers(_thresholdAmounts, _bpsFees);
    }

    /**
     * @notice Returns the total claimable protocol fees
     * @return Amount of protocol fees available to claim
     */
    function claimableProtocolFees() external view returns (uint256) {
        return protocolFeesCollected - protocolFeesClaimed;
    }

    /**
     * @notice Returns the total claimable LP fees
     * @return Amount of LP fees available to claim
     */
    function claimableLPFees() external view returns (uint256) {
        return lpFeesCollected - lpFeesClaimed;
    }

    /**
     * @notice Returns the total claimable operator fees
     * @return Amount of operator fees available to claim
     */
    function claimableOperatorFees() external view returns (uint256) {
        return operatorFeesCollected - operatorFeesClaimed;
    }

    /**
     * @notice Calculates the complete fee breakdown for an order
     * @param _amount The order amount
     * @param _destChainId The destination chain ID
     * @return A FeeBreakdown struct containing the breakdown of fees
     */
    function getOrderFees(
        uint256 _amount,
        uint256 _destChainId
    ) external view returns (FeeBreakdown memory) {
        return _calculateFeeBreakdown(_amount, _destChainId);
    }

    /**
     * @dev Internal function to set the stablecoin address
     * @param _stablecoin The address of the stablecoin
     */
    function _setStablecoin(address _stablecoin) internal {
        if (_stablecoin == address(0)) revert GeniusErrors.NonAddress0();
        stablecoin = IERC20(_stablecoin);
    }

    /**
     * @dev Internal function to set the protocol fee receiver address
     * @param _receiver The address to receive protocol fees
     */
    function _setProtocolFeeReceiver(address _receiver) internal {
        if (_receiver == address(0)) revert GeniusErrors.NonAddress0();
        protocolFeeReceiver = _receiver;
        emit ProtocolFeeReceiverSet(_receiver);
    }

    /**
     * @dev Internal function to set the LP fee receiver address
     * @param _receiver The address to receive LP fees
     */
    function _setLPFeeReceiver(address _receiver) internal {
        if (_receiver == address(0)) revert GeniusErrors.NonAddress0();
        lpFeeReceiver = _receiver;
        emit LPFeeReceiverSet(_receiver);
    }

    /**
     * @dev Internal function to set the operator fee receiver address
     * @param _receiver The address to receive operator fees
     */
    function _setOperatorFeeReceiver(address _receiver) internal {
        if (_receiver == address(0)) revert GeniusErrors.NonAddress0();
        operatorFeeReceiver = _receiver;
        emit OperatorFeeReceiverSet(_receiver);
    }

    /**
     * @dev Internal function to set the vault address
     * @param _vault The vault contract address
     */
    function _setVault(address _vault) internal {
        if (_vault == address(0)) revert GeniusErrors.NonAddress0();
        vault = _vault;
        emit VaultSet(_vault);
    }

    /**
     * @dev Internal function to set the protocol fee percentage
     * @param _protocolFee Percentage of the BPS fees allocated to protocol
     */
    function _setProtocolFee(uint256 _protocolFee) internal {
        // Protocol + LP fees cannot exceed 100%
        if (_protocolFee > BASE_PERCENTAGE)
            revert GeniusErrors.InvalidPercentage();

        protocolFee = _protocolFee;
        emit ProtocolFeeUpdated(_protocolFee);
    }

    /**
     * @dev Internal function to set the minimum fee for a target chain.
     * @param _targetChainId The target chain ID.
     * @param _minFee The minimum fee required.
     */
    function _setTargetChainMinFee(
        uint256 _targetChainId,
        uint256 _minFee
    ) internal {
        if (_targetChainId == block.chainid)
            revert GeniusErrors.InvalidDestChainId(_targetChainId);

        targetChainMinFee[_targetChainId] = _minFee;
        emit TargetChainMinFeeChanged(_targetChainId, _minFee);
    }

    /**
     * @dev Internal function to set fee tiers based on order size.
     * The tiers should be ordered from smallest to largest threshold amount.
     * @param _thresholdAmounts Array of threshold amounts for each tier (minimum order size for tier)
     * @param _bpsFees Array of basis point fees for each tier
     */
    function _setFeeTiers(
        uint256[] calldata _thresholdAmounts,
        uint256[] calldata _bpsFees
    ) internal {
        if (_thresholdAmounts.length == 0 || _bpsFees.length == 0)
            revert GeniusErrors.EmptyArray();

        if (_thresholdAmounts.length != _bpsFees.length)
            revert GeniusErrors.ArrayLengthsMismatch();

        // Clear existing tiers
        delete feeTiers;

        // Validate inputs and add new tiers
        uint256 prevThreshold = 0;

        for (uint256 i = 0; i < _thresholdAmounts.length; i++) {
            // Ensure tiers are in ascending order
            if (i > 0 && _thresholdAmounts[i] <= prevThreshold)
                revert GeniusErrors.InvalidAmount();

            // Validate bps fee
            if (_bpsFees[i] > BASE_PERCENTAGE)
                revert GeniusErrors.InvalidPercentage();

            prevThreshold = _thresholdAmounts[i];

            // Add the tier
            feeTiers.push(
                FeeTier({
                    thresholdAmount: _thresholdAmounts[i],
                    bpsFee: _bpsFees[i]
                })
            );
        }

        emit FeeTiersUpdated(_thresholdAmounts, _bpsFees);
    }

    /**
     * @dev Internal function to set insurance fee tiers based on order size.
     * The tiers should be ordered from smallest to largest threshold amount.
     * @param _thresholdAmounts Array of threshold amounts for each tier (minimum order size for tier)
     * @param _bpsFees Array of basis point fees for each tier
     */
    function _setInsuranceFeeTiers(
        uint256[] calldata _thresholdAmounts,
        uint256[] calldata _bpsFees
    ) internal {
        if (_thresholdAmounts.length == 0 || _bpsFees.length == 0)
            revert GeniusErrors.EmptyArray();

        if (_thresholdAmounts.length != _bpsFees.length)
            revert GeniusErrors.ArrayLengthsMismatch();

        // Clear existing tiers
        delete insuranceFeeTiers;

        // Validate inputs and add new tiers
        uint256 prevThreshold = 0;

        for (uint256 i = 0; i < _thresholdAmounts.length; i++) {
            // Ensure tiers are in ascending order
            if (i > 0 && _thresholdAmounts[i] <= prevThreshold)
                revert GeniusErrors.InvalidAmount();

            // Validate bps fee
            if (_bpsFees[i] > BASE_PERCENTAGE)
                revert GeniusErrors.InvalidPercentage();

            prevThreshold = _thresholdAmounts[i];

            // Add the tier
            insuranceFeeTiers.push(
                FeeTier({
                    thresholdAmount: _thresholdAmounts[i],
                    bpsFee: _bpsFees[i]
                })
            );
        }

        emit InsuranceFeeTiersUpdated(_thresholdAmounts, _bpsFees);
    }

    /**
     * @dev Internal function to determine the basis points fee based on order size.
     * Returns the bps fee for the appropriate tier.
     * If no tiers are set or amount is below the first tier, returns 0.
     * @param _amount The order amount to determine the fee for
     * @return bpsFee The basis points fee to apply
     */
    function _getBpsFeeForAmount(
        uint256 _amount
    ) internal view returns (uint256 bpsFee) {
        if (feeTiers.length == 0) return 0;

        // Default to the lowest tier fee
        bpsFee = feeTiers[0].bpsFee;

        // Find the highest tier that the amount qualifies for
        for (uint256 i = 0; i < feeTiers.length; i++) {
            if (_amount >= feeTiers[i].thresholdAmount) {
                bpsFee = feeTiers[i].bpsFee;
            } else {
                // Found a tier with threshold higher than amount, so break
                break;
            }
        }

        return bpsFee;
    }

    /**
     * @dev Internal function to determine the insurance fee basis points based on order size.
     * Returns the bps fee for the appropriate tier.
     * If no tiers are set or amount is below the first tier, returns 0.
     * @param _amount The order amount to determine the fee for
     * @return bpsFee The basis points fee to apply
     */
    function _getInsuranceFeeBpsForAmount(
        uint256 _amount
    ) internal view returns (uint256 bpsFee) {
        if (insuranceFeeTiers.length == 0) return 0;

        // Default to the lowest tier fee
        bpsFee = insuranceFeeTiers[0].bpsFee;

        // Find the highest tier that the amount qualifies for
        for (uint256 i = 0; i < insuranceFeeTiers.length; i++) {
            if (_amount >= insuranceFeeTiers[i].thresholdAmount) {
                bpsFee = insuranceFeeTiers[i].bpsFee;
            } else {
                // Found a tier with threshold higher than amount, so break
                break;
            }
        }

        return bpsFee;
    }

    /**
     * @dev Internal function to calculate the complete fee breakdown for an order
     * @param _amount The order amount
     * @param _destChainId The destination chain ID
     * @return FeeBreakdown containing the breakdown of fees
     */
    function _calculateFeeBreakdown(
        uint256 _amount,
        uint256 _destChainId
    ) internal view returns (FeeBreakdown memory) {
        uint256 baseFee = targetChainMinFee[_destChainId];

        if (baseFee == 0) {
            revert GeniusErrors.InvalidDestChainId(_destChainId);
        }

        // Calculate BPS fee
        uint256 bpsFeePercentage = _getBpsFeeForAmount(_amount);
        uint256 bpsFee = (_amount * bpsFeePercentage) / BASE_PERCENTAGE;

        // Calculate insurance fee
        uint256 insuranceFeePercentage = _getInsuranceFeeBpsForAmount(_amount);
        uint256 insuranceFee = (_amount * insuranceFeePercentage) /
            BASE_PERCENTAGE;

        // Calculate total fee
        uint256 totalFee = baseFee + bpsFee + insuranceFee;

        return
            FeeBreakdown({
                baseFee: baseFee,
                bpsFee: bpsFee,
                insuranceFee: insuranceFee,
                totalFee: totalFee
            });
    }

    /**
     * @dev Authorizes contract upgrades
     * @param newImplementation The address of the new implementation
     */
    function _authorizeUpgrade(
        address newImplementation
    ) internal override onlyAdmin {}
}
UUPSUpgradeable.sol 153 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.20;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC1967-compliant implementation pointing to self.
     * See {_onlyProxy}.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}
AccessControlUpgradeable.sol 233 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.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 {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    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` to `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;
        }
    }
}
ReentrancyGuardUpgradeable.sol 105 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 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;
    }
}
SafeERC20.sol 118 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 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 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 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 {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @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 {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    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.
     */
    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.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), 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 data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), 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 data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
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);
}
GeniusErrors.sol 273 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

library GeniusErrors {
    /**
     * @dev Error thrown when an invalid address is encountered.
     */
    error NonAddress0();

    /**
     * @dev Error thrown when an invalid spender address is encountered.
     */
    error InvalidSpender();

    /**
     * @dev Error thrown when an invalid trader address is encountered.
     */
    error InvalidTrader();

    /**
     * @dev Error thrown when msg.sender is not the vault.
     */
    error IsNotVault();

    error IsNotExecutor();

    error IsNotPauser();

    error IsNotOrchestrator();

    error IsNotOrchestratorNorAdmin();

    /**
     * @dev Error thrown when an invalid admin address is encountered.
     */
    error IsNotAdmin();

    /**
     * @dev This library contains custom error definitions for the Genius contract.
     */
    error Paused();

    /**
     * @dev Error thrown when the contract is already initialized.
     */
    error Initialized();

    /**
     * @dev Error thrown when the contract is not initialized.
     */
    error NotInitialized();

    /**
     * @dev Error thrown when an invalid amount is encountered.
     */
    error InvalidAmount();

    /**
     * @dev Error thrown when the expected change is invalid.
     */
    error InvalidDelta();

    /**
     * @dev Error thrown when the array lengths do not match.
     */
    error ArrayLengthsMismatch();

    /**
     * @dev Error thrown when the array is empty.
     */
    error EmptyArray();

    /**
     * @dev Error thrown when the permit batch length is invalid.
     */
    error InvalidPermitBatchLength();

    error InvalidOrderStatus();

    error InvalidSeed();

    /**
     * @dev Error thrown thrown when the msg.value is not sufficient.
     */
    error InvalidNativeAmount();

    /**
     * @dev Error thrown when the target of a generic call is invalid.
     */
    error InvalidTarget(address invalidTarget);

    /**
     * @dev Error thrown when the target of a generic swap call is to an unauthorized bridge.
     */
    error InvalidBridge(address invalidBridge);

    /**
     * @dev Error thrown when the target of a generic swap call is to an unauthorized router.
     */
    error InvalidRouter(address invalidRouter);

    /**
     * @dev Error thrown when attempting to add a duplicate router.
     */
    error DuplicateRouter(address router);

    /**
     * @dev Error thrown when attempting to add a duplicate token.
     */
    error DuplicateToken(address token);

    /**
     * @dev Error thrown when a supported tokens balance is unexpectedly decreased.
     */
    error UnexpectedBalanceDecrease(
        address token,
        uint256 postBalance,
        uint256 preBalance
    );

    /**
     * @dev Error thrown when the the balance of a token is unexpectedly changed.
     * @param token The address of the effected token.
     * @param expectedBalance The expected balance of the token.
     * @param newBalance The new balance of the token.
     */
    error UnexpectedBalanceChange(
        address token,
        uint256 expectedBalance,
        uint256 newBalance
    );

    /**
     * @dev Error thrown when there is an insufficient amount of STABLECOIN available for rebalance
            or swaps in the contract.
     */
    error InsufficientLiquidity(
        uint256 availableLiquidity,
        uint256 requiredLiquidity
    );

    /**
     * @dev Error thrown when an invalid amount is passed to a function.
     * @param assets The amount that was passed.
     * @param shares The amount that was expected.
     */
    error InvalidAssetAmount(uint256 assets, uint256 shares);

    /**
     * @dev Error thrown when an approval fails.
     * @param token The address of the token that is required.
     * @param amount The amount that is required.
     */
    error ApprovalFailure(address token, uint256 amount);

    /**
     * @dev Error thrown when an approval fails.
     * @param token The address of the token that is required.
     * @param amount The amount that is required.
     */
    error TransferFailed(address token, uint256 amount);

    /**
     * @dev Error thrown when an external call fails.
     * @param target The address of the target contract.
     */
    error ExternalCallFailed(address target);

    /**
     * @dev Error thrown when there is insufficient native balance.
     * @param expectedAmount The amount that is required.
     * @param actualAmount The amount that is available.
     */
    error InsufficientNativeBalance(
        uint256 expectedAmount,
        uint256 actualAmount
    );

    /**
     * @dev Error thrown when there is insufficient fees to collect.
     * @param attemptedAmount The amount that was attempted to be collected.
     * @param actualAmount The amount that was actually collected.
     */
    error InsufficientFees(uint256 attemptedAmount, uint256 actualAmount);

    /**
     * @dev Error thrown when there is remaining balance of a supported token when
     *      attempting to remove support for the token.
     * @param amount The amount that would be left in the contract.
     */
    error RemainingBalance(uint256 amount);

    /**
     * @dev Error thrown when there is a residual STABLECOIN balance after an external call.
     * @param amount The amount that of STABLECOIN that would be left in the contract.
     */
    error ResidualBalance(uint256 amount);

    /**
     * @dev Error thrown when there is insufficient token balance.
     * @param token The address of the token.
     * @param amount The amount that is required.
     * @param balance The balance that is available.
     */
    error InsufficientBalance(address token, uint256 amount, uint256 balance);

    /**
     * @dev Thrown when a token address is invalid.
     * @param token The adddress of the invalid token.
     */
    error InvalidToken(address token);

    /**
     * @dev Thrown when a token bytes32 is invalid.
     */
    error InvalidTokenIn();

    /**
     * @dev Thrown when attempting to set a threshold balance that would exceed the minimum STABLECOIN balance needed.
     * @param threshBal The threshold balance being attempted to set.
     * @param attemptedThreshBal The balance that would be exceeded if the threshold is set.
     */
    error ThresholdWouldExceed(uint256 threshBal, uint256 attemptedThreshBal);

    error InvalidAmountOut(uint256 amountOut, uint256 minAmountOut);

    error OrderAlreadyFilled(bytes32 srcOrderHash);

    error InvalidDestChainId(uint256 chainId);

    error InvalidSourceChainId(uint256 chainId);

    error DeadlinePassed(uint256 deadline);

    error DeadlineNotPassed(uint256 deadline);

    error InvalidDeadline();

    error InvalidPercentage();

    error NoStablecoinBalanceIncrease();

    error InvalidSignature();

    error InvalidCallerMulticall();

    error TargetIsNotContract();

    error ApprovalTargetIsNotContract();

    error InvalidCaller();

    error TokenOrTargetChainNotSupported();

    error PriceOutOfBounds(uint256 price);
    error StalePrice(uint256 timestamp);
    error PriceFeedError();

    error InvalidRound();
    error InvalidPrice();
    error InvalidBytes32Address();

    error AccessDenied();
    error LabelAlreadyExists();
    error IpfsHashAlreadyExists();
    error IncorrectIpfsHash();
    error ActionDoesNotExist();
    error SameIpfsHash();
    error NewLabelExists();
    error StatusAlreadySet();
    error NotAuthorized();
    error InvalidFeeAmount();
}
IFeeCollector.sol 257 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

/**
 * @title IFeeCollector
 * @notice Interface for the FeeCollector contract
 */
interface IFeeCollector {
    /**
     * @notice Struct representing a fee tier based on order size
     * @param thresholdAmount Minimum amount for this tier
     * @param bpsFee Basis points fee for this tier
     */
    struct FeeTier {
        uint256 thresholdAmount; // Minimum amount for this tier
        uint256 bpsFee; // Basis points fee for this tier
    }

    /**
     * @notice Breakdown of different fee components for an order
     * @param baseFee Base fee that goes to operations
     * @param bpsFee BPS fee that goes to fee collector
     * @param insuranceFee Insurance fee that gets re-injected into liquidity
     * @param totalFee Total fee (sum of all components)
     */
    struct FeeBreakdown {
        uint256 baseFee;
        uint256 bpsFee;
        uint256 insuranceFee;
        uint256 totalFee;
    }

    /**
     * @notice Emitted when fees are updated by the vault
     * @param orderHash The hash of the order processed
     * @param protocolFee Amount of protocol fees added
     * @param lpFee Amount of LP fees added
     * @param operatorFee Amount of operator fees added
     */
    event FeesCollectedFromVault(
        bytes32 indexed orderHash,
        uint256 protocolFee,
        uint256 lpFee,
        uint256 operatorFee
    );

    /**
     * @notice Emitted when protocol fees are claimed
     * @param claimant The address that initiated the claim
     * @param receiver The address that received the fees
     * @param amount The amount claimed
     */
    event ProtocolFeesClaimed(
        address indexed claimant,
        address indexed receiver,
        uint256 amount
    );

    /**
     * @notice Emitted when LP fees are claimed
     * @param claimant The address that initiated the claim
     * @param receiver The address that received the fees
     * @param amount The amount claimed
     */
    event LPFeesClaimed(
        address indexed claimant,
        address indexed receiver,
        uint256 amount
    );

    /**
     * @notice Emitted when operator fees are claimed
     * @param claimant The address that initiated the claim
     * @param receiver The address that received the fees
     * @param amount The amount claimed
     */
    event OperatorFeesClaimed(
        address indexed claimant,
        address indexed receiver,
        uint256 amount
    );

    /**
     * @notice Emitted when the protocol fee receiver is set
     * @param receiver The new protocol fee receiver
     */
    event ProtocolFeeReceiverSet(address receiver);

    /**
     * @notice Emitted when the LP fee receiver is set
     * @param receiver The new LP fee receiver
     */
    event LPFeeReceiverSet(address receiver);

    /**
     * @notice Emitted when the operator fee receiver is set
     * @param receiver The new operator fee receiver
     */
    event OperatorFeeReceiverSet(address receiver);

    /**
     * @notice Emitted when the vault address is set
     * @param vault The new vault address
     */
    event VaultSet(address vault);

    /**
     * @notice Emitted when the protocol fee percentage is updated
     * @param protocolFee The new protocol fee percentage
     */
    event ProtocolFeeUpdated(uint256 protocolFee);

    /**
     * @notice Emitted when the fee tiers based on order size are updated
     * @param thresholdAmounts Array of threshold amounts for each tier
     * @param bpsFees Array of basis point fees for each tier
     */
    event FeeTiersUpdated(uint256[] thresholdAmounts, uint256[] bpsFees);

    /**
     * @notice Emitted when insurance fee tiers are updated
     */
    event InsuranceFeeTiersUpdated(
        uint256[] thresholdAmounts,
        uint256[] bpsFees
    );

    /**
     * @notice Emitted when the minimum fee for a target chain has changed
     * @param targetChainId The id of the target chain
     * @param newMinFee The new minimum fee for the target chain
     */
    event TargetChainMinFeeChanged(uint256 targetChainId, uint256 newMinFee);

    /**
     * @notice Collects and processes fees for an order
     * @dev Can only be called by the vault
     * @param _orderHash The hash of the order
     * @param _amountIn The order amount
     * @param _destChainId The destination chain ID
     * @param _orderFee The total fee amount provided with the order
     * @return amountToTransfer The amount of fees to transfer to the fee collector
     */
    function collectFromVault(
        bytes32 _orderHash,
        uint256 _amountIn,
        uint256 _destChainId,
        uint256 _orderFee
    ) external returns (uint256 amountToTransfer);

    /**
     * @notice Allows admins to claim protocol fees for the designated receiver
     * @return amount The amount of fees claimed
     */
    function claimProtocolFees() external returns (uint256 amount);

    /**
     * @notice Allows LP fee distributors to claim LP fees for the designated receiver
     * @return amount The amount of fees claimed
     */
    function claimLPFees() external returns (uint256 amount);

    /**
     * @notice Allows workers to claim operator fees for the designated receiver
     * @return amount The amount of fees claimed
     */
    function claimOperatorFees() external returns (uint256 amount);

    /**
     * @notice Sets the protocol fee receiver address
     * @param _receiver The address to receive protocol fees
     */
    function setProtocolFeeReceiver(address _receiver) external;

    /**
     * @notice Sets the LP fee receiver address
     * @param _receiver The address to receive LP fees
     */
    function setLPFeeReceiver(address _receiver) external;

    /**
     * @notice Sets the operator fee receiver address
     * @param _receiver The address to receive operator fees
     */
    function setOperatorFeeReceiver(address _receiver) external;

    /**
     * @notice Sets the vault address that can update fees
     * @param _vault The vault contract address
     */
    function setVault(address _vault) external;

    /**
     * @notice Sets the protocol fee percentage
     * @param _protocolFee Percentage of the BPS fees allocated to protocol
     */
    function setProtocolFee(uint256 _protocolFee) external;

    /**
     * @notice Sets the minimum fee for a target chain
     * @param _targetChainId The id of the target chain
     * @param _minFee The new minimum fee for the target chain
     */
    function setTargetChainMinFee(
        uint256 _targetChainId,
        uint256 _minFee
    ) external;

    /**
     * @notice Sets the fee tiers based on order size
     * @param _thresholdAmounts Array of threshold amounts for each tier (minimum order size)
     * @param _bpsFees Array of basis point fees for each tier
     */
    function setFeeTiers(
        uint256[] calldata _thresholdAmounts,
        uint256[] calldata _bpsFees
    ) external;

    /**
     * @notice Sets the tiered insurance fee structure based on order size
     * @param _thresholdAmounts Array of threshold amounts for each tier
     * @param _bpsFees Array of basis point fees for each tier
     */
    function setInsuranceFeeTiers(
        uint256[] calldata _thresholdAmounts,
        uint256[] calldata _bpsFees
    ) external;

    /**
     * @notice Returns the total claimable protocol fees
     * @return Amount of protocol fees available to claim
     */
    function claimableProtocolFees() external view returns (uint256);

    /**
     * @notice Returns the total claimable LP fees
     * @return Amount of LP fees available to claim
     */
    function claimableLPFees() external view returns (uint256);

    /**
     * @notice Returns the total claimable operator fees
     * @return Amount of operator fees available to claim
     */
    function claimableOperatorFees() external view returns (uint256);

    /**
     * @notice Calculates the complete fee breakdown for an order
     * @param _amount The order amount
     * @param _destChainId The destination chain ID
     * @return A FeeBreakdown struct containing the breakdown of fees
     */
    function getOrderFees(
        uint256 _amount,
        uint256 _destChainId
    ) external view returns (FeeBreakdown memory);
}
draft-IERC1822.sol 20 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}
ERC1967Utils.sol 193 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.20;

import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 */
library ERC1967Utils {
    // We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
    // This will be fixed in Solidity 0.8.21. At that point we should remove these events.
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}
Initializable.sol 228 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}
IAccessControl.sol 98 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC165 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 signaling 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, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    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 role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @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.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @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 granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}
ContextUpgradeable.sol 34 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    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;
    }
}
ERC165Upgradeable.sol 33 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165Upgradeable is Initializable, IERC165 {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}
IERC20Permit.sol 90 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}
Address.sol 159 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}
IBeacon.sol 16 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}
StorageSlot.sol 135 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * 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[EIP 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);
}

Read Contract

BASE_PERCENTAGE 0x2643d627 → uint256
DEFAULT_ADMIN_ROLE 0xa217fddf → bytes32
DISTRIBUTOR_ROLE 0xf0bd87cc → bytes32
UPGRADE_INTERFACE_VERSION 0xad3cb1cc → string
WORKER_ROLE 0x634252dc → bytes32
claimableLPFees 0x97ede1d4 → uint256
claimableOperatorFees 0x5537a2c9 → uint256
claimableProtocolFees 0x70a1c1ff → uint256
feeTiers 0x230ed44a → uint256, uint256
getOrderFees 0xae35f640 → tuple
getRoleAdmin 0x248a9ca3 → bytes32
hasRole 0x91d14854 → bool
insuranceFeeTiers 0x01dc937e → uint256, uint256
lpFeeReceiver 0x09d2d0bc → address
lpFeesClaimed 0xfbe984a3 → uint256
lpFeesCollected 0x123ccd7f → uint256
operatorFeeReceiver 0x5225dcc0 → address
operatorFeesClaimed 0x183590e5 → uint256
operatorFeesCollected 0xf0011186 → uint256
protocolFee 0xb0e21e8a → uint256
protocolFeeReceiver 0x39a51be5 → address
protocolFeesClaimed 0xbfca3627 → uint256
protocolFeesCollected 0xcc08b834 → uint256
proxiableUUID 0x52d1902d → bytes32
stablecoin 0xe9cbd822 → address
supportsInterface 0x01ffc9a7 → bool
targetChainMinFee 0x6d127cfb → uint256
vault 0xfbfa77cf → address

Write Contract 17 functions

These functions modify contract state and require a wallet transaction to execute.

claimLPFees 0xfbf00e02
No parameters
returns: uint256
claimOperatorFees 0x7486caee
No parameters
returns: uint256
claimProtocolFees 0x4a7d0369
No parameters
returns: uint256
collectFromVault 0xdf269166
bytes32 _orderHash
uint256 _amountIn
uint256 _destChainId
uint256 _orderFee
returns: uint256
grantRole 0x2f2ff15d
bytes32 role
address account
initialize 0xff9935cb
address _admin
address _stablecoin
uint256 _protocolFee
address _protocolFeeReceiver
address _lpFeeReceiver
address _operatorFeeReceiver
renounceRole 0x36568abe
bytes32 role
address callerConfirmation
revokeRole 0xd547741f
bytes32 role
address account
setFeeTiers 0x1d57042c
uint256[] _thresholdAmounts
uint256[] _bpsFees
setInsuranceFeeTiers 0xa2dc3b59
uint256[] _thresholdAmounts
uint256[] _bpsFees
setLPFeeReceiver 0xfc13001a
address _receiver
setOperatorFeeReceiver 0xf63220a5
address _receiver
setProtocolFee 0x787dce3d
uint256 _protocolFee
setProtocolFeeReceiver 0x46877b1a
address _receiver
setTargetChainMinFee 0x41cd0266
uint256 _targetChainId
uint256 _minFee
setVault 0x6817031b
address _vault
upgradeToAndCall 0x4f1ef286
address newImplementation
bytes data

Recent Transactions

No transactions found for this address