Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0x1e1D42781FC170EF9da004Fb735f56F0276d01B8
Balance 0 ETH
Nonce 1
Code Size 19366 bytes
Indexed Transactions 1 (24,427,63724,427,637)
Value (indexed) ↓ 0.000221425 ETH
Gas Used (indexed) 306,902
External Etherscan · Sourcify

Contract Bytecode

19366 bytes
0x6080604052600436106103605760003560e01c806375f1b82c116101c6578063bb0b6a53116100f7578063ca5eb5e111610095578063e1a452181161006f578063e1a4521814610bd6578063f2fde38b14610bec578063fc0c546a14610c0c578063ff7bd03d14610c3f57600080fd5b8063ca5eb5e114610b83578063d045a0dc14610ba3578063d424388514610bb657600080fd5b8063bd815db0116100d1578063bd815db014610b0f578063c272198d14610b22578063c4f6d68f14610b42578063c7c7f5b314610b6257600080fd5b8063bb0b6a5314610aa7578063bc70b35414610ad4578063bcae25a414610af457600080fd5b80638da5cb5b11610164578063ad3b1b471161013e578063ad3b1b4714610a1a578063aeebf20714610a3a578063b731ea0a14610a5a578063b98bd07014610a8757600080fd5b80638da5cb5b146109a7578063963efcaa146109d25780639f68b96414610a0657600080fd5b806381bde774116101a057806381bde7741461091a57806382413eac1461093a5780638456cb5914610976578063857749b01461098b57600080fd5b806375f1b82c1461088e5780637d25a05e146108ae57806380f51c12146108ea57600080fd5b806351c32a88116102a05780635e280f111161023e5780636fc1b31e116102185780636fc1b31e14610804578063703d376814610824578063715018a6146108595780637180c8ca1461086e57600080fd5b80635e280f111461079a57806360b71d4e146107ce5780636db7bcdb146107e457600080fd5b806355b56c0c1161027a57806355b56c0c146106a15780635a0dfe4d1461070d5780635bf9c226146107545780635c975abb1461078257600080fd5b806351c32a88146105bb57806352ae2879146106615780635535d4611461067457600080fd5b80631f5e13341161030d5780633b6f743b116102e75780633b6f743b1461051a5780633f4ba83a146105475780634488b6521461055c57806344b002561461057c57600080fd5b80631f5e13341461048f5780633194c180146104a45780633400288b146104fa57600080fd5b8063134d4f251161033e578063134d4f2514610404578063156a0d0f1461042c57806317442b701461046d57600080fd5b80630d35b41514610365578063111ecdad1461039d57806313137d65146103ef575b600080fd5b34801561037157600080fd5b506103856103803660046136a0565b610c5f565b60405161039493929190613743565b60405180910390f35b3480156103a957600080fd5b506004546103ca9073ffffffffffffffffffffffffffffffffffffffff1681565b60405173ffffffffffffffffffffffffffffffffffffffff9091168152602001610394565b6104026103fd366004613877565b610e0d565b005b34801561041057600080fd5b50610419600281565b60405161ffff9091168152602001610394565b34801561043857600080fd5b50604080517f02e49c2c0000000000000000000000000000000000000000000000000000000081526001602082015201610394565b34801561047957600080fd5b5060408051600181526002602082015201610394565b34801561049b57600080fd5b50610419600181565b3480156104b057600080fd5b506104e06104bf366004613930565b60086020526000908152604090205461ffff81169062010000900460ff1682565b6040805161ffff9093168352901515602083015201610394565b34801561050657600080fd5b5061040261051536600461394b565b610f0c565b34801561052657600080fd5b5061053a610535366004613983565b610f22565b60405161039491906139d5565b34801561055357600080fd5b50610402610f8b565b34801561056857600080fd5b506104026105773660046139fe565b610f9d565b34801561058857600080fd5b506004546105ae9074010000000000000000000000000000000000000000900460ff1681565b6040516103949190613a7f565b3480156105c757600080fd5b506106276105d6366004613930565b6005602052600090815260409020805460018201546002909201546fffffffffffffffffffffffffffffffff82169270010000000000000000000000000000000090920465ffffffffffff16919084565b604080516fffffffffffffffffffffffffffffffff909516855265ffffffffffff9093166020850152918301526060820152608001610394565b34801561066d57600080fd5b50306103ca565b34801561068057600080fd5b5061069461068f366004613a92565b61104d565b6040516103949190613ac5565b3480156106ad57600080fd5b506106276106bc366004613930565b6006602052600090815260409020805460018201546002909201546fffffffffffffffffffffffffffffffff82169270010000000000000000000000000000000090920465ffffffffffff16919084565b34801561071957600080fd5b5061074461072836600461394b565b63ffffffff919091166000908152600160205260409020541490565b6040519015158152602001610394565b34801561076057600080fd5b5061077461076f36600461394b565b6110f2565b604051908152602001610394565b34801561078e57600080fd5b5060095460ff16610744565b3480156107a657600080fd5b506103ca7f0000000000000000000000001a44076050125825900e736c501f859c50fe728c81565b3480156107da57600080fd5b50610774600b5481565b3480156107f057600080fd5b506104026107ff366004613ad8565b611135565b34801561081057600080fd5b5061040261081f366004613b1f565b611227565b34801561083057600080fd5b5061084461083f366004613930565b6112a2565b60408051928352602083019190915201610394565b34801561086557600080fd5b5061040261130b565b34801561087a57600080fd5b50610402610889366004613b3c565b61131d565b34801561089a57600080fd5b506104026108a9366004613b6a565b61142f565b3480156108ba57600080fd5b506108d16108c936600461394b565b600092915050565b60405167ffffffffffffffff9091168152602001610394565b3480156108f657600080fd5b50610744610905366004613b1f565b600a6020526000908152604090205460ff1681565b34801561092657600080fd5b50610402610935366004613b1f565b611443565b34801561094657600080fd5b50610744610955366004613b8b565b73ffffffffffffffffffffffffffffffffffffffff81163014949350505050565b34801561098257600080fd5b506104026115e2565b34801561099757600080fd5b5060405160068152602001610394565b3480156109b357600080fd5b5060005473ffffffffffffffffffffffffffffffffffffffff166103ca565b3480156109de57600080fd5b506107747f000000000000000000000000000000000000000000000000000000e8d4a5100081565b348015610a1257600080fd5b506001610744565b348015610a2657600080fd5b50610402610a35366004613bf2565b611635565b348015610a4657600080fd5b50610402610a55366004613c55565b611732565b348015610a6657600080fd5b506002546103ca9073ffffffffffffffffffffffffffffffffffffffff1681565b348015610a9357600080fd5b50610402610aa2366004613cc1565b6117bb565b348015610ab357600080fd5b50610774610ac2366004613930565b60016020526000908152604090205481565b348015610ae057600080fd5b50610694610aef366004613d03565b6117d5565b348015610b0057600080fd5b506007546104199061ffff1681565b610402610b1d366004613cc1565b611996565b348015610b2e57600080fd5b50610844610b3d366004613930565b611b64565b348015610b4e57600080fd5b50610402610b5d366004613d9d565b611bc3565b610b75610b70366004613dfd565b611c85565b604051610394929190613e7e565b348015610b8f57600080fd5b50610402610b9e366004613b1f565b611cb8565b610402610bb1366004613877565b611d64565b348015610bc257600080fd5b50610402610bd1366004613b1f565b611dac565b348015610be257600080fd5b5061041961271081565b348015610bf857600080fd5b50610402610c07366004613b1f565b611e27565b348015610c1857600080fd5b507f000000000000000000000000dc035d45d973e3ec169d2276ddab16f1e407384f6103ca565b348015610c4b57600080fd5b50610744610c5a366004613ed1565b611e88565b60408051808201909152600080825260208201526060610c92604051806040016040528060008152602001600081525090565b600080610ca5610b3d6020880188613930565b9150506040518060400160405280838152602001828152509450600080610ce7886040013589606001358a6000016020810190610ce29190613930565b611ebe565b915091506040518060400160405280838152602001828152509450808203610d4f576040805160008082526020820190925290610d47565b604080518082019091526000815260606020820152815260200190600190039081610d1f5790505b509550610e02565b60408051600180825281830190925290816020015b604080518082019091526000815260606020820152815260200190600190039081610d6457905050955060405180604001604052808284610da59190613f4b565b81526020016040518060400160405280602081526020017f536b794f46543a2063726f73732d636861696e207472616e736665722066656581525081525086600081518110610df657610df6613f5e565b60200260200101819052505b505050509193909250565b7f0000000000000000000000001a44076050125825900e736c501f859c50fe728c73ffffffffffffffffffffffffffffffffffffffff163314610e83576040517f91ac5e4f0000000000000000000000000000000000000000000000000000000081523360048201526024015b60405180910390fd5b60208701803590610e9d90610e98908a613930565b611f3b565b14610ef457610eaf6020880188613930565b6040517fc26bebcc00000000000000000000000000000000000000000000000000000000815263ffffffff909116600482015260208801356024820152604401610e7a565b610f0387878787878787611f90565b50505050505050565b610f1461212a565b610f1e828261217d565b5050565b60408051808201909152600080825260208201526000610f5260408501356060860135610ce26020880188613930565b915050600080610f6286846121d3565b9092509050610f7f610f776020880188613930565b838388612329565b93505050505b92915050565b610f9361212a565b610f9b612417565b565b610fa561212a565b61271061ffff82161115610fe5576040517fc6cc5d7f00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600780547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00001661ffff83169081179091556040519081527f9283ddc0c2b59320e00b0ae4a992b110df098c38e3b6ea1d92fe7a6d3504be9b906020015b60405180910390a150565b60036020908152600092835260408084209091529082529020805461107190613f8d565b80601f016020809104026020016040519081016040528092919081815260200182805461109d90613f8d565b80156110ea5780601f106110bf576101008083540402835291602001916110ea565b820191906000526020600020905b8154815290600101906020018083116110cd57829003601f168201915b505050505081565b6000806110fe84612494565b905061ffff81161561112a5761271061111b61ffff831685613fda565b6111259190613ff1565b61112d565b60005b949350505050565b61113d61212a565b61271061ffff8316111561117d576040517fc6cc5d7f00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60408051808201825261ffff848116808352841515602080850182815263ffffffff8a16600081815260088452889020965187549251151562010000027fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000090931696169590951717909455845192835292820152918201527f56f0bca120766dba5aeeb89a1cf629c3495dc497c82f426d4e4d58c54b72764c9060600160405180910390a1505050565b61122f61212a565b600480547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff83169081179091556040519081527ff0be4f1e87349231d80c36b33f9e8639658eeaf474014dee15a3e6a4d441419790602001611042565b63ffffffff811660009081526006602052604081206001810154815460028301548493926113019290916fffffffffffffffffffffffffffffffff821691700100000000000000000000000000000000900465ffffffffffff166124e8565b9250925050915091565b61131361212a565b610f9b6000612504565b61132561212a565b73ffffffffffffffffffffffffffffffffffffffff82166000908152600a602052604090205481151560ff9091161515036113a4576040517f96e0002100000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff83166004820152602401610e7a565b73ffffffffffffffffffffffffffffffffffffffff82166000818152600a602090815260409182902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001685151590811790915591519182527fa11b5803b8a35081b8f993e0dee5bc30301a3d83f644e5ab2ff39f972f0a807f91015b60405180910390a25050565b61143761212a565b61144081612579565b50565b61144b61212a565b73ffffffffffffffffffffffffffffffffffffffff8116611498576040517f10c748a600000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600b546040517f70a082310000000000000000000000000000000000000000000000000000000081523060048201526000919073ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000dc035d45d973e3ec169d2276ddab16f1e407384f16906370a0823190602401602060405180830381865afa158015611529573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061154d919061402c565b6115579190613f4b565b905061159a73ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000dc035d45d973e3ec169d2276ddab16f1e407384f1683836125fe565b8173ffffffffffffffffffffffffffffffffffffffff167fb976826e1881dd71fd9bbf78877e973f7e2bb2acc535ff91652561898d1f7af88260405161142391815260200190565b336000908152600a602052604090205460ff1661162d576040517fad834271000000000000000000000000000000000000000000000000000000008152336004820152602401610e7a565b610f9b612684565b61163d61212a565b600b5480821115611684576040517f206ff18d0000000000000000000000000000000000000000000000000000000081526004810183905260248101829052604401610e7a565b81600b60008282546116969190613f4b565b909155506116dd905073ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000dc035d45d973e3ec169d2276ddab16f1e407384f1684846125fe565b8273ffffffffffffffffffffffffffffffffffffffff167fc0819c13be868895eb93e40eaceb96de976442fa1d404e5c55f14bb65a8c489a8360405161172591815260200190565b60405180910390a2505050565b61173a61212a565b611776848480806020026020016040519081016040528093929190818152602001838360200280828437600092018290525092506126df915050565b6117b5828280806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250600192506126df915050565b50505050565b6117c361212a565b610f1e6117d08284614126565b6127ff565b63ffffffff8416600090815260036020908152604080832061ffff8716845290915281208054606092919061180990613f8d565b80601f016020809104026020016040519081016040528092919081815260200182805461183590613f8d565b80156118825780601f1061185757610100808354040283529160200191611882565b820191906000526020600020905b81548152906001019060200180831161186557829003601f168201915b5050505050905080516000036118d25783838080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525092945061112d9350505050565b60008390036118e257905061112d565b600283106119605761192984848080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061290692505050565b80611937846002818861423c565b60405160200161194993929190614266565b60405160208183030381529060405291505061112d565b83836040517f9a6d49cd000000000000000000000000000000000000000000000000000000008152600401610e7a9291906142d7565b60005b81811015611a9f57368383838181106119b4576119b4613f5e565b90506020028101906119c691906142eb565b90506119f96119d86020830183613930565b602083013563ffffffff919091166000908152600160205260409020541490565b611a035750611a97565b3063d045a0dc60c08301358360a0810135611a22610100830183614329565b611a33610100890160e08a01613b1f565b611a416101208a018a614329565b6040518963ffffffff1660e01b8152600401611a6397969594939291906143a4565b6000604051808303818588803b158015611a7c57600080fd5b505af1158015611a90573d6000803e3d6000fd5b5050505050505b600101611999565b503373ffffffffffffffffffffffffffffffffffffffff16638e9e70996040518163ffffffff1660e01b8152600401600060405180830381865afa158015611aeb573d6000803e3d6000fd5b505050506040513d6000823e601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0168201604052611b319190810190614438565b6040517f8351eea7000000000000000000000000000000000000000000000000000000008152600401610e7a9190613ac5565b63ffffffff811660009081526005602052604081206001810154815460028301548493926113019290916fffffffffffffffffffffffffffffffff821691700100000000000000000000000000000000900465ffffffffffff166124e8565b611bcb61212a565b611c288484808060200260200160405190810160405280939291908181526020016000905b82821015611c1c57611c0d606083028601368190038101906144a6565b81526020019060010190611bf0565b5050505050600061294b565b6117b58282808060200260200160405190810160405280939291908181526020016000905b82821015611c7957611c6a606083028601368190038101906144a6565b81526020019060010190611c4d565b5050505050600161294b565b611c8d613640565b6040805180820190915260008082526020820152611cac858585612ae1565b91509150935093915050565b611cc061212a565b6040517fca5eb5e100000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff82811660048301527f0000000000000000000000001a44076050125825900e736c501f859c50fe728c169063ca5eb5e190602401600060405180830381600087803b158015611d4957600080fd5b505af1158015611d5d573d6000803e3d6000fd5b5050505050565b333014611d9d576040517f14d4a4e800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b610f0387878787878787610ef4565b611db461212a565b600280547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff83169081179091556040519081527fd48d879cef83a1c0bdda516f27b13ddb1b3f8bbac1c9e1511bb2a659c242776090602001611042565b611e2f61212a565b73ffffffffffffffffffffffffffffffffffffffff8116611e7f576040517f1e4fbdf700000000000000000000000000000000000000000000000000000000815260006004820152602401610e7a565b61144081612504565b6000602082018035906001908390611ea09086613930565b63ffffffff1681526020810191909152604001600020541492915050565b600080611ec9612bdc565b8491506000611ed884876110f2565b9050611eec611ee78288613f4b565b612c19565b915084821015611f32576040517f71c4efed0000000000000000000000000000000000000000000000000000000081526004810183905260248101869052604401610e7a565b50935093915050565b63ffffffff811660009081526001602052604081205480610f85576040517ff6ff4fb700000000000000000000000000000000000000000000000000000000815263ffffffff84166004820152602401610e7a565b6000611fa2611f9f8787612c50565b90565b90506000611fce82611fbc611fb78a8a612c68565b612c8b565b611fc960208d018d613930565b612cc1565b905060288611156120bb57600061200b611fee60608c0160408d016144fc565b611ffb60208d018d613930565b846120068c8c612d99565b612de4565b6040517f7cb5901200000000000000000000000000000000000000000000000000000000815290915073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000001a44076050125825900e736c501f859c50fe728c1690637cb59012906120879086908d906000908790600401614519565b600060405180830381600087803b1580156120a157600080fd5b505af11580156120b5573d6000803e3d6000fd5b50505050505b73ffffffffffffffffffffffffffffffffffffffff8216887fefed6d3500546b29533b128a29e3a94d70788727f0507505ac12eaf2e578fd9c61210160208d018d613930565b6040805163ffffffff9092168252602082018690520160405180910390a3505050505050505050565b60005473ffffffffffffffffffffffffffffffffffffffff163314610f9b576040517f118cdaa7000000000000000000000000000000000000000000000000000000008152336004820152602401610e7a565b63ffffffff8216600081815260016020908152604091829020849055815192835282018390527f238399d427b947898edb290f5ff0f9109849b1c3ba196a42e35f00c50a54b98b91015b60405180910390a15050565b606080600061223085602001356121e986612e16565b6121f660a0890189614329565b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250612e8a92505050565b9093509050600081612243576001612246565b60025b90506122666122586020880188613930565b82610aef60808a018a614329565b60045490935073ffffffffffffffffffffffffffffffffffffffff16801561231f576040517f043a78eb00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff82169063043a78eb906122dc9088908890600401614562565b602060405180830381865afa1580156122f9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061231d9190614587565b505b5050509250929050565b60408051808201909152600080825260208201527f0000000000000000000000001a44076050125825900e736c501f859c50fe728c73ffffffffffffffffffffffffffffffffffffffff1663ddc28c586040518060a001604052808863ffffffff16815260200161239989611f3b565b8152602001878152602001868152602001851515815250306040518363ffffffff1660e01b81526004016123ce9291906145a4565b6040805180830381865afa1580156123ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061240e9190614678565b95945050505050565b61241f612f1c565b600980547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390a1565b63ffffffff8116600090815260086020908152604080832081518083019092525461ffff8116825262010000900460ff161515918101829052906124de5760075461ffff166124e1565b80515b9392505050565b6000806124f786868686612f58565b9097909650945050505050565b6000805473ffffffffffffffffffffffffffffffffffffffff8381167fffffffffffffffffffffffff0000000000000000000000000000000000000000831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b600480548291907fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff16740100000000000000000000000000000000000000008360018111156125ca576125ca613a19565b02179055507fe762c415a771b152578f7e5806259d5bfe81926f83a1df36714e699753c4b909816040516110429190613a7f565b60405173ffffffffffffffffffffffffffffffffffffffff83811660248301526044820183905261267f91859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050612ff8565b505050565b61268c612bdc565b600980547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861246a3390565b60005b82518110156127cd576000600183600181111561270157612701613a19565b14612743576006600085848151811061271c5761271c613f5e565b602002602001015163ffffffff1663ffffffff16815260200190815260200160002061277c565b6005600085848151811061275957612759613f5e565b602002602001015163ffffffff1663ffffffff1681526020019081526020016000205b600060018281019190915581547fffffffffffffffffffffffffffffffff0000000000000000000000000000000016426fffffffffffffffffffffffffffffffff16179091559190910190506126e2565b507f174e6a591c6b6462824254f0b8b1f619d22ef8f7f30f5e8825263a26211d6e9b82826040516121c7929190614694565b60005b81518110156128d65761283182828151811061282057612820613f5e565b602002602001015160400151612906565b81818151811061284357612843613f5e565b6020026020010151604001516003600084848151811061286557612865613f5e565b60200260200101516000015163ffffffff1663ffffffff168152602001908152602001600020600084848151811061289f5761289f613f5e565b60200260200101516020015161ffff1661ffff16815260200190815260200160002090816128cd9190614739565b50600101612802565b507fbe4864a8e820971c0247f5992e2da559595f7bf076a21cb5928d443d2a13b674816040516110429190614853565b600281015161ffff8116600314610f1e57816040517f9a6d49cd000000000000000000000000000000000000000000000000000000008152600401610e7a9190613ac5565b60005b8251811015612aaf576000600183600181111561296d5761296d613a19565b146129b3576006600085848151811061298857612988613f5e565b60200260200101516000015163ffffffff1663ffffffff1681526020019081526020016000206129f0565b600560008584815181106129c9576129c9613f5e565b60200260200101516000015163ffffffff1663ffffffff1681526020019081526020016000205b9050612a1b848381518110612a0757612a07613f5e565b60200260200101516000015160008561309c565b838281518110612a2d57612a2d613f5e565b6020026020010151604001518160020181905550838281518110612a5357612a53613f5e565b6020908102919091018101510151815465ffffffffffff909116700100000000000000000000000000000000027fffffffffffffffffffff000000000000ffffffffffffffffffffffffffffffff90911617905560010161294e565b507f0444fc2918618a4d3486dbfe63ecffa576c8c5ea05ce7f8f35020bb6084e684482826040516121c79291906148fc565b612ae9613640565b6040805180820190915260008082526020820152600080612b2033604089013560608a0135612b1b60208c018c613930565b6132e9565b91509150600080612b3189846121d3565b9092509050612b5d612b4660208b018b613930565b8383612b57368d90038d018d614969565b8b61337f565b60408051808201909152858152602080820186905282519298509096503391907f85496b760a4b7f8d66384b9df21b381f5d1b1e79f229a47aaf4c232edc2fe59a90612bab908d018d613930565b6040805163ffffffff909216825260208201899052810187905260600160405180910390a350505050935093915050565b60095460ff1615610f9b576040517fd93c066500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60007f000000000000000000000000000000000000000000000000000000e8d4a51000612c468184613ff1565b610f859190613fda565b6000612c5f602082848661423c565b6124e19161499b565b6000612c7860286020848661423c565b612c81916149d7565b60c01c9392505050565b6000610f857f000000000000000000000000000000000000000000000000000000e8d4a5100067ffffffffffffffff8416613fda565b6000612ccb612bdc565b612cd78284600061309c565b73ffffffffffffffffffffffffffffffffffffffff84161580612d4557507f000000000000000000000000dc035d45d973e3ec169d2276ddab16f1e407384f73ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16145b15612d505761dead93505b612d9173ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000dc035d45d973e3ec169d2276ddab16f1e407384f1685856125fe565b509092915050565b6060612da8826028818661423c565b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929695505050505050565b606084848484604051602001612dfd9493929190614a1f565b6040516020818303038152906040529050949350505050565b600080612e437f000000000000000000000000000000000000000000000000000000e8d4a5100084613ff1565b905067ffffffffffffffff811115610f85576040517fe2ce941300000000000000000000000000000000000000000000000000000000815260048101829052602401610e7a565b8051606090151580612eeb578484604051602001612ed792919091825260c01b7fffffffffffffffff00000000000000000000000000000000000000000000000016602082015260280190565b604051602081830303815290604052612f12565b84843385604051602001612f029493929190614a9d565b6040516020818303038152906040525b9150935093915050565b60095460ff16610f9b576040517f8dfc202b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60008080612f786fffffffffffffffffffffffffffffffff871642613f4b565b90508365ffffffffffff168110612f96576000859250925050612fef565b600065ffffffffffff8516612fab8388613fda565b612fb59190613ff1565b9050808811612fc5576000612fcf565b612fcf8189613f4b565b9350838611612fdf576000612fe9565b612fe98487613f4b565b9250505b505b94509492505050565b600080602060008451602086016000885af18061301b576040513d6000823e3d81fd5b50506000513d9150811561303357806001141561304d565b73ffffffffffffffffffffffffffffffffffffffff84163b155b156117b5576040517f5274afe700000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff85166004820152602401610e7a565b600060018260018111156130b2576130b2613a19565b146130d15763ffffffff841660009081526006602052604090206130e7565b63ffffffff841660009081526005602052604090205b60018101548154600283015492935060009283926131369290916fffffffffffffffffffffffffffffffff821691700100000000000000000000000000000000900465ffffffffffff16612f58565b9150915080851115613174576040517fa74c1c5f00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b61317e8583614af6565b600184015582547fffffffffffffffffffffffffffffffff0000000000000000000000000000000016426fffffffffffffffffffffffffffffffff16178355600060045474010000000000000000000000000000000000000000900460ff1660018111156131ee576131ee613a19565b036132e1576000600185600181111561320957613209613a19565b146132285763ffffffff8716600090815260056020526040902061323e565b63ffffffff871660009081526006602052604090205b60018101548154600283015492935060009261328b92916fffffffffffffffffffffffffffffffff81169190700100000000000000000000000000000000900465ffffffffffff16612f58565b50905086811161329c5760006132a0565b8681035b60018301555080547fffffffffffffffffffffffffffffffff0000000000000000000000000000000016426fffffffffffffffffffffffffffffffff161790555b505050505050565b6000806132f7858585611ebe565b90925090506133088382600161309c565b61334a73ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000dc035d45d973e3ec169d2276ddab16f1e407384f16873085613497565b60006133568284613f4b565b90508015612fed5780600b60008282546133709190614af6565b90915550505094509492505050565b613387613640565b600061339684600001516134dd565b6020850151909150156133b0576133b0846020015161351e565b7f0000000000000000000000001a44076050125825900e736c501f859c50fe728c73ffffffffffffffffffffffffffffffffffffffff16632637a450826040518060a001604052808b63ffffffff16815260200161340d8c611f3b565b81526020018a815260200189815260200160008960200151111515815250866040518463ffffffff1660e01b81526004016134499291906145a4565b60806040518083038185885af1158015613467573d6000803e3d6000fd5b50505050506040513d601f19601f8201168201806040525081019061348c9190614b09565b979650505050505050565b60405173ffffffffffffffffffffffffffffffffffffffff84811660248301528381166044830152606482018390526117b59186918216906323b872dd90608401612638565b600081341461351a576040517f9f704120000000000000000000000000000000000000000000000000000000008152346004820152602401610e7a565b5090565b60007f0000000000000000000000001a44076050125825900e736c501f859c50fe728c73ffffffffffffffffffffffffffffffffffffffff1663e4fe1d946040518163ffffffff1660e01b8152600401602060405180830381865afa15801561358b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135af9190614b53565b905073ffffffffffffffffffffffffffffffffffffffff81166135fe576040517f5373352a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b610f1e73ffffffffffffffffffffffffffffffffffffffff8216337f0000000000000000000000001a44076050125825900e736c501f859c50fe728c85613497565b604051806060016040528060008019168152602001600067ffffffffffffffff168152602001613683604051806040016040528060008152602001600081525090565b905290565b600060e0828403121561369a57600080fd5b50919050565b6000602082840312156136b257600080fd5b813567ffffffffffffffff8111156136c957600080fd5b61112d84828501613688565b60005b838110156136f05781810151838201526020016136d8565b50506000910152565b600081518084526137118160208601602086016136d5565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b8351815260208085015190820152600060a08201604060a0604085015281865180845260c08601915060c08160051b8701019350602080890160005b838110156137dc578887037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff400185528151805188528301518388018790526137c9878901826136f9565b975050938201939082019060010161377f565b5050875160608801525050506020850151608085015250905061112d565b60006060828403121561369a57600080fd5b60008083601f84011261381e57600080fd5b50813567ffffffffffffffff81111561383657600080fd5b60208301915083602082850101111561384e57600080fd5b9250929050565b73ffffffffffffffffffffffffffffffffffffffff8116811461144057600080fd5b600080600080600080600060e0888a03121561389257600080fd5b61389c89896137fa565b965060608801359550608088013567ffffffffffffffff808211156138c057600080fd5b6138cc8b838c0161380c565b909750955060a08a013591506138e182613855565b90935060c089013590808211156138f757600080fd5b506139048a828b0161380c565b989b979a50959850939692959293505050565b803563ffffffff8116811461392b57600080fd5b919050565b60006020828403121561394257600080fd5b6124e182613917565b6000806040838503121561395e57600080fd5b61396783613917565b946020939093013593505050565b801515811461144057600080fd5b6000806040838503121561399657600080fd5b823567ffffffffffffffff8111156139ad57600080fd5b6139b985828601613688565b92505060208301356139ca81613975565b809150509250929050565b815181526020808301519082015260408101610f85565b803561ffff8116811461392b57600080fd5b600060208284031215613a1057600080fd5b6124e1826139ec565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b60028110611440577f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b60208101613a8c83613a48565b91905290565b60008060408385031215613aa557600080fd5b613aae83613917565b9150613abc602084016139ec565b90509250929050565b6020815260006124e160208301846136f9565b600080600060608486031215613aed57600080fd5b613af684613917565b9250613b04602085016139ec565b91506040840135613b1481613975565b809150509250925092565b600060208284031215613b3157600080fd5b81356124e181613855565b60008060408385031215613b4f57600080fd5b8235613b5a81613855565b915060208301356139ca81613975565b600060208284031215613b7c57600080fd5b8135600281106124e157600080fd5b60008060008060a08587031215613ba157600080fd5b613bab86866137fa565b9350606085013567ffffffffffffffff811115613bc757600080fd5b613bd38782880161380c565b9094509250506080850135613be781613855565b939692955090935050565b60008060408385031215613c0557600080fd5b823561396781613855565b60008083601f840112613c2257600080fd5b50813567ffffffffffffffff811115613c3a57600080fd5b6020830191508360208260051b850101111561384e57600080fd5b60008060008060408587031215613c6b57600080fd5b843567ffffffffffffffff80821115613c8357600080fd5b613c8f88838901613c10565b90965094506020870135915080821115613ca857600080fd5b50613cb587828801613c10565b95989497509550505050565b60008060208385031215613cd457600080fd5b823567ffffffffffffffff811115613ceb57600080fd5b613cf785828601613c10565b90969095509350505050565b60008060008060608587031215613d1957600080fd5b613d2285613917565b9350613d30602086016139ec565b9250604085013567ffffffffffffffff811115613d4c57600080fd5b613cb58782880161380c565b60008083601f840112613d6a57600080fd5b50813567ffffffffffffffff811115613d8257600080fd5b60208301915083602060608302850101111561384e57600080fd5b60008060008060408587031215613db357600080fd5b843567ffffffffffffffff80821115613dcb57600080fd5b613dd788838901613d58565b90965094506020870135915080821115613df057600080fd5b50613cb587828801613d58565b60008060008385036080811215613e1357600080fd5b843567ffffffffffffffff811115613e2a57600080fd5b613e3687828801613688565b94505060407fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe082011215613e6957600080fd5b506020840191506060840135613b1481613855565b600060c0820190508351825267ffffffffffffffff60208501511660208301526040840151613eba604084018280518252602090810151910152565b5082516080830152602083015160a08301526124e1565b600060608284031215613ee357600080fd5b6124e183836137fa565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b81810381811115610f8557610f85613f1c565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600181811c90821680613fa157607f821691505b60208210810361369a577f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b8082028115828204841417610f8557610f85613f1c565b600082614027577f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b500490565b60006020828403121561403e57600080fd5b5051919050565b6040516060810167ffffffffffffffff8111828210171561406857614068613eed565b60405290565b6040805190810167ffffffffffffffff8111828210171561406857614068613eed565b604051601f82017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016810167ffffffffffffffff811182821017156140d8576140d8613eed565b604052919050565b600067ffffffffffffffff8211156140fa576140fa613eed565b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01660200190565b600067ffffffffffffffff8084111561414157614141613eed565b8360051b6020614152818301614091565b86815291850191818101903684111561416a57600080fd5b865b84811015614230578035868111156141845760008081fd5b880160603682900312156141985760008081fd5b6141a0614045565b6141a982613917565b81526141b68683016139ec565b86820152604080830135898111156141ce5760008081fd5b929092019136601f8401126141e35760008081fd5b82356141f66141f1826140e0565b614091565b818152368983870101111561420b5760008081fd5b818986018a83013760009181018901919091529082015284525091830191830161416c565b50979650505050505050565b6000808585111561424c57600080fd5b8386111561425957600080fd5b5050820193919092039150565b600084516142788184602089016136d5565b8201838582376000930192835250909392505050565b8183528181602085013750600060208284010152600060207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f840116840101905092915050565b60208152600061112d60208301848661428e565b600082357ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec183360301811261431f57600080fd5b9190910192915050565b60008083357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe184360301811261435e57600080fd5b83018035915067ffffffffffffffff82111561437957600080fd5b60200191503681900382131561384e57600080fd5b67ffffffffffffffff8116811461144057600080fd5b63ffffffff6143b289613917565b16815260208801356020820152600060408901356143cf8161438e565b67ffffffffffffffff811660408401525087606083015260e060808301526143fb60e08301878961428e565b73ffffffffffffffffffffffffffffffffffffffff861660a084015282810360c084015261442a81858761428e565b9a9950505050505050505050565b60006020828403121561444a57600080fd5b815167ffffffffffffffff81111561446157600080fd5b8201601f8101841361447257600080fd5b80516144806141f1826140e0565b81815285602083850101111561449557600080fd5b61240e8260208301602086016136d5565b6000606082840312156144b857600080fd5b6144c0614045565b6144c983613917565b8152602083013565ffffffffffff811681146144e457600080fd5b60208201526040928301359281019290925250919050565b60006020828403121561450e57600080fd5b81356124e18161438e565b73ffffffffffffffffffffffffffffffffffffffff8516815283602082015261ffff8316604082015260806060820152600061455860808301846136f9565b9695505050505050565b60408152600061457560408301856136f9565b828103602084015261240e81856136f9565b60006020828403121561459957600080fd5b81516124e181613975565b6040815263ffffffff8351166040820152602083015160608201526000604084015160a060808401526145da60e08401826136f9565b905060608501517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc08483030160a085015261461582826136f9565b60809690960151151560c085015250505073ffffffffffffffffffffffffffffffffffffffff9190911660209091015290565b60006040828403121561465a57600080fd5b61466261406e565b9050815181526020820151602082015292915050565b60006040828403121561468a57600080fd5b6124e18383614648565b604080825283519082018190526000906020906060840190828701845b828110156146d357815163ffffffff16845292840192908401906001016146b1565b50505080925050506146e483613a48565b8260208301529392505050565b601f82111561267f576000816000526020600020601f850160051c8101602086101561471a5750805b601f850160051c820191505b818110156132e157828155600101614726565b815167ffffffffffffffff81111561475357614753613eed565b614767816147618454613f8d565b846146f1565b602080601f8311600181146147ba57600084156147845750858301515b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff600386901b1c1916600185901b1785556132e1565b6000858152602081207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08616915b82811015614807578886015182559484019460019091019084016147e8565b508582101561484357878501517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff600388901b60f8161c191681555b5050505050600190811b01905550565b600060208083018184528085518083526040925060408601915060408160051b87010184880160005b838110156148ee578883037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc00185528151805163ffffffff1684528781015161ffff168885015286015160608785018190526148da818601836136f9565b96890196945050509086019060010161487c565b509098975050505050505050565b6040808252835182820181905260009190606090818501906020808901865b83811015614956578151805163ffffffff1686528381015165ffffffffffff168487015287015187860152938501939082019060010161491b565b505050508093505050506146e483613a48565b60006040828403121561497b57600080fd5b61498361406e565b82358152602083013560208201528091505092915050565b80356020831015610f85577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff602084900360031b1b1692915050565b7fffffffffffffffff0000000000000000000000000000000000000000000000008135818116916008851015614a175780818660080360031b1b83161692505b505092915050565b7fffffffffffffffff0000000000000000000000000000000000000000000000008560c01b1681527fffffffff000000000000000000000000000000000000000000000000000000008460e01b16600882015282600c82015260008251614a8d81602c8501602087016136d5565b91909101602c0195945050505050565b8481527fffffffffffffffff0000000000000000000000000000000000000000000000008460c01b16602082015282602882015260008251614ae68160488501602087016136d5565b9190910160480195945050505050565b80820180821115610f8557610f85613f1c565b600060808284031215614b1b57600080fd5b614b23614045565b825181526020830151614b358161438e565b6020820152614b478460408501614648565b60408201529392505050565b600060208284031215614b6557600080fd5b81516124e18161385556fea26469706673582212202a3baca7feb1fc0f1d1de25c9a1cd01fa05f9d67e125378ea1329d70fb4c2e5a64736f6c63430008160033

Verified Source Code Full Match

Compiler: v0.8.22+commit.4fc1097e EVM: paris Optimization: Yes (20000 runs)
ILayerZeroEndpointV2.sol 89 lines
// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

import { IMessageLibManager } from "./IMessageLibManager.sol";
import { IMessagingComposer } from "./IMessagingComposer.sol";
import { IMessagingChannel } from "./IMessagingChannel.sol";
import { IMessagingContext } from "./IMessagingContext.sol";

struct MessagingParams {
    uint32 dstEid;
    bytes32 receiver;
    bytes message;
    bytes options;
    bool payInLzToken;
}

struct MessagingReceipt {
    bytes32 guid;
    uint64 nonce;
    MessagingFee fee;
}

struct MessagingFee {
    uint256 nativeFee;
    uint256 lzTokenFee;
}

struct Origin {
    uint32 srcEid;
    bytes32 sender;
    uint64 nonce;
}

interface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext {
    event PacketSent(bytes encodedPayload, bytes options, address sendLibrary);

    event PacketVerified(Origin origin, address receiver, bytes32 payloadHash);

    event PacketDelivered(Origin origin, address receiver);

    event LzReceiveAlert(
        address indexed receiver,
        address indexed executor,
        Origin origin,
        bytes32 guid,
        uint256 gas,
        uint256 value,
        bytes message,
        bytes extraData,
        bytes reason
    );

    event LzTokenSet(address token);

    event DelegateSet(address sender, address delegate);

    function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory);

    function send(
        MessagingParams calldata _params,
        address _refundAddress
    ) external payable returns (MessagingReceipt memory);

    function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external;

    function verifiable(Origin calldata _origin, address _receiver) external view returns (bool);

    function initializable(Origin calldata _origin, address _receiver) external view returns (bool);

    function lzReceive(
        Origin calldata _origin,
        address _receiver,
        bytes32 _guid,
        bytes calldata _message,
        bytes calldata _extraData
    ) external payable;

    // oapp can burn messages partially by calling this function with its own business logic if messages are verified in order
    function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external;

    function setLzToken(address _lzToken) external;

    function lzToken() external view returns (address);

    function nativeToken() external view returns (address);

    function setDelegate(address _delegate) external;
}
ILayerZeroReceiver.sol 19 lines
// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

import { Origin } from "./ILayerZeroEndpointV2.sol";

interface ILayerZeroReceiver {
    function allowInitializePath(Origin calldata _origin) external view returns (bool);

    function nextNonce(uint32 _eid, bytes32 _sender) external view returns (uint64);

    function lzReceive(
        Origin calldata _origin,
        bytes32 _guid,
        bytes calldata _message,
        address _executor,
        bytes calldata _extraData
    ) external payable;
}
IMessageLib.sol 26 lines
// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

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

import { SetConfigParam } from "./IMessageLibManager.sol";

enum MessageLibType {
    Send,
    Receive,
    SendAndReceive
}

interface IMessageLib is IERC165 {
    function setConfig(address _oapp, SetConfigParam[] calldata _config) external;

    function getConfig(uint32 _eid, address _oapp, uint32 _configType) external view returns (bytes memory config);

    function isSupportedEid(uint32 _eid) external view returns (bool);

    // message libs of same major version are compatible
    function version() external view returns (uint64 major, uint8 minor, uint8 endpointVersion);

    function messageLibType() external view returns (MessageLibType);
}
IMessageLibManager.sol 70 lines
// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

struct SetConfigParam {
    uint32 eid;
    uint32 configType;
    bytes config;
}

interface IMessageLibManager {
    struct Timeout {
        address lib;
        uint256 expiry;
    }

    event LibraryRegistered(address newLib);
    event DefaultSendLibrarySet(uint32 eid, address newLib);
    event DefaultReceiveLibrarySet(uint32 eid, address newLib);
    event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry);
    event SendLibrarySet(address sender, uint32 eid, address newLib);
    event ReceiveLibrarySet(address receiver, uint32 eid, address newLib);
    event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout);

    function registerLibrary(address _lib) external;

    function isRegisteredLibrary(address _lib) external view returns (bool);

    function getRegisteredLibraries() external view returns (address[] memory);

    function setDefaultSendLibrary(uint32 _eid, address _newLib) external;

    function defaultSendLibrary(uint32 _eid) external view returns (address);

    function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _gracePeriod) external;

    function defaultReceiveLibrary(uint32 _eid) external view returns (address);

    function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external;

    function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry);

    function isSupportedEid(uint32 _eid) external view returns (bool);

    function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool);

    /// ------------------- OApp interfaces -------------------
    function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external;

    function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib);

    function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool);

    function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external;

    function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault);

    function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _expiry) external;

    function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry);

    function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external;

    function getConfig(
        address _oapp,
        address _lib,
        uint32 _eid,
        uint32 _configType
    ) external view returns (bytes memory config);
}
IMessagingChannel.sol 34 lines
// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

interface IMessagingChannel {
    event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce);
    event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
    event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);

    function eid() external view returns (uint32);

    // this is an emergency function if a message cannot be verified for some reasons
    // required to provide _nextNonce to avoid race condition
    function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external;

    function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;

    function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;

    function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32);

    function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);

    function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64);

    function inboundPayloadHash(
        address _receiver,
        uint32 _srcEid,
        bytes32 _sender,
        uint64 _nonce
    ) external view returns (bytes32);

    function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
}
IMessagingComposer.sol 38 lines
// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

interface IMessagingComposer {
    event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message);
    event ComposeDelivered(address from, address to, bytes32 guid, uint16 index);
    event LzComposeAlert(
        address indexed from,
        address indexed to,
        address indexed executor,
        bytes32 guid,
        uint16 index,
        uint256 gas,
        uint256 value,
        bytes message,
        bytes extraData,
        bytes reason
    );

    function composeQueue(
        address _from,
        address _to,
        bytes32 _guid,
        uint16 _index
    ) external view returns (bytes32 messageHash);

    function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external;

    function lzCompose(
        address _from,
        address _to,
        bytes32 _guid,
        uint16 _index,
        bytes calldata _message,
        bytes calldata _extraData
    ) external payable;
}
IMessagingContext.sol 9 lines
// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

interface IMessagingContext {
    function isSendingMessage() external view returns (bool);

    function getSendContext() external view returns (uint32 dstEid, address sender);
}
ISendLib.sol 36 lines
// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

import { MessagingFee } from "./ILayerZeroEndpointV2.sol";
import { IMessageLib } from "./IMessageLib.sol";

struct Packet {
    uint64 nonce;
    uint32 srcEid;
    address sender;
    uint32 dstEid;
    bytes32 receiver;
    bytes32 guid;
    bytes message;
}

interface ISendLib is IMessageLib {
    function send(
        Packet calldata _packet,
        bytes calldata _options,
        bool _payInLzToken
    ) external returns (MessagingFee memory, bytes memory encodedPacket);

    function quote(
        Packet calldata _packet,
        bytes calldata _options,
        bool _payInLzToken
    ) external view returns (MessagingFee memory);

    function setTreasury(address _treasury) external;

    function withdrawFee(address _to, uint256 _amount) external;

    function withdrawLzTokenFee(address _lzToken, address _to, uint256 _amount) external;
}
AddressCast.sol 41 lines
// SPDX-License-Identifier: LZBL-1.2

pragma solidity ^0.8.20;

library AddressCast {
    error AddressCast_InvalidSizeForAddress();
    error AddressCast_InvalidAddress();

    function toBytes32(bytes calldata _addressBytes) internal pure returns (bytes32 result) {
        if (_addressBytes.length > 32) revert AddressCast_InvalidAddress();
        result = bytes32(_addressBytes);
        unchecked {
            uint256 offset = 32 - _addressBytes.length;
            result = result >> (offset * 8);
        }
    }

    function toBytes32(address _address) internal pure returns (bytes32 result) {
        result = bytes32(uint256(uint160(_address)));
    }

    function toBytes(bytes32 _addressBytes32, uint256 _size) internal pure returns (bytes memory result) {
        if (_size == 0 || _size > 32) revert AddressCast_InvalidSizeForAddress();
        result = new bytes(_size);
        unchecked {
            uint256 offset = 256 - _size * 8;
            assembly {
                mstore(add(result, 32), shl(offset, _addressBytes32))
            }
        }
    }

    function toAddress(bytes32 _addressBytes32) internal pure returns (address result) {
        result = address(uint160(uint256(_addressBytes32)));
    }

    function toAddress(bytes calldata _addressBytes) internal pure returns (address result) {
        if (_addressBytes.length != 20) revert AddressCast_InvalidAddress();
        result = address(bytes20(_addressBytes));
    }
}
PacketV1Codec.sol 108 lines
// SPDX-License-Identifier: LZBL-1.2

pragma solidity ^0.8.20;

import { Packet } from "../../interfaces/ISendLib.sol";
import { AddressCast } from "../../libs/AddressCast.sol";

library PacketV1Codec {
    using AddressCast for address;
    using AddressCast for bytes32;

    uint8 internal constant PACKET_VERSION = 1;

    // header (version + nonce + path)
    // version
    uint256 private constant PACKET_VERSION_OFFSET = 0;
    //    nonce
    uint256 private constant NONCE_OFFSET = 1;
    //    path
    uint256 private constant SRC_EID_OFFSET = 9;
    uint256 private constant SENDER_OFFSET = 13;
    uint256 private constant DST_EID_OFFSET = 45;
    uint256 private constant RECEIVER_OFFSET = 49;
    // payload (guid + message)
    uint256 private constant GUID_OFFSET = 81; // keccak256(nonce + path)
    uint256 private constant MESSAGE_OFFSET = 113;

    function encode(Packet memory _packet) internal pure returns (bytes memory encodedPacket) {
        encodedPacket = abi.encodePacked(
            PACKET_VERSION,
            _packet.nonce,
            _packet.srcEid,
            _packet.sender.toBytes32(),
            _packet.dstEid,
            _packet.receiver,
            _packet.guid,
            _packet.message
        );
    }

    function encodePacketHeader(Packet memory _packet) internal pure returns (bytes memory) {
        return
            abi.encodePacked(
                PACKET_VERSION,
                _packet.nonce,
                _packet.srcEid,
                _packet.sender.toBytes32(),
                _packet.dstEid,
                _packet.receiver
            );
    }

    function encodePayload(Packet memory _packet) internal pure returns (bytes memory) {
        return abi.encodePacked(_packet.guid, _packet.message);
    }

    function header(bytes calldata _packet) internal pure returns (bytes calldata) {
        return _packet[0:GUID_OFFSET];
    }

    function version(bytes calldata _packet) internal pure returns (uint8) {
        return uint8(bytes1(_packet[PACKET_VERSION_OFFSET:NONCE_OFFSET]));
    }

    function nonce(bytes calldata _packet) internal pure returns (uint64) {
        return uint64(bytes8(_packet[NONCE_OFFSET:SRC_EID_OFFSET]));
    }

    function srcEid(bytes calldata _packet) internal pure returns (uint32) {
        return uint32(bytes4(_packet[SRC_EID_OFFSET:SENDER_OFFSET]));
    }

    function sender(bytes calldata _packet) internal pure returns (bytes32) {
        return bytes32(_packet[SENDER_OFFSET:DST_EID_OFFSET]);
    }

    function senderAddressB20(bytes calldata _packet) internal pure returns (address) {
        return sender(_packet).toAddress();
    }

    function dstEid(bytes calldata _packet) internal pure returns (uint32) {
        return uint32(bytes4(_packet[DST_EID_OFFSET:RECEIVER_OFFSET]));
    }

    function receiver(bytes calldata _packet) internal pure returns (bytes32) {
        return bytes32(_packet[RECEIVER_OFFSET:GUID_OFFSET]);
    }

    function receiverB20(bytes calldata _packet) internal pure returns (address) {
        return receiver(_packet).toAddress();
    }

    function guid(bytes calldata _packet) internal pure returns (bytes32) {
        return bytes32(_packet[GUID_OFFSET:MESSAGE_OFFSET]);
    }

    function message(bytes calldata _packet) internal pure returns (bytes calldata) {
        return bytes(_packet[MESSAGE_OFFSET:]);
    }

    function payload(bytes calldata _packet) internal pure returns (bytes calldata) {
        return bytes(_packet[GUID_OFFSET:]);
    }

    function payloadHash(bytes calldata _packet) internal pure returns (bytes32) {
        return keccak256(payload(_packet));
    }
}
IOAppCore.sol 52 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import { ILayerZeroEndpointV2 } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";

/**
 * @title IOAppCore
 */
interface IOAppCore {
    // Custom error messages
    error OnlyPeer(uint32 eid, bytes32 sender);
    error NoPeer(uint32 eid);
    error InvalidEndpointCall();
    error InvalidDelegate();

    // Event emitted when a peer (OApp) is set for a corresponding endpoint
    event PeerSet(uint32 eid, bytes32 peer);

    /**
     * @notice Retrieves the OApp version information.
     * @return senderVersion The version of the OAppSender.sol contract.
     * @return receiverVersion The version of the OAppReceiver.sol contract.
     */
    function oAppVersion() external view returns (uint64 senderVersion, uint64 receiverVersion);

    /**
     * @notice Retrieves the LayerZero endpoint associated with the OApp.
     * @return iEndpoint The LayerZero endpoint as an interface.
     */
    function endpoint() external view returns (ILayerZeroEndpointV2 iEndpoint);

    /**
     * @notice Retrieves the peer (OApp) associated with a corresponding endpoint.
     * @param _eid The endpoint ID.
     * @return peer The peer address (OApp instance) associated with the corresponding endpoint.
     */
    function peers(uint32 _eid) external view returns (bytes32 peer);

    /**
     * @notice Sets the peer address (OApp instance) for a corresponding endpoint.
     * @param _eid The endpoint ID.
     * @param _peer The address of the peer to be associated with the corresponding endpoint.
     */
    function setPeer(uint32 _eid, bytes32 _peer) external;

    /**
     * @notice Sets the delegate address for the OApp Core.
     * @param _delegate The address of the delegate to be set.
     */
    function setDelegate(address _delegate) external;
}
IOAppMsgInspector.sol 22 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @title IOAppMsgInspector
 * @dev Interface for the OApp Message Inspector, allowing examination of message and options contents.
 */
interface IOAppMsgInspector {
    // Custom error message for inspection failure
    error InspectionFailed(bytes message, bytes options);

    /**
     * @notice Allows the inspector to examine LayerZero message contents and optionally throw a revert if invalid.
     * @param _message The message payload to be inspected.
     * @param _options Additional options or parameters for inspection.
     * @return valid A boolean indicating whether the inspection passed (true) or failed (false).
     *
     * @dev Optionally done as a revert, OR use the boolean provided to handle the failure.
     */
    function inspect(bytes calldata _message, bytes calldata _options) external view returns (bool valid);
}
IOAppOptionsType3.sol 43 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @dev Struct representing enforced option parameters.
 */
struct EnforcedOptionParam {
    uint32 eid; // Endpoint ID
    uint16 msgType; // Message Type
    bytes options; // Additional options
}

/**
 * @title IOAppOptionsType3
 * @dev Interface for the OApp with Type 3 Options, allowing the setting and combining of enforced options.
 */
interface IOAppOptionsType3 {
    // Custom error message for invalid options
    error InvalidOptions(bytes options);

    // Event emitted when enforced options are set
    event EnforcedOptionSet(EnforcedOptionParam[] _enforcedOptions);

    /**
     * @notice Sets enforced options for specific endpoint and message type combinations.
     * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
     */
    function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) external;

    /**
     * @notice Combines options for a given endpoint and message type.
     * @param _eid The endpoint ID.
     * @param _msgType The OApp message type.
     * @param _extraOptions Additional options passed by the caller.
     * @return options The combination of caller specified options AND enforced options.
     */
    function combineOptions(
        uint32 _eid,
        uint16 _msgType,
        bytes calldata _extraOptions
    ) external view returns (bytes memory options);
}
IOAppReceiver.sol 25 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import { ILayerZeroReceiver, Origin } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol";

interface IOAppReceiver is ILayerZeroReceiver {
    /**
     * @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.
     * @param _origin The origin information containing the source endpoint and sender address.
     *  - srcEid: The source chain endpoint ID.
     *  - sender: The sender address on the src chain.
     *  - nonce: The nonce of the message.
     * @param _message The lzReceive payload.
     * @param _sender The sender address.
     * @return isSender Is a valid sender.
     *
     * @dev Applications can optionally choose to implement a separate composeMsg sender that is NOT the bridging layer.
     * @dev The default sender IS the OAppReceiver implementer.
     */
    function isComposeMsgSender(
        Origin calldata _origin,
        bytes calldata _message,
        address _sender
    ) external view returns (bool isSender);
}
OAppOptionsType3.sol 98 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IOAppOptionsType3, EnforcedOptionParam } from "../interfaces/IOAppOptionsType3.sol";

/**
 * @title OAppOptionsType3
 * @dev Abstract contract implementing the IOAppOptionsType3 interface with type 3 options.
 */
abstract contract OAppOptionsType3 is IOAppOptionsType3, Ownable {
    uint16 internal constant OPTION_TYPE_3 = 3;

    // @dev The "msgType" should be defined in the child contract.
    mapping(uint32 eid => mapping(uint16 msgType => bytes enforcedOption)) public enforcedOptions;

    /**
     * @dev Sets the enforced options for specific endpoint and message type combinations.
     * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
     *
     * @dev Only the owner/admin of the OApp can call this function.
     * @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc.
     * @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType.
     * eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay
     * if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose().
     */
    function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) public virtual onlyOwner {
        _setEnforcedOptions(_enforcedOptions);
    }

    /**
     * @dev Sets the enforced options for specific endpoint and message type combinations.
     * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
     *
     * @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc.
     * @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType.
     * eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay
     * if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose().
     */
    function _setEnforcedOptions(EnforcedOptionParam[] memory _enforcedOptions) internal virtual {
        for (uint256 i = 0; i < _enforcedOptions.length; i++) {
            // @dev Enforced options are only available for optionType 3, as type 1 and 2 dont support combining.
            _assertOptionsType3(_enforcedOptions[i].options);
            enforcedOptions[_enforcedOptions[i].eid][_enforcedOptions[i].msgType] = _enforcedOptions[i].options;
        }

        emit EnforcedOptionSet(_enforcedOptions);
    }

    /**
     * @notice Combines options for a given endpoint and message type.
     * @param _eid The endpoint ID.
     * @param _msgType The OAPP message type.
     * @param _extraOptions Additional options passed by the caller.
     * @return options The combination of caller specified options AND enforced options.
     *
     * @dev If there is an enforced lzReceive option:
     * - {gasLimit: 200k, msg.value: 1 ether} AND a caller supplies a lzReceive option: {gasLimit: 100k, msg.value: 0.5 ether}
     * - The resulting options will be {gasLimit: 300k, msg.value: 1.5 ether} when the message is executed on the remote lzReceive() function.
     * @dev This presence of duplicated options is handled off-chain in the verifier/executor.
     */
    function combineOptions(
        uint32 _eid,
        uint16 _msgType,
        bytes calldata _extraOptions
    ) public view virtual returns (bytes memory) {
        bytes memory enforced = enforcedOptions[_eid][_msgType];

        // No enforced options, pass whatever the caller supplied, even if it's empty or legacy type 1/2 options.
        if (enforced.length == 0) return _extraOptions;

        // No caller options, return enforced
        if (_extraOptions.length == 0) return enforced;

        // @dev If caller provided _extraOptions, must be type 3 as its the ONLY type that can be combined.
        if (_extraOptions.length >= 2) {
            _assertOptionsType3(_extraOptions);
            // @dev Remove the first 2 bytes containing the type from the _extraOptions and combine with enforced.
            return bytes.concat(enforced, _extraOptions[2:]);
        }

        // No valid set of options was found.
        revert InvalidOptions(_extraOptions);
    }

    /**
     * @dev Internal function to assert that options are of type 3.
     * @param _options The options to be checked.
     */
    function _assertOptionsType3(bytes memory _options) internal pure virtual {
        uint16 optionsType;
        assembly {
            optionsType := mload(add(_options, 2))
        }
        if (optionsType != OPTION_TYPE_3) revert InvalidOptions(_options);
    }
}
OApp.sol 39 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

// @dev Import the 'MessagingFee' and 'MessagingReceipt' so it's exposed to OApp implementers
// solhint-disable-next-line no-unused-import
import { OAppSender, MessagingFee, MessagingReceipt } from "./OAppSender.sol";
// @dev Import the 'Origin' so it's exposed to OApp implementers
// solhint-disable-next-line no-unused-import
import { OAppReceiver, Origin } from "./OAppReceiver.sol";
import { OAppCore } from "./OAppCore.sol";

/**
 * @title OApp
 * @dev Abstract contract serving as the base for OApp implementation, combining OAppSender and OAppReceiver functionality.
 */
abstract contract OApp is OAppSender, OAppReceiver {
    /**
     * @dev Constructor to initialize the OApp with the provided endpoint and owner.
     * @param _endpoint The address of the LOCAL LayerZero endpoint.
     * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
     */
    constructor(address _endpoint, address _delegate) OAppCore(_endpoint, _delegate) {}

    /**
     * @notice Retrieves the OApp version information.
     * @return senderVersion The version of the OAppSender.sol implementation.
     * @return receiverVersion The version of the OAppReceiver.sol implementation.
     */
    function oAppVersion()
        public
        pure
        virtual
        override(OAppSender, OAppReceiver)
        returns (uint64 senderVersion, uint64 receiverVersion)
    {
        return (SENDER_VERSION, RECEIVER_VERSION);
    }
}
OAppCore.sol 83 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IOAppCore, ILayerZeroEndpointV2 } from "./interfaces/IOAppCore.sol";

/**
 * @title OAppCore
 * @dev Abstract contract implementing the IOAppCore interface with basic OApp configurations.
 */
abstract contract OAppCore is IOAppCore, Ownable {
    // The LayerZero endpoint associated with the given OApp
    ILayerZeroEndpointV2 public immutable endpoint;

    // Mapping to store peers associated with corresponding endpoints
    mapping(uint32 eid => bytes32 peer) public peers;

    /**
     * @dev Constructor to initialize the OAppCore with the provided endpoint and delegate.
     * @param _endpoint The address of the LOCAL Layer Zero endpoint.
     * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
     *
     * @dev The delegate typically should be set as the owner of the contract.
     */
    constructor(address _endpoint, address _delegate) {
        endpoint = ILayerZeroEndpointV2(_endpoint);

        if (_delegate == address(0)) revert InvalidDelegate();
        endpoint.setDelegate(_delegate);
    }

    /**
     * @notice Sets the peer address (OApp instance) for a corresponding endpoint.
     * @param _eid The endpoint ID.
     * @param _peer The address of the peer to be associated with the corresponding endpoint.
     *
     * @dev Only the owner/admin of the OApp can call this function.
     * @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.
     * @dev Set this to bytes32(0) to remove the peer address.
     * @dev Peer is a bytes32 to accommodate non-evm chains.
     */
    function setPeer(uint32 _eid, bytes32 _peer) public virtual onlyOwner {
        _setPeer(_eid, _peer);
    }

    /**
     * @notice Sets the peer address (OApp instance) for a corresponding endpoint.
     * @param _eid The endpoint ID.
     * @param _peer The address of the peer to be associated with the corresponding endpoint.
     *
     * @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.
     * @dev Set this to bytes32(0) to remove the peer address.
     * @dev Peer is a bytes32 to accommodate non-evm chains.
     */
    function _setPeer(uint32 _eid, bytes32 _peer) internal virtual {
        peers[_eid] = _peer;
        emit PeerSet(_eid, _peer);
    }

    /**
     * @notice Internal function to get the peer address associated with a specific endpoint; reverts if NOT set.
     * ie. the peer is set to bytes32(0).
     * @param _eid The endpoint ID.
     * @return peer The address of the peer associated with the specified endpoint.
     */
    function _getPeerOrRevert(uint32 _eid) internal view virtual returns (bytes32) {
        bytes32 peer = peers[_eid];
        if (peer == bytes32(0)) revert NoPeer(_eid);
        return peer;
    }

    /**
     * @notice Sets the delegate address for the OApp.
     * @param _delegate The address of the delegate to be set.
     *
     * @dev Only the owner/admin of the OApp can call this function.
     * @dev Provides the ability for a delegate to set configs, on behalf of the OApp, directly on the Endpoint contract.
     */
    function setDelegate(address _delegate) public onlyOwner {
        endpoint.setDelegate(_delegate);
    }
}
OAppReceiver.sol 122 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import { IOAppReceiver, Origin } from "./interfaces/IOAppReceiver.sol";
import { OAppCore } from "./OAppCore.sol";

/**
 * @title OAppReceiver
 * @dev Abstract contract implementing the ILayerZeroReceiver interface and extending OAppCore for OApp receivers.
 */
abstract contract OAppReceiver is IOAppReceiver, OAppCore {
    // Custom error message for when the caller is not the registered endpoint/
    error OnlyEndpoint(address addr);

    // @dev The version of the OAppReceiver implementation.
    // @dev Version is bumped when changes are made to this contract.
    uint64 internal constant RECEIVER_VERSION = 2;

    /**
     * @notice Retrieves the OApp version information.
     * @return senderVersion The version of the OAppSender.sol contract.
     * @return receiverVersion The version of the OAppReceiver.sol contract.
     *
     * @dev Providing 0 as the default for OAppSender version. Indicates that the OAppSender is not implemented.
     * ie. this is a RECEIVE only OApp.
     * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions.
     */
    function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {
        return (0, RECEIVER_VERSION);
    }

    /**
     * @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.
     * @dev _origin The origin information containing the source endpoint and sender address.
     *  - srcEid: The source chain endpoint ID.
     *  - sender: The sender address on the src chain.
     *  - nonce: The nonce of the message.
     * @dev _message The lzReceive payload.
     * @param _sender The sender address.
     * @return isSender Is a valid sender.
     *
     * @dev Applications can optionally choose to implement separate composeMsg senders that are NOT the bridging layer.
     * @dev The default sender IS the OAppReceiver implementer.
     */
    function isComposeMsgSender(
        Origin calldata /*_origin*/,
        bytes calldata /*_message*/,
        address _sender
    ) public view virtual returns (bool) {
        return _sender == address(this);
    }

    /**
     * @notice Checks if the path initialization is allowed based on the provided origin.
     * @param origin The origin information containing the source endpoint and sender address.
     * @return Whether the path has been initialized.
     *
     * @dev This indicates to the endpoint that the OApp has enabled msgs for this particular path to be received.
     * @dev This defaults to assuming if a peer has been set, its initialized.
     * Can be overridden by the OApp if there is other logic to determine this.
     */
    function allowInitializePath(Origin calldata origin) public view virtual returns (bool) {
        return peers[origin.srcEid] == origin.sender;
    }

    /**
     * @notice Retrieves the next nonce for a given source endpoint and sender address.
     * @dev _srcEid The source endpoint ID.
     * @dev _sender The sender address.
     * @return nonce The next nonce.
     *
     * @dev The path nonce starts from 1. If 0 is returned it means that there is NO nonce ordered enforcement.
     * @dev Is required by the off-chain executor to determine the OApp expects msg execution is ordered.
     * @dev This is also enforced by the OApp.
     * @dev By default this is NOT enabled. ie. nextNonce is hardcoded to return 0.
     */
    function nextNonce(uint32 /*_srcEid*/, bytes32 /*_sender*/) public view virtual returns (uint64 nonce) {
        return 0;
    }

    /**
     * @dev Entry point for receiving messages or packets from the endpoint.
     * @param _origin The origin information containing the source endpoint and sender address.
     *  - srcEid: The source chain endpoint ID.
     *  - sender: The sender address on the src chain.
     *  - nonce: The nonce of the message.
     * @param _guid The unique identifier for the received LayerZero message.
     * @param _message The payload of the received message.
     * @param _executor The address of the executor for the received message.
     * @param _extraData Additional arbitrary data provided by the corresponding executor.
     *
     * @dev Entry point for receiving msg/packet from the LayerZero endpoint.
     */
    function lzReceive(
        Origin calldata _origin,
        bytes32 _guid,
        bytes calldata _message,
        address _executor,
        bytes calldata _extraData
    ) public payable virtual {
        // Ensures that only the endpoint can attempt to lzReceive() messages to this OApp.
        if (address(endpoint) != msg.sender) revert OnlyEndpoint(msg.sender);

        // Ensure that the sender matches the expected peer for the source endpoint.
        if (_getPeerOrRevert(_origin.srcEid) != _origin.sender) revert OnlyPeer(_origin.srcEid, _origin.sender);

        // Call the internal OApp implementation of lzReceive.
        _lzReceive(_origin, _guid, _message, _executor, _extraData);
    }

    /**
     * @dev Internal function to implement lzReceive logic without needing to copy the basic parameter validation.
     */
    function _lzReceive(
        Origin calldata _origin,
        bytes32 _guid,
        bytes calldata _message,
        address _executor,
        bytes calldata _extraData
    ) internal virtual;
}
OAppSender.sol 124 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { MessagingParams, MessagingFee, MessagingReceipt } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
import { OAppCore } from "./OAppCore.sol";

/**
 * @title OAppSender
 * @dev Abstract contract implementing the OAppSender functionality for sending messages to a LayerZero endpoint.
 */
abstract contract OAppSender is OAppCore {
    using SafeERC20 for IERC20;

    // Custom error messages
    error NotEnoughNative(uint256 msgValue);
    error LzTokenUnavailable();

    // @dev The version of the OAppSender implementation.
    // @dev Version is bumped when changes are made to this contract.
    uint64 internal constant SENDER_VERSION = 1;

    /**
     * @notice Retrieves the OApp version information.
     * @return senderVersion The version of the OAppSender.sol contract.
     * @return receiverVersion The version of the OAppReceiver.sol contract.
     *
     * @dev Providing 0 as the default for OAppReceiver version. Indicates that the OAppReceiver is not implemented.
     * ie. this is a SEND only OApp.
     * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions
     */
    function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {
        return (SENDER_VERSION, 0);
    }

    /**
     * @dev Internal function to interact with the LayerZero EndpointV2.quote() for fee calculation.
     * @param _dstEid The destination endpoint ID.
     * @param _message The message payload.
     * @param _options Additional options for the message.
     * @param _payInLzToken Flag indicating whether to pay the fee in LZ tokens.
     * @return fee The calculated MessagingFee for the message.
     *      - nativeFee: The native fee for the message.
     *      - lzTokenFee: The LZ token fee for the message.
     */
    function _quote(
        uint32 _dstEid,
        bytes memory _message,
        bytes memory _options,
        bool _payInLzToken
    ) internal view virtual returns (MessagingFee memory fee) {
        return
            endpoint.quote(
                MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _payInLzToken),
                address(this)
            );
    }

    /**
     * @dev Internal function to interact with the LayerZero EndpointV2.send() for sending a message.
     * @param _dstEid The destination endpoint ID.
     * @param _message The message payload.
     * @param _options Additional options for the message.
     * @param _fee The calculated LayerZero fee for the message.
     *      - nativeFee: The native fee.
     *      - lzTokenFee: The lzToken fee.
     * @param _refundAddress The address to receive any excess fee values sent to the endpoint.
     * @return receipt The receipt for the sent message.
     *      - guid: The unique identifier for the sent message.
     *      - nonce: The nonce of the sent message.
     *      - fee: The LayerZero fee incurred for the message.
     */
    function _lzSend(
        uint32 _dstEid,
        bytes memory _message,
        bytes memory _options,
        MessagingFee memory _fee,
        address _refundAddress
    ) internal virtual returns (MessagingReceipt memory receipt) {
        // @dev Push corresponding fees to the endpoint, any excess is sent back to the _refundAddress from the endpoint.
        uint256 messageValue = _payNative(_fee.nativeFee);
        if (_fee.lzTokenFee > 0) _payLzToken(_fee.lzTokenFee);

        return
            // solhint-disable-next-line check-send-result
            endpoint.send{ value: messageValue }(
                MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _fee.lzTokenFee > 0),
                _refundAddress
            );
    }

    /**
     * @dev Internal function to pay the native fee associated with the message.
     * @param _nativeFee The native fee to be paid.
     * @return nativeFee The amount of native currency paid.
     *
     * @dev If the OApp needs to initiate MULTIPLE LayerZero messages in a single transaction,
     * this will need to be overridden because msg.value would contain multiple lzFees.
     * @dev Should be overridden in the event the LayerZero endpoint requires a different native currency.
     * @dev Some EVMs use an ERC20 as a method for paying transactions/gasFees.
     * @dev The endpoint is EITHER/OR, ie. it will NOT support both types of native payment at a time.
     */
    function _payNative(uint256 _nativeFee) internal virtual returns (uint256 nativeFee) {
        if (msg.value != _nativeFee) revert NotEnoughNative(msg.value);
        return _nativeFee;
    }

    /**
     * @dev Internal function to pay the LZ token fee associated with the message.
     * @param _lzTokenFee The LZ token fee to be paid.
     *
     * @dev If the caller is trying to pay in the specified lzToken, then the lzTokenFee is passed to the endpoint.
     * @dev Any excess sent, is passed back to the specified _refundAddress in the _lzSend().
     */
    function _payLzToken(uint256 _lzTokenFee) internal virtual {
        // @dev Cannot cache the token because it is not immutable in the endpoint.
        address lzToken = endpoint.lzToken();
        if (lzToken == address(0)) revert LzTokenUnavailable();

        // Pay LZ token fee by sending tokens to the endpoint.
        IERC20(lzToken).safeTransferFrom(msg.sender, address(endpoint), _lzTokenFee);
    }
}
IOAppPreCrimeSimulator.sol 55 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

// @dev Import the Origin so it's exposed to OAppPreCrimeSimulator implementers.
// solhint-disable-next-line no-unused-import
import { InboundPacket, Origin } from "../libs/Packet.sol";

/**
 * @title IOAppPreCrimeSimulator Interface
 * @dev Interface for the preCrime simulation functionality in an OApp.
 */
interface IOAppPreCrimeSimulator {
    // @dev simulation result used in PreCrime implementation
    error SimulationResult(bytes result);
    error OnlySelf();

    /**
     * @dev Emitted when the preCrime contract address is set.
     * @param preCrimeAddress The address of the preCrime contract.
     */
    event PreCrimeSet(address preCrimeAddress);

    /**
     * @dev Retrieves the address of the preCrime contract implementation.
     * @return The address of the preCrime contract.
     */
    function preCrime() external view returns (address);

    /**
     * @dev Retrieves the address of the OApp contract.
     * @return The address of the OApp contract.
     */
    function oApp() external view returns (address);

    /**
     * @dev Sets the preCrime contract address.
     * @param _preCrime The address of the preCrime contract.
     */
    function setPreCrime(address _preCrime) external;

    /**
     * @dev Mocks receiving a packet, then reverts with a series of data to infer the state/result.
     * @param _packets An array of LayerZero InboundPacket objects representing received packets.
     */
    function lzReceiveAndRevert(InboundPacket[] calldata _packets) external payable;

    /**
     * @dev checks if the specified peer is considered 'trusted' by the OApp.
     * @param _eid The endpoint Id to check.
     * @param _peer The peer to check.
     * @return Whether the peer passed is considered 'trusted' by the OApp.
     */
    function isPeer(uint32 _eid, bytes32 _peer) external view returns (bool);
}
IPreCrime.sol 40 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;
struct PreCrimePeer {
    uint32 eid;
    bytes32 preCrime;
    bytes32 oApp;
}

// TODO not done yet
interface IPreCrime {
    error OnlyOffChain();

    // for simulate()
    error PacketOversize(uint256 max, uint256 actual);
    error PacketUnsorted();
    error SimulationFailed(bytes reason);

    // for preCrime()
    error SimulationResultNotFound(uint32 eid);
    error InvalidSimulationResult(uint32 eid, bytes reason);
    error CrimeFound(bytes crime);

    function getConfig(bytes[] calldata _packets, uint256[] calldata _packetMsgValues) external returns (bytes memory);

    function simulate(
        bytes[] calldata _packets,
        uint256[] calldata _packetMsgValues
    ) external payable returns (bytes memory);

    function buildSimulationResult() external view returns (bytes memory);

    function preCrime(
        bytes[] calldata _packets,
        uint256[] calldata _packetMsgValues,
        bytes[] calldata _simulations
    ) external;

    function version() external view returns (uint64 major, uint8 minor);
}
Packet.sol 61 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import { Origin } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
import { PacketV1Codec } from "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/PacketV1Codec.sol";

/**
 * @title InboundPacket
 * @dev Structure representing an inbound packet received by the contract.
 */
struct InboundPacket {
    Origin origin; // Origin information of the packet.
    uint32 dstEid; // Destination endpointId of the packet.
    address receiver; // Receiver address for the packet.
    bytes32 guid; // Unique identifier of the packet.
    uint256 value; // msg.value of the packet.
    address executor; // Executor address for the packet.
    bytes message; // Message payload of the packet.
    bytes extraData; // Additional arbitrary data for the packet.
}

/**
 * @title PacketDecoder
 * @dev Library for decoding LayerZero packets.
 */
library PacketDecoder {
    using PacketV1Codec for bytes;

    /**
     * @dev Decode an inbound packet from the given packet data.
     * @param _packet The packet data to decode.
     * @return packet An InboundPacket struct representing the decoded packet.
     */
    function decode(bytes calldata _packet) internal pure returns (InboundPacket memory packet) {
        packet.origin = Origin(_packet.srcEid(), _packet.sender(), _packet.nonce());
        packet.dstEid = _packet.dstEid();
        packet.receiver = _packet.receiverB20();
        packet.guid = _packet.guid();
        packet.message = _packet.message();
    }

    /**
     * @dev Decode multiple inbound packets from the given packet data and associated message values.
     * @param _packets An array of packet data to decode.
     * @param _packetMsgValues An array of associated message values for each packet.
     * @return packets An array of InboundPacket structs representing the decoded packets.
     */
    function decode(
        bytes[] calldata _packets,
        uint256[] memory _packetMsgValues
    ) internal pure returns (InboundPacket[] memory packets) {
        packets = new InboundPacket[](_packets.length);
        for (uint256 i = 0; i < _packets.length; i++) {
            bytes calldata packet = _packets[i];
            packets[i] = PacketDecoder.decode(packet);
            // @dev Allows the verifier to specify the msg.value that gets passed in lzReceive.
            packets[i].value = _packetMsgValues[i];
        }
    }
}
OAppPreCrimeSimulator.sol 125 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IPreCrime } from "./interfaces/IPreCrime.sol";
import { IOAppPreCrimeSimulator, InboundPacket, Origin } from "./interfaces/IOAppPreCrimeSimulator.sol";

/**
 * @title OAppPreCrimeSimulator
 * @dev Abstract contract serving as the base for preCrime simulation functionality in an OApp.
 */
abstract contract OAppPreCrimeSimulator is IOAppPreCrimeSimulator, Ownable {
    // The address of the preCrime implementation.
    address public preCrime;

    /**
     * @dev Retrieves the address of the OApp contract.
     * @return The address of the OApp contract.
     *
     * @dev The simulator contract is the base contract for the OApp by default.
     * @dev If the simulator is a separate contract, override this function.
     */
    function oApp() external view virtual returns (address) {
        return address(this);
    }

    /**
     * @dev Sets the preCrime contract address.
     * @param _preCrime The address of the preCrime contract.
     */
    function setPreCrime(address _preCrime) public virtual onlyOwner {
        preCrime = _preCrime;
        emit PreCrimeSet(_preCrime);
    }

    /**
     * @dev Interface for pre-crime simulations. Always reverts at the end with the simulation results.
     * @param _packets An array of InboundPacket objects representing received packets to be delivered.
     *
     * @dev WARNING: MUST revert at the end with the simulation results.
     * @dev Gives the preCrime implementation the ability to mock sending packets to the lzReceive function,
     * WITHOUT actually executing them.
     */
    function lzReceiveAndRevert(InboundPacket[] calldata _packets) public payable virtual {
        for (uint256 i = 0; i < _packets.length; i++) {
            InboundPacket calldata packet = _packets[i];

            // Ignore packets that are not from trusted peers.
            if (!isPeer(packet.origin.srcEid, packet.origin.sender)) continue;

            // @dev Because a verifier is calling this function, it doesnt have access to executor params:
            //  - address _executor
            //  - bytes calldata _extraData
            // preCrime will NOT work for OApps that rely on these two parameters inside of their _lzReceive().
            // They are instead stubbed to default values, address(0) and bytes("")
            // @dev Calling this.lzReceiveSimulate removes ability for assembly return 0 callstack exit,
            // which would cause the revert to be ignored.
            this.lzReceiveSimulate{ value: packet.value }(
                packet.origin,
                packet.guid,
                packet.message,
                packet.executor,
                packet.extraData
            );
        }

        // @dev Revert with the simulation results. msg.sender must implement IPreCrime.buildSimulationResult().
        revert SimulationResult(IPreCrime(msg.sender).buildSimulationResult());
    }

    /**
     * @dev Is effectively an internal function because msg.sender must be address(this).
     * Allows resetting the call stack for 'internal' calls.
     * @param _origin The origin information containing the source endpoint and sender address.
     *  - srcEid: The source chain endpoint ID.
     *  - sender: The sender address on the src chain.
     *  - nonce: The nonce of the message.
     * @param _guid The unique identifier of the packet.
     * @param _message The message payload of the packet.
     * @param _executor The executor address for the packet.
     * @param _extraData Additional data for the packet.
     */
    function lzReceiveSimulate(
        Origin calldata _origin,
        bytes32 _guid,
        bytes calldata _message,
        address _executor,
        bytes calldata _extraData
    ) external payable virtual {
        // @dev Ensure ONLY can be called 'internally'.
        if (msg.sender != address(this)) revert OnlySelf();
        _lzReceiveSimulate(_origin, _guid, _message, _executor, _extraData);
    }

    /**
     * @dev Internal function to handle the OAppPreCrimeSimulator simulated receive.
     * @param _origin The origin information.
     *  - srcEid: The source chain endpoint ID.
     *  - sender: The sender address from the src chain.
     *  - nonce: The nonce of the LayerZero message.
     * @param _guid The GUID of the LayerZero message.
     * @param _message The LayerZero message.
     * @param _executor The address of the off-chain executor.
     * @param _extraData Arbitrary data passed by the msg executor.
     *
     * @dev Enables the preCrime simulator to mock sending lzReceive() messages,
     * routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver.
     */
    function _lzReceiveSimulate(
        Origin calldata _origin,
        bytes32 _guid,
        bytes calldata _message,
        address _executor,
        bytes calldata _extraData
    ) internal virtual;

    /**
     * @dev checks if the specified peer is considered 'trusted' by the OApp.
     * @param _eid The endpoint Id to check.
     * @param _peer The peer to check.
     * @return Whether the peer passed is considered 'trusted' by the OApp.
     */
    function isPeer(uint32 _eid, bytes32 _peer) public view virtual returns (bool);
}
Fee.sol 56 lines
// SPDX-LICENSE-IDENTIFIER: MIT

pragma solidity ^0.8.20;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

import { FeeConfig, IFee } from "./interfaces/IFee.sol";

/**
 * @title Fee
 * @notice Implements fee configuration and calculation.
 */
abstract contract Fee is IFee, Ownable {
    uint16 public constant BPS_DENOMINATOR = 10_000;

    /**
     * @dev Default fee basis points (BPS) for all destinations.
     */
    uint16 public defaultFeeBps;

    /**
     * @dev Fee configuration for a specific destination LayerZero endpoint ID.
     */
    mapping(uint32 dstEid => FeeConfig config) public feeBps;

    /**
     * @dev Sets the default fee basis points (BPS) for all destinations.
     */
    function setDefaultFeeBps(uint16 _feeBps) external onlyOwner {
        if (_feeBps > BPS_DENOMINATOR) revert IFee.InvalidBps();
        defaultFeeBps = _feeBps;
        emit DefaultFeeBpsSet(_feeBps);
    }

    /**
     * @dev Sets the fee basis points (BPS) for a specific destination LayerZero EndpointV2 ID.
     */
    function setFeeBps(uint32 _dstEid, uint16 _feeBps, bool _enabled) external onlyOwner {
        if (_feeBps > BPS_DENOMINATOR) revert IFee.InvalidBps();
        feeBps[_dstEid] = FeeConfig(_feeBps, _enabled);
        emit FeeBpsSet(_dstEid, _feeBps, _enabled);
    }

    /**
     * @dev Returns the fee for a specific destination LayerZero EndpointV2 ID.
     */
    function getFee(uint32 _dstEid, uint256 _amount) public view virtual returns (uint256) {
        uint16 bps = _getFeeBps(_dstEid);
        return bps == 0 ? 0 : (_amount * bps) / BPS_DENOMINATOR;
    }

    function _getFeeBps(uint32 _dstEid) internal view returns (uint16) {
        FeeConfig memory config = feeBps[_dstEid];
        return config.enabled ? config.feeBps : defaultFeeBps;
    }
}
IFee.sol 33 lines
// SPDX-LICENSE-IDENTIFIER: MIT

pragma solidity ^0.8.0;

struct FeeConfig {
    uint16 feeBps;
    bool enabled;
}

/**
 * @title Fee interface.
 * @notice A generic interface for collecting fees.
 */
interface IFee {
    // errors
    error InvalidBps();
    error InvalidFeeOwner();

    // events
    event FeeBpsSet(uint32 dstEid, uint16 feeBps, bool enabled);
    event DefaultFeeBpsSet(uint16 feeBps);

    // setters
    /**
     * @dev Sets the default fee basis points (BPS) for all destinations.
     */
    function setDefaultFeeBps(uint16 _feeBps) external;

    /**
     * @dev Sets the fee basis points (BPS) for a specific destination LayerZero EndpointV2 ID.
     */
    function setFeeBps(uint32 _dstEid, uint16 _feeBps, bool _enabled) external;
}
IOFT.sol 150 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import { MessagingReceipt, MessagingFee } from "@layerzerolabs/oapp-evm/contracts/oapp/OAppSender.sol";

/**
 * @dev Struct representing token parameters for the OFT send() operation.
 */
struct SendParam {
    uint32 dstEid; // Destination endpoint ID.
    bytes32 to; // Recipient address.
    uint256 amountLD; // Amount to send in local decimals.
    uint256 minAmountLD; // Minimum amount to send in local decimals.
    bytes extraOptions; // Additional options supplied by the caller to be used in the LayerZero message.
    bytes composeMsg; // The composed message for the send() operation.
    bytes oftCmd; // The OFT command to be executed, unused in default OFT implementations.
}

/**
 * @dev Struct representing OFT limit information.
 * @dev These amounts can change dynamically and are up the specific oft implementation.
 */
struct OFTLimit {
    uint256 minAmountLD; // Minimum amount in local decimals that can be sent to the recipient.
    uint256 maxAmountLD; // Maximum amount in local decimals that can be sent to the recipient.
}

/**
 * @dev Struct representing OFT receipt information.
 */
struct OFTReceipt {
    uint256 amountSentLD; // Amount of tokens ACTUALLY debited from the sender in local decimals.
    // @dev In non-default implementations, the amountReceivedLD COULD differ from this value.
    uint256 amountReceivedLD; // Amount of tokens to be received on the remote side.
}

/**
 * @dev Struct representing OFT fee details.
 * @dev Future proof mechanism to provide a standardized way to communicate fees to things like a UI.
 */
struct OFTFeeDetail {
    int256 feeAmountLD; // Amount of the fee in local decimals.
    string description; // Description of the fee.
}

/**
 * @title IOFT
 * @dev Interface for the OftChain (OFT) token.
 * @dev Does not inherit ERC20 to accommodate usage by OFTAdapter as well.
 * @dev This specific interface ID is '0x02e49c2c'.
 */
interface IOFT {
    // Custom error messages
    error InvalidLocalDecimals();
    error SlippageExceeded(uint256 amountLD, uint256 minAmountLD);
    error AmountSDOverflowed(uint256 amountSD);

    // Events
    event OFTSent(
        bytes32 indexed guid, // GUID of the OFT message.
        uint32 dstEid, // Destination Endpoint ID.
        address indexed fromAddress, // Address of the sender on the src chain.
        uint256 amountSentLD, // Amount of tokens sent in local decimals.
        uint256 amountReceivedLD // Amount of tokens received in local decimals.
    );
    event OFTReceived(
        bytes32 indexed guid, // GUID of the OFT message.
        uint32 srcEid, // Source Endpoint ID.
        address indexed toAddress, // Address of the recipient on the dst chain.
        uint256 amountReceivedLD // Amount of tokens received in local decimals.
    );

    /**
     * @notice Retrieves interfaceID and the version of the OFT.
     * @return interfaceId The interface ID.
     * @return version The version.
     *
     * @dev interfaceId: This specific interface ID is '0x02e49c2c'.
     * @dev version: Indicates a cross-chain compatible msg encoding with other OFTs.
     * @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented.
     * ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)
     */
    function oftVersion() external view returns (bytes4 interfaceId, uint64 version);

    /**
     * @notice Retrieves the address of the token associated with the OFT.
     * @return token The address of the ERC20 token implementation.
     */
    function token() external view returns (address);

    /**
     * @notice Indicates whether the OFT contract requires approval of the 'token()' to send.
     * @return requiresApproval Needs approval of the underlying token implementation.
     *
     * @dev Allows things like wallet implementers to determine integration requirements,
     * without understanding the underlying token implementation.
     */
    function approvalRequired() external view returns (bool);

    /**
     * @notice Retrieves the shared decimals of the OFT.
     * @return sharedDecimals The shared decimals of the OFT.
     */
    function sharedDecimals() external view returns (uint8);

    /**
     * @notice Provides the fee breakdown and settings data for an OFT. Unused in the default implementation.
     * @param _sendParam The parameters for the send operation.
     * @return limit The OFT limit information.
     * @return oftFeeDetails The details of OFT fees.
     * @return receipt The OFT receipt information.
     */
    function quoteOFT(
        SendParam calldata _sendParam
    ) external view returns (OFTLimit memory, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory);

    /**
     * @notice Provides a quote for the send() operation.
     * @param _sendParam The parameters for the send() operation.
     * @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.
     * @return fee The calculated LayerZero messaging fee from the send() operation.
     *
     * @dev MessagingFee: LayerZero msg fee
     *  - nativeFee: The native fee.
     *  - lzTokenFee: The lzToken fee.
     */
    function quoteSend(SendParam calldata _sendParam, bool _payInLzToken) external view returns (MessagingFee memory);

    /**
     * @notice Executes the send() operation.
     * @param _sendParam The parameters for the send operation.
     * @param _fee The fee information supplied by the caller.
     *      - nativeFee: The native fee.
     *      - lzTokenFee: The lzToken fee.
     * @param _refundAddress The address to receive any excess funds from fees etc. on the src.
     * @return receipt The LayerZero messaging receipt from the send() operation.
     * @return oftReceipt The OFT receipt information.
     *
     * @dev MessagingReceipt: LayerZero msg receipt
     *  - guid: The unique identifier for the sent message.
     *  - nonce: The nonce of the sent message.
     *  - fee: The LayerZero fee incurred for the message.
     */
    function send(
        SendParam calldata _sendParam,
        MessagingFee calldata _fee,
        address _refundAddress
    ) external payable returns (MessagingReceipt memory, OFTReceipt memory);
}
OFTComposeMsgCodec.sol 91 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

library OFTComposeMsgCodec {
    // Offset constants for decoding composed messages
    uint8 private constant NONCE_OFFSET = 8;
    uint8 private constant SRC_EID_OFFSET = 12;
    uint8 private constant AMOUNT_LD_OFFSET = 44;
    uint8 private constant COMPOSE_FROM_OFFSET = 76;

    /**
     * @dev Encodes a OFT composed message.
     * @param _nonce The nonce value.
     * @param _srcEid The source endpoint ID.
     * @param _amountLD The amount in local decimals.
     * @param _composeMsg The composed message.
     * @return _msg The encoded Composed message.
     */
    function encode(
        uint64 _nonce,
        uint32 _srcEid,
        uint256 _amountLD,
        bytes memory _composeMsg // 0x[composeFrom][composeMsg]
    ) internal pure returns (bytes memory _msg) {
        _msg = abi.encodePacked(_nonce, _srcEid, _amountLD, _composeMsg);
    }

    /**
     * @dev Retrieves the nonce for the composed message.
     * @param _msg The message.
     * @return The nonce value.
     */
    function nonce(bytes calldata _msg) internal pure returns (uint64) {
        return uint64(bytes8(_msg[:NONCE_OFFSET]));
    }

    /**
     * @dev Retrieves the source endpoint ID for the composed message.
     * @param _msg The message.
     * @return The source endpoint ID.
     */
    function srcEid(bytes calldata _msg) internal pure returns (uint32) {
        return uint32(bytes4(_msg[NONCE_OFFSET:SRC_EID_OFFSET]));
    }

    /**
     * @dev Retrieves the amount in local decimals from the composed message.
     * @param _msg The message.
     * @return The amount in local decimals.
     */
    function amountLD(bytes calldata _msg) internal pure returns (uint256) {
        return uint256(bytes32(_msg[SRC_EID_OFFSET:AMOUNT_LD_OFFSET]));
    }

    /**
     * @dev Retrieves the composeFrom value from the composed message.
     * @param _msg The message.
     * @return The composeFrom value.
     */
    function composeFrom(bytes calldata _msg) internal pure returns (bytes32) {
        return bytes32(_msg[AMOUNT_LD_OFFSET:COMPOSE_FROM_OFFSET]);
    }

    /**
     * @dev Retrieves the composed message.
     * @param _msg The message.
     * @return The composed message.
     */
    function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) {
        return _msg[COMPOSE_FROM_OFFSET:];
    }

    /**
     * @dev Converts an address to bytes32.
     * @param _addr The address to convert.
     * @return The bytes32 representation of the address.
     */
    function addressToBytes32(address _addr) internal pure returns (bytes32) {
        return bytes32(uint256(uint160(_addr)));
    }

    /**
     * @dev Converts bytes32 to an address.
     * @param _b The bytes32 value to convert.
     * @return The address representation of bytes32.
     */
    function bytes32ToAddress(bytes32 _b) internal pure returns (address) {
        return address(uint160(uint256(_b)));
    }
}
OFTMsgCodec.sol 83 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

library OFTMsgCodec {
    // Offset constants for encoding and decoding OFT messages
    uint8 private constant SEND_TO_OFFSET = 32;
    uint8 private constant SEND_AMOUNT_SD_OFFSET = 40;

    /**
     * @dev Encodes an OFT LayerZero message.
     * @param _sendTo The recipient address.
     * @param _amountShared The amount in shared decimals.
     * @param _composeMsg The composed message.
     * @return _msg The encoded message.
     * @return hasCompose A boolean indicating whether the message has a composed payload.
     */
    function encode(
        bytes32 _sendTo,
        uint64 _amountShared,
        bytes memory _composeMsg
    ) internal view returns (bytes memory _msg, bool hasCompose) {
        hasCompose = _composeMsg.length > 0;
        // @dev Remote chains will want to know the composed function caller ie. msg.sender on the src.
        _msg = hasCompose
            ? abi.encodePacked(_sendTo, _amountShared, addressToBytes32(msg.sender), _composeMsg)
            : abi.encodePacked(_sendTo, _amountShared);
    }

    /**
     * @dev Checks if the OFT message is composed.
     * @param _msg The OFT message.
     * @return A boolean indicating whether the message is composed.
     */
    function isComposed(bytes calldata _msg) internal pure returns (bool) {
        return _msg.length > SEND_AMOUNT_SD_OFFSET;
    }

    /**
     * @dev Retrieves the recipient address from the OFT message.
     * @param _msg The OFT message.
     * @return The recipient address.
     */
    function sendTo(bytes calldata _msg) internal pure returns (bytes32) {
        return bytes32(_msg[:SEND_TO_OFFSET]);
    }

    /**
     * @dev Retrieves the amount in shared decimals from the OFT message.
     * @param _msg The OFT message.
     * @return The amount in shared decimals.
     */
    function amountSD(bytes calldata _msg) internal pure returns (uint64) {
        return uint64(bytes8(_msg[SEND_TO_OFFSET:SEND_AMOUNT_SD_OFFSET]));
    }

    /**
     * @dev Retrieves the composed message from the OFT message.
     * @param _msg The OFT message.
     * @return The composed message.
     */
    function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) {
        return _msg[SEND_AMOUNT_SD_OFFSET:];
    }

    /**
     * @dev Converts an address to bytes32.
     * @param _addr The address to convert.
     * @return The bytes32 representation of the address.
     */
    function addressToBytes32(address _addr) internal pure returns (bytes32) {
        return bytes32(uint256(uint160(_addr)));
    }

    /**
     * @dev Converts bytes32 to an address.
     * @param _b The bytes32 value to convert.
     * @return The address representation of bytes32.
     */
    function bytes32ToAddress(bytes32 _b) internal pure returns (address) {
        return address(uint160(uint256(_b)));
    }
}
OFTCore.sol 430 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import { OApp, Origin } from "@layerzerolabs/oapp-evm/contracts/oapp/OApp.sol";
import { OAppOptionsType3 } from "@layerzerolabs/oapp-evm/contracts/oapp/libs/OAppOptionsType3.sol";
import { IOAppMsgInspector } from "@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppMsgInspector.sol";

import { OAppPreCrimeSimulator } from "@layerzerolabs/oapp-evm/contracts/precrime/OAppPreCrimeSimulator.sol";

import { IOFT, SendParam, OFTLimit, OFTReceipt, OFTFeeDetail, MessagingReceipt, MessagingFee } from "./interfaces/IOFT.sol";
import { OFTMsgCodec } from "./libs/OFTMsgCodec.sol";
import { OFTComposeMsgCodec } from "./libs/OFTComposeMsgCodec.sol";

/**
 * @title OFTCore
 * @dev Abstract contract for the OftChain (OFT) token.
 */
abstract contract OFTCore is IOFT, OApp, OAppPreCrimeSimulator, OAppOptionsType3 {
    using OFTMsgCodec for bytes;
    using OFTMsgCodec for bytes32;

    // @notice Provides a conversion rate when swapping between denominations of SD and LD
    //      - shareDecimals == SD == shared Decimals
    //      - localDecimals == LD == local decimals
    // @dev Considers that tokens have different decimal amounts on various chains.
    // @dev eg.
    //  For a token
    //      - locally with 4 decimals --> 1.2345 => uint(12345)
    //      - remotely with 2 decimals --> 1.23 => uint(123)
    //      - The conversion rate would be 10 ** (4 - 2) = 100
    //  @dev If you want to send 1.2345 -> (uint 12345), you CANNOT represent that value on the remote,
    //  you can only display 1.23 -> uint(123).
    //  @dev To preserve the dust that would otherwise be lost on that conversion,
    //  we need to unify a denomination that can be represented on ALL chains inside of the OFT mesh
    uint256 public immutable decimalConversionRate;

    // @notice Msg types that are used to identify the various OFT operations.
    // @dev This can be extended in child contracts for non-default oft operations
    // @dev These values are used in things like combineOptions() in OAppOptionsType3.sol.
    uint16 public constant SEND = 1;
    uint16 public constant SEND_AND_CALL = 2;

    // Address of an optional contract to inspect both 'message' and 'options'
    address public msgInspector;
    event MsgInspectorSet(address inspector);

    /**
     * @dev Constructor.
     * @param _localDecimals The decimals of the token on the local chain (this chain).
     * @param _endpoint The address of the LayerZero endpoint.
     * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
     */
    constructor(uint8 _localDecimals, address _endpoint, address _delegate) OApp(_endpoint, _delegate) {
        if (_localDecimals < sharedDecimals()) revert InvalidLocalDecimals();
        decimalConversionRate = 10 ** (_localDecimals - sharedDecimals());
    }

    /**
     * @notice Retrieves interfaceID and the version of the OFT.
     * @return interfaceId The interface ID.
     * @return version The version.
     *
     * @dev interfaceId: This specific interface ID is '0x02e49c2c'.
     * @dev version: Indicates a cross-chain compatible msg encoding with other OFTs.
     * @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented.
     * ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)
     */
    function oftVersion() external pure virtual returns (bytes4 interfaceId, uint64 version) {
        return (type(IOFT).interfaceId, 1);
    }

    /**
     * @dev Retrieves the shared decimals of the OFT.
     * @return The shared decimals of the OFT.
     *
     * @dev Sets an implicit cap on the amount of tokens, over uint64.max() will need some sort of outbound cap / totalSupply cap
     * Lowest common decimal denominator between chains.
     * Defaults to 6 decimal places to provide up to 18,446,744,073,709.551615 units (max uint64).
     * For tokens exceeding this totalSupply(), they will need to override the sharedDecimals function with something smaller.
     * ie. 4 sharedDecimals would be 1,844,674,407,370,955.1615
     */
    function sharedDecimals() public view virtual returns (uint8) {
        return 6;
    }

    /**
     * @dev Sets the message inspector address for the OFT.
     * @param _msgInspector The address of the message inspector.
     *
     * @dev This is an optional contract that can be used to inspect both 'message' and 'options'.
     * @dev Set it to address(0) to disable it, or set it to a contract address to enable it.
     */
    function setMsgInspector(address _msgInspector) public virtual onlyOwner {
        msgInspector = _msgInspector;
        emit MsgInspectorSet(_msgInspector);
    }

    /**
     * @notice Provides the fee breakdown and settings data for an OFT. Unused in the default implementation.
     * @param _sendParam The parameters for the send operation.
     * @return oftLimit The OFT limit information.
     * @return oftFeeDetails The details of OFT fees.
     * @return oftReceipt The OFT receipt information.
     */
    function quoteOFT(
        SendParam calldata _sendParam
    )
        external
        view
        virtual
        returns (OFTLimit memory oftLimit, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory oftReceipt)
    {
        uint256 minAmountLD = 0; // Unused in the default implementation.
        uint256 maxAmountLD = IERC20(this.token()).totalSupply(); // Unused in the default implementation.
        oftLimit = OFTLimit(minAmountLD, maxAmountLD);

        // Unused in the default implementation; reserved for future complex fee details.
        oftFeeDetails = new OFTFeeDetail[](0);

        // @dev This is the same as the send() operation, but without the actual send.
        // - amountSentLD is the amount in local decimals that would be sent from the sender.
        // - amountReceivedLD is the amount in local decimals that will be credited to the recipient on the remote OFT instance.
        // @dev The amountSentLD MIGHT not equal the amount the user actually receives. HOWEVER, the default does.
        (uint256 amountSentLD, uint256 amountReceivedLD) = _debitView(
            _sendParam.amountLD,
            _sendParam.minAmountLD,
            _sendParam.dstEid
        );
        oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD);
    }

    /**
     * @notice Provides a quote for the send() operation.
     * @param _sendParam The parameters for the send() operation.
     * @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.
     * @return msgFee The calculated LayerZero messaging fee from the send() operation.
     *
     * @dev MessagingFee: LayerZero msg fee
     *  - nativeFee: The native fee.
     *  - lzTokenFee: The lzToken fee.
     */
    function quoteSend(
        SendParam calldata _sendParam,
        bool _payInLzToken
    ) external view virtual returns (MessagingFee memory msgFee) {
        // @dev mock the amount to receive, this is the same operation used in the send().
        // The quote is as similar as possible to the actual send() operation.
        (, uint256 amountReceivedLD) = _debitView(_sendParam.amountLD, _sendParam.minAmountLD, _sendParam.dstEid);

        // @dev Builds the options and OFT message to quote in the endpoint.
        (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD);

        // @dev Calculates the LayerZero fee for the send() operation.
        return _quote(_sendParam.dstEid, message, options, _payInLzToken);
    }

    /**
     * @dev Executes the send operation.
     * @param _sendParam The parameters for the send operation.
     * @param _fee The calculated fee for the send() operation.
     *      - nativeFee: The native fee.
     *      - lzTokenFee: The lzToken fee.
     * @param _refundAddress The address to receive any excess funds.
     * @return msgReceipt The receipt for the send operation.
     * @return oftReceipt The OFT receipt information.
     *
     * @dev MessagingReceipt: LayerZero msg receipt
     *  - guid: The unique identifier for the sent message.
     *  - nonce: The nonce of the sent message.
     *  - fee: The LayerZero fee incurred for the message.
     */
    function send(
        SendParam calldata _sendParam,
        MessagingFee calldata _fee,
        address _refundAddress
    ) external payable virtual returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) {
        return _send(_sendParam, _fee, _refundAddress);
    }

    /**
     * @dev Internal function to execute the send operation.
     * @param _sendParam The parameters for the send operation.
     * @param _fee The calculated fee for the send() operation.
     *      - nativeFee: The native fee.
     *      - lzTokenFee: The lzToken fee.
     * @param _refundAddress The address to receive any excess funds.
     * @return msgReceipt The receipt for the send operation.
     * @return oftReceipt The OFT receipt information.
     *
     * @dev MessagingReceipt: LayerZero msg receipt
     *  - guid: The unique identifier for the sent message.
     *  - nonce: The nonce of the sent message.
     *  - fee: The LayerZero fee incurred for the message.
     */
    function _send(
        SendParam calldata _sendParam,
        MessagingFee calldata _fee,
        address _refundAddress
    ) internal virtual returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) {
        // @dev Applies the token transfers regarding this send() operation.
        // - amountSentLD is the amount in local decimals that was ACTUALLY sent/debited from the sender.
        // - amountReceivedLD is the amount in local decimals that will be received/credited to the recipient on the remote OFT instance.
        (uint256 amountSentLD, uint256 amountReceivedLD) = _debit(
            msg.sender,
            _sendParam.amountLD,
            _sendParam.minAmountLD,
            _sendParam.dstEid
        );

        // @dev Builds the options and OFT message to quote in the endpoint.
        (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD);

        // @dev Sends the message to the LayerZero endpoint and returns the LayerZero msg receipt.
        msgReceipt = _lzSend(_sendParam.dstEid, message, options, _fee, _refundAddress);
        // @dev Formulate the OFT receipt.
        oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD);

        emit OFTSent(msgReceipt.guid, _sendParam.dstEid, msg.sender, amountSentLD, amountReceivedLD);
    }

    /**
     * @dev Internal function to build the message and options.
     * @param _sendParam The parameters for the send() operation.
     * @param _amountLD The amount in local decimals.
     * @return message The encoded message.
     * @return options The encoded options.
     */
    function _buildMsgAndOptions(
        SendParam calldata _sendParam,
        uint256 _amountLD
    ) internal view virtual returns (bytes memory message, bytes memory options) {
        bool hasCompose;
        // @dev This generated message has the msg.sender encoded into the payload so the remote knows who the caller is.
        (message, hasCompose) = OFTMsgCodec.encode(
            _sendParam.to,
            _toSD(_amountLD),
            // @dev Must be include a non empty bytes if you want to compose, EVEN if you dont need it on the remote.
            // EVEN if you dont require an arbitrary payload to be sent... eg. '0x01'
            _sendParam.composeMsg
        );
        // @dev Change the msg type depending if its composed or not.
        uint16 msgType = hasCompose ? SEND_AND_CALL : SEND;
        // @dev Combine the callers _extraOptions with the enforced options via the OAppOptionsType3.
        options = combineOptions(_sendParam.dstEid, msgType, _sendParam.extraOptions);

        // @dev Optionally inspect the message and options depending if the OApp owner has set a msg inspector.
        // @dev If it fails inspection, needs to revert in the implementation. ie. does not rely on return boolean
        address inspector = msgInspector; // caches the msgInspector to avoid potential double storage read
        if (inspector != address(0)) IOAppMsgInspector(inspector).inspect(message, options);
    }

    /**
     * @dev Internal function to handle the receive on the LayerZero endpoint.
     * @param _origin The origin information.
     *  - srcEid: The source chain endpoint ID.
     *  - sender: The sender address from the src chain.
     *  - nonce: The nonce of the LayerZero message.
     * @param _guid The unique identifier for the received LayerZero message.
     * @param _message The encoded message.
     * @dev _executor The address of the executor.
     * @dev _extraData Additional data.
     */
    function _lzReceive(
        Origin calldata _origin,
        bytes32 _guid,
        bytes calldata _message,
        address /*_executor*/, // @dev unused in the default implementation.
        bytes calldata /*_extraData*/ // @dev unused in the default implementation.
    ) internal virtual override {
        // @dev The src sending chain doesnt know the address length on this chain (potentially non-evm)
        // Thus everything is bytes32() encoded in flight.
        address toAddress = _message.sendTo().bytes32ToAddress();
        // @dev Credit the amountLD to the recipient and return the ACTUAL amount the recipient received in local decimals
        uint256 amountReceivedLD = _credit(toAddress, _toLD(_message.amountSD()), _origin.srcEid);

        if (_message.isComposed()) {
            // @dev Proprietary composeMsg format for the OFT.
            bytes memory composeMsg = OFTComposeMsgCodec.encode(
                _origin.nonce,
                _origin.srcEid,
                amountReceivedLD,
                _message.composeMsg()
            );

            // @dev Stores the lzCompose payload that will be executed in a separate tx.
            // Standardizes functionality for executing arbitrary contract invocation on some non-evm chains.
            // @dev The off-chain executor will listen and process the msg based on the src-chain-callers compose options passed.
            // @dev The index is used when a OApp needs to compose multiple msgs on lzReceive.
            // For default OFT implementation there is only 1 compose msg per lzReceive, thus its always 0.
            endpoint.sendCompose(toAddress, _guid, 0 /* the index of the composed message*/, composeMsg);
        }

        emit OFTReceived(_guid, _origin.srcEid, toAddress, amountReceivedLD);
    }

    /**
     * @dev Internal function to handle the OAppPreCrimeSimulator simulated receive.
     * @param _origin The origin information.
     *  - srcEid: The source chain endpoint ID.
     *  - sender: The sender address from the src chain.
     *  - nonce: The nonce of the LayerZero message.
     * @param _guid The unique identifier for the received LayerZero message.
     * @param _message The LayerZero message.
     * @param _executor The address of the off-chain executor.
     * @param _extraData Arbitrary data passed by the msg executor.
     *
     * @dev Enables the preCrime simulator to mock sending lzReceive() messages,
     * routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver.
     */
    function _lzReceiveSimulate(
        Origin calldata _origin,
        bytes32 _guid,
        bytes calldata _message,
        address _executor,
        bytes calldata _extraData
    ) internal virtual override {
        _lzReceive(_origin, _guid, _message, _executor, _extraData);
    }

    /**
     * @dev Check if the peer is considered 'trusted' by the OApp.
     * @param _eid The endpoint ID to check.
     * @param _peer The peer to check.
     * @return Whether the peer passed is considered 'trusted' by the OApp.
     *
     * @dev Enables OAppPreCrimeSimulator to check whether a potential Inbound Packet is from a trusted source.
     */
    function isPeer(uint32 _eid, bytes32 _peer) public view virtual override returns (bool) {
        return peers[_eid] == _peer;
    }

    /**
     * @dev Internal function to remove dust from the given local decimal amount.
     * @param _amountLD The amount in local decimals.
     * @return amountLD The amount after removing dust.
     *
     * @dev Prevents the loss of dust when moving amounts between chains with different decimals.
     * @dev eg. uint(123) with a conversion rate of 100 becomes uint(100).
     */
    function _removeDust(uint256 _amountLD) internal view virtual returns (uint256 amountLD) {
        return (_amountLD / decimalConversionRate) * decimalConversionRate;
    }

    /**
     * @dev Internal function to convert an amount from shared decimals into local decimals.
     * @param _amountSD The amount in shared decimals.
     * @return amountLD The amount in local decimals.
     */
    function _toLD(uint64 _amountSD) internal view virtual returns (uint256 amountLD) {
        return _amountSD * decimalConversionRate;
    }

    /**
     * @dev Internal function to convert an amount from local decimals into shared decimals.
     * @param _amountLD The amount in local decimals.
     * @return amountSD The amount in shared decimals.
     *
     * @dev Reverts if the _amountLD in shared decimals overflows uint64.
     * @dev eg. uint(2**64 + 123) with a conversion rate of 1 wraps around 2**64 to uint(123).
     */
    function _toSD(uint256 _amountLD) internal view virtual returns (uint64 amountSD) {
        uint256 _amountSD = _amountLD / decimalConversionRate;
        if (_amountSD > type(uint64).max) revert AmountSDOverflowed(_amountSD);
        return uint64(_amountSD);
    }

    /**
     * @dev Internal function to mock the amount mutation from a OFT debit() operation.
     * @param _amountLD The amount to send in local decimals.
     * @param _minAmountLD The minimum amount to send in local decimals.
     * @dev _dstEid The destination endpoint ID.
     * @return amountSentLD The amount sent, in local decimals.
     * @return amountReceivedLD The amount to be received on the remote chain, in local decimals.
     *
     * @dev This is where things like fees would be calculated and deducted from the amount to be received on the remote.
     */
    function _debitView(
        uint256 _amountLD,
        uint256 _minAmountLD,
        uint32 /*_dstEid*/
    ) internal view virtual returns (uint256 amountSentLD, uint256 amountReceivedLD) {
        // @dev Remove the dust so nothing is lost on the conversion between chains with different decimals for the token.
        amountSentLD = _removeDust(_amountLD);
        // @dev The amount to send is the same as amount received in the default implementation.
        amountReceivedLD = amountSentLD;

        // @dev Check for slippage.
        if (amountReceivedLD < _minAmountLD) {
            revert SlippageExceeded(amountReceivedLD, _minAmountLD);
        }
    }

    /**
     * @dev Internal function to perform a debit operation.
     * @param _from The address to debit.
     * @param _amountLD The amount to send in local decimals.
     * @param _minAmountLD The minimum amount to send in local decimals.
     * @param _dstEid The destination endpoint ID.
     * @return amountSentLD The amount sent in local decimals.
     * @return amountReceivedLD The amount received in local decimals on the remote.
     *
     * @dev Defined here but are intended to be overriden depending on the OFT implementation.
     * @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD.
     */
    function _debit(
        address _from,
        uint256 _amountLD,
        uint256 _minAmountLD,
        uint32 _dstEid
    ) internal virtual returns (uint256 amountSentLD, uint256 amountReceivedLD);

    /**
     * @dev Internal function to perform a credit operation.
     * @param _to The address to credit.
     * @param _amountLD The amount to credit in local decimals.
     * @param _srcEid The source endpoint ID.
     * @return amountReceivedLD The amount ACTUALLY received in local decimals.
     *
     * @dev Defined here but are intended to be overriden depending on the OFT implementation.
     * @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD.
     */
    function _credit(
        address _to,
        uint256 _amountLD,
        uint32 _srcEid
    ) internal virtual returns (uint256 amountReceivedLD);
}
Ownable.sol 100 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
IERC1363.sol 86 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
IERC165.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";
IERC20.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";
IERC20Metadata.sol 26 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
SafeERC20.sol 212 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _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 Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity 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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            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 silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}
Context.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Pausable.sol 112 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}
ReentrancyGuard.sol 87 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // 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;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _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 {
        // 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 {
        // 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) {
        return _status == ENTERED;
    }
}
GovernanceOAppReceiver.sol 101 lines
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.22;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

import { OAppReceiver, OAppCore, Origin } from "@layerzerolabs/oapp-evm/contracts/oapp/OAppReceiver.sol";

import { IGovernanceOAppReceiver, MessageOrigin } from "./interfaces/IGovernanceOAppReceiver.sol";

/**
 * @title GovernanceOAppReceiver
 * @dev Cross-chain governance receiver contract that handles inbound governance calls
 * @notice This contract receives and executes governance transactions from remote chains via LayerZero
 * @author LayerZero Labs
 */
contract GovernanceOAppReceiver is OAppReceiver, ReentrancyGuard, IGovernanceOAppReceiver {
    /// @dev Temporary variable to store the origin caller and expose it to target contracts during execution
    MessageOrigin private _messageOrigin;

    /**
     * @dev Constructor to initialize the GovernanceOAppReceiver contract
     * @param _governanceOAppSenderEid The GovernanceOAppSender endpoint ID
     * @param _governanceOAppSenderAddress The GovernanceOAppSender address
     * @param _endpoint The LayerZero endpoint address
     * @param _owner The delegate and owner address for the OApp
     */
    constructor(
        uint32 _governanceOAppSenderEid, 
        bytes32 _governanceOAppSenderAddress, 
        address _endpoint, 
        address _owner
    ) OAppCore(_endpoint, _owner) Ownable(_owner) {
        // Set the peer on the GovernanceOAppReceiver contract to the GovernanceOAppSender contract
        _setPeer(_governanceOAppSenderEid, _governanceOAppSenderAddress);

        // Deployment steps:
        // 1. Deploy the GovernanceOAppSender on a given chain.
        // 2. Deploy the GovernanceOAppReceiver on all the dst chains with eid, and addresses generated from step 1.
        // 3. Set the peers on the GovernanceOAppSender contract for all of the receivers deployed in step 2.
        //
        // IMPORTANT!!!!: Since the GovernanceOAppReceiver's lzReceive is gated by valid peers. 
        // If you remove the GovernanceOAppSender as a peer on the GovernanceOAppReceiver contracts, 
        // the GovernanceOAppReceiver will no longer be able to receive/execute messages from the GovernanceOAppSender. 
        // This will brick the system!!! So be very careful when removing a peer.
    }

    /**
     * @inheritdoc IGovernanceOAppReceiver
     */
    function messageOrigin() external view returns (MessageOrigin memory) {
        return _messageOrigin;
    }

    /**
     * @dev Internal function to handle incoming LayerZero messages
     * @param _origin The origin information of the message
     * @param _guid The unique identifier for the message
     * @param _payload The message payload containing sender, target, and calldata
     * @dev _executor The executor address (unused)
     * @dev _extraData Additional data (unused)
     * @notice This function decodes the payload and executes the governance call on the target contract
     */
    function _lzReceive(
        Origin calldata _origin,
        bytes32 _guid,
        bytes calldata _payload,
        address /*_executor*/,
        bytes calldata /*_extraData*/
    ) internal override nonReentrant {
        // Extract the source sender from the first 32 bytes of payload
        bytes32 srcSender = bytes32(_payload[0:32]);
        
        // Extract the target address from bytes 44:64 (last 20 bytes of the 32-byte padded field)
        // The source pads the address to 32 bytes for EVM compatibility.
        address dstTarget = address(uint160(bytes20(_payload[44:64])));
        
        // Extract the calldata from the remaining payload
        bytes memory dstCallData = _payload[64:];
    
        // Set the message origin for the target contract to validate
        // The target contract NEEDS to validate the MessageOrigin struct to confirm it is a valid caller from the source
        _messageOrigin = MessageOrigin({ srcEid: _origin.srcEid, srcSender: srcSender });

        // Execute the governance call on the target contract
        // Target contract SHOULD validate the msg.value if it's used
        (bool success, bytes memory returnData) = dstTarget.call{ value: msg.value }(dstCallData);
        if (!success) {
            if (returnData.length == 0) revert GovernanceCallFailed();
            // Bubble up the revert reason from the target contract
            assembly ("memory-safe") {
                revert(add(32, returnData), mload(returnData))
            }
        }

        // Clear the MessageOrigin to prevent reuse on subsequent calls
        _messageOrigin = MessageOrigin({ srcEid: 0, srcSender: bytes32(0) });

        emit GovernanceCallReceived(_guid);
    }
}
GovernanceOAppSender.sol 94 lines
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.22;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

import { OAppSender, OAppCore, MessagingFee, MessagingReceipt } from "@layerzerolabs/oapp-evm/contracts/oapp/OAppSender.sol";
import { OAppOptionsType3 } from "@layerzerolabs/oapp-evm/contracts/oapp/libs/OAppOptionsType3.sol";

import { IGovernanceOAppSender, TxParams } from "./interfaces/IGovernanceOAppSender.sol";

/**
 * @title GovernanceOAppSender
 * @dev Cross-chain governance sender contract that handles outbound governance calls
 * @notice This contract manages permissions and sends governance transactions to remote chains via LayerZero
 * @author LayerZero Labs
 */
contract GovernanceOAppSender is OAppSender, OAppOptionsType3, IGovernanceOAppSender {
    /// @dev The message type identifier for sending transactions
    uint16 public constant SEND_TX = 1;

    /// @dev This mapping is used to determine if a sender is allowed to call a specific target on a given dst EID.
    mapping(address srcSender => mapping(uint32 dstEid => mapping(bytes32 dstTarget => bool canCall))) public canCallTarget;

    /**
     * @dev Constructor to initialize the GovernanceOAppSender contract
     * @param _endpoint The LayerZero endpoint address
     * @param _owner The delegate and owner address for the OApp
     */
    constructor(address _endpoint, address _owner) OAppCore(_endpoint, _owner) Ownable(_owner) {

        // Deployment steps:
        // 1. Deploy the GovernanceOAppSender on a given chain.
        // 2. Deploy the GovernanceOAppReceiver on all the dst chains with eid, and addresses generated from step 1.
        // 3. Set the peers on the GovernanceOAppSender contract for all of the receivers deployed in step 2.
        //
        // IMPORTANT!!!!: Since the GovernanceOAppReceiver's lzReceive is gated by valid peers. 
        // If you remove the GovernanceOAppSender as a peer on the GovernanceOAppReceiver contracts, 
        // the GovernanceOAppReceiver will no longer be able to receive/execute messages from the GovernanceOAppSender. 
        // This will brick the system!!! So be very careful when removing a peer.
    }

    /**
     * @inheritdoc IGovernanceOAppSender
     */
    function setCanCallTarget(address _srcSender, uint32 _dstEid, bytes32 _dstTarget, bool _canCall) external onlyOwner {
        if (canCallTarget[_srcSender][_dstEid][_dstTarget] == _canCall) revert CanCallTargetIdempotent();

        canCallTarget[_srcSender][_dstEid][_dstTarget] = _canCall;
        emit CanCallTargetSet(_srcSender, _dstEid, _dstTarget, _canCall);
    }

    /**
     * @inheritdoc IGovernanceOAppSender
     */
    function quoteTx(TxParams calldata _params, bool _payInLzToken) external view returns (MessagingFee memory fee) {
        (bytes memory message, bytes memory options) = _buildMsgAndOptions(_params);

        return _quote(_params.dstEid, message, options, _payInLzToken);
    }

    /**
     * @inheritdoc IGovernanceOAppSender
     */
    function sendTx(
        TxParams calldata _params,
        MessagingFee calldata _fee,
        address _refundAddress
    ) external payable returns (MessagingReceipt memory msgReceipt) {
        if (!canCallTarget[msg.sender][_params.dstEid][_params.dstTarget]) revert CannotCallTarget();

        (bytes memory message, bytes memory options) = _buildMsgAndOptions(_params);

        msgReceipt = _lzSend(_params.dstEid, message, options, _fee, _refundAddress);

        emit GovernanceCallSent(msgReceipt.guid);
    }

    /**
     * @dev Build the message and options for sending a governance transaction
     * @param _params The transaction parameters
     * @return message The encoded message containing sender, target, and calldata
     * @return options The LayerZero options for the message
     */
    function _buildMsgAndOptions(TxParams calldata _params) internal view returns (bytes memory, bytes memory) {
        // Convert msg.sender to bytes32 for cross-chain compatibility
        bytes32 msgSenderBytes32 = bytes32(uint256(uint160(msg.sender)));

        // Encode the message with sender, target, and calldata
        bytes memory message = abi.encodePacked(msgSenderBytes32, _params.dstTarget, _params.dstCallData);
        bytes memory options = combineOptions(_params.dstEid, SEND_TX, _params.extraOptions);

        return (message, options);
    }
}
IGovernanceOAppReceiver.sol 38 lines
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.22;

/**
 * @dev Information about the origin of a cross-chain governance message
 * @param srcEid The source endpoint ID where the message originated
 * @param srcSender The address of the original sender on the source chain (as bytes32)
 */
struct MessageOrigin {
    uint32 srcEid;
    bytes32 srcSender;
}

/**
 * @title IGovernanceOAppReceiver
 * @dev Interface for the governance receiver contract that handles inbound cross-chain governance calls
 * @notice This contract receives and executes governance transactions from remote chains
 */
interface IGovernanceOAppReceiver {
    /**
     * @dev Thrown when a governance call execution fails on the target contract
     */
    error GovernanceCallFailed();

    /**
     * @dev Emitted when a governance call is successfully received and executed
     * @param guid The unique identifier for the LayerZero message
     */
    event GovernanceCallReceived(bytes32 indexed guid);

    /**
     * @dev Get the origin information of the current cross-chain governance message
     * @return The MessageOrigin struct containing source endpoint ID and sender address
     * @notice This function should be called by target contracts to validate the message origin
     * @notice Returns zero values when no message is being processed
     */
    function messageOrigin() external view returns (MessageOrigin memory);
}
IGovernanceOAppSender.sol 97 lines
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.22;

import { MessagingFee, MessagingReceipt } from "@layerzerolabs/oapp-evm/contracts/oapp/OApp.sol";

/**
 * @dev Parameters for cross-chain governance transaction
 * @param dstEid The destination endpoint ID
 * @param dstTarget The target contract address on the destination chain (as bytes32)
 * @param dstCallData The calldata to execute on the target contract
 * @param extraOptions Additional LayerZero options for the message
 */
struct TxParams {
    uint32 dstEid;
    bytes32 dstTarget;
    bytes dstCallData;
    bytes extraOptions;
}

/**
 * @title IGovernanceOAppSender
 * @dev Interface for the governance sender contract that handles outbound cross-chain governance calls
 * @notice This contract manages permissions and sends governance transactions to remote chains
 */
interface IGovernanceOAppSender {
    /**
     * @dev Thrown when trying to set the same canCallTarget value that's already set
     */
    error CanCallTargetIdempotent();

    /**
     * @dev Thrown when a sender attempts to call a target they don't have permission for
     */
    error CannotCallTarget();

    /**
     * @dev Emitted when a governance call is successfully sent to a remote chain
     * @param guid The unique identifier for the LayerZero message
     */
    event GovernanceCallSent(bytes32 indexed guid);

    /**
     * @dev Emitted when canCallTarget permission is updated
     * @param sender The address whose permission is being updated
     * @param dstEid The destination endpoint ID
     * @param dstTarget The target contract address (as bytes32)
     * @param canCall Whether the sender can call the target
     */
    event CanCallTargetSet(address indexed sender, uint32 indexed dstEid, bytes32 indexed dstTarget, bool canCall);

    /**
     * @dev The message type identifier for sending transactions
     * @return The message type constant (1)
     */
    function SEND_TX() external view returns (uint16);

    /**
     * @dev Check if a sender can call a specific target on a destination chain
     * @param _srcSender The address of the sender
     * @param _dstEid The destination endpoint ID
     * @param _dstTarget The target contract address (as bytes32)
     * @return canCall Whether the sender has permission to call the target
     */
    function canCallTarget(address _srcSender, uint32 _dstEid, bytes32 _dstTarget) external view returns (bool canCall);

    /**
     * @dev Set permission for a sender to call a specific target on a destination chain
     * @param _srcSender The address of the sender
     * @param _dstEid The destination endpoint ID
     * @param _dstTarget The target contract address (as bytes32)
     * @param _canCall Whether to grant or revoke permission
     * @notice Only callable by the contract owner
     */
    function setCanCallTarget(address _srcSender, uint32 _dstEid, bytes32 _dstTarget, bool _canCall) external;

    /**
     * @dev Quote the fee for sending a governance transaction
     * @param _params The transaction parameters
     * @param _payInLzToken Whether to pay the fee in LayerZero token
     * @return fee The messaging fee required for the transaction
     */
    function quoteTx(TxParams calldata _params, bool _payInLzToken) external view returns (MessagingFee memory fee);

    /**
     * @dev Send a governance transaction to a remote chain
     * @param _params The transaction parameters
     * @param _fee The messaging fee to pay
     * @param _refundAddress The address to receive any excess fee refund
     * @return msgReceipt The receipt containing the message GUID and other details
     * @notice Requires the caller to have permission via canCallTarget mapping
     */
    function sendTx(
        TxParams calldata _params,
        MessagingFee calldata _fee,
        address _refundAddress
    ) external payable returns (MessagingReceipt memory msgReceipt);
}
IMintBurnVoidReturn.sol 19 lines
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.22;

/// @title Interface for mintable and burnable tokens that DOES NOT return success boolean
interface IMintBurnVoidReturn {
    /**
     * @notice Burns tokens from a specified account
     * @param from Address from which tokens will be burned
     * @param amount Amount of tokens to be burned
     */
    function burn(address from, uint256 amount) external;

    /**
     * @notice Mints tokens to a specified account
     * @param to Address to which tokens will be minted
     * @param amount Amount of tokens to be minted
     */
    function mint(address to, uint256 amount) external;
}
ISkyOFT.sol 88 lines
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.22;

import { RateLimitConfig, RateLimitDirection, RateLimitAccountingType } from "./ISkyRateLimiter.sol";

/**
 * @title ISkyOFT
 * @notice Interface for the SkyOFTCore contract, which manages cross-chain transfer rate limits and fees.
 * @dev This interface defines the core functionalities of the SkyOFT system, including rate limit management,
 * pauser management, and fee withdrawal.
 */
interface ISkyOFT {
    // Events
    event FeesWithdrawn(address indexed to, uint256 amountLD);
    event PauserSet(address indexed pauser, bool canPause);

    // Errors
    error PauserIdempotent(address pauser);
    error InsufficientFeeBalance(uint256 amountLD, uint256 feeBalance);
    error OnlyPauser(address caller);

    // @dev Global variable view function definitions.
    function feeBalance() external view returns (uint256 amountLD);
    function pausers(address _pauser) external view returns (bool canPause);

    /**
     * @notice Sets the cross-chain tx rate limits for specific endpoints based on provided configurations.
     * It allows configuration of rate limits either for outbound and inbound directions.
     * This method is designed to be called by contract admins for updating the system's rate limiting behavior.
     *
     * @notice WARNING: Changing rate limits without first calling resetRateLimits() MIGHT result in unexpected behavior.
     * DYOR on Rate Limits across every VM to ensure compatibility.
     * Especially consider inflight decay rates when reducing limits.
     *
     * @param rateLimitConfigsInbound Array of INBOUND `RateLimitConfig` structs that specify new rate limit settings.
     * @param rateLimitConfigsOutbound Array of OUTBOUND `RateLimitConfig` structs that specify new rate limit settings.
     *
     * @dev Each struct includes an endpoint ID, the limit value, and the window duration.
     * @dev The direction (inbound or outbound) specifies whether the eid passed should be considered a srcEid or dstEid.
     */
    function setRateLimits(
        RateLimitConfig[] calldata rateLimitConfigsInbound,
        RateLimitConfig[] calldata rateLimitConfigsOutbound
    ) external;

    /**
     * @notice Resets the rate limits for the given endpoint ids.
     * @param eidsInbound The endpoint ids to reset the rate limits for inbound.
     * @param eidsOutbound The endpoint ids to reset the rate limits for outbound.
     */
    function resetRateLimits(uint32[] calldata eidsInbound, uint32[] calldata eidsOutbound) external;

    /**
     * @notice Sets the rate limit accounting type.
     * @param rateLimitAccountingType The new rate limit accounting type.
     * @dev You may want to call `resetRateLimits` after changing the rate limit accounting type.
     */
    function setRateLimitAccountingType(RateLimitAccountingType rateLimitAccountingType) external;

    /**
     * @notice Sets the pauser status for a given address.
     * @param _pauser The address to set the pauser status for.
     * @param _canPause Boolean indicating ability to pause cross-chain transfers.
     */
    function setPauser(address _pauser, bool _canPause) external;

    /**
     * @notice Pauses the contract if the caller is a pauser.
     * @dev Only pausers can pause the contract.
     */
    function pause() external;

    /**
     * @notice Unpauses the contract.
     * @dev Only the owner can unpause the contract.
     */
    function unpause() external;

    /**
     * @notice Withdraws accumulated fees to a specified address.
     * @param to The address to which the fees will be withdrawn.
     * @param amountLD The amount of tokens to withdraw in local decimals.
     *
     * @dev This also allows for owner to rescue tokens that are otherwise burned/lost.
     */
    function withdrawFees(address to, uint256 amountLD) external;

}
ISkyOFTAdapter.sol 20 lines
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.22;

interface ISkyOFTAdapter {
    // Events
    event LockedTokensMigrated(address indexed to, uint256 amountLD);

    // Errors
    error InvalidAddressZero();

    /**
     * @notice Migrates all locked tokens to a specified address, less the accumulated fees.
     * @param _to The address to which the locked tokens will be migrated.
     *
     * @dev This function is intended to be called by the owner to migrate all locked tokens
     * from this contract to another address, effectively allowing for a migration of the contract's state.
     * @dev The migration EXCLUDES accumulated fees.
     */
    function migrateLockedTokens(address _to) external;
}
ISkyRateLimiter.sol 81 lines
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;

/**
 * @notice Rate Limit struct
 * @param lastUpdated Timestamp representing the last time the rate limit was checked or updated.
 * @param window Defines the duration of the rate limiting window.
 * @param amountInFlight Current amount within the rate limit window.
 * @param limit This represents the maximum allowed amount within a given window.
 */
struct RateLimit {
    uint128 lastUpdated;    // 16 bytes
    uint48 window;          // 6 bytes
    uint256 amountInFlight; // 32 bytes (new slot)
    uint256 limit;          // 32 bytes (new slot)
}

/**
* @notice Rate Limit Configuration struct.
 * @param eid The endpoint id.
 * @param window Defines the duration of the rate limiting window.
 * @param limit This represents the maximum allowed amount within a given window.
 */
struct RateLimitConfig {
    uint32 eid;      // 4 bytes
    uint48 window;   // 6 bytes
    uint256 limit;   // 32 bytes (new slot)
}

// @dev Define an enum to clearly distinguish between inbound and outbound rate limits.
enum RateLimitDirection {
    Inbound,
    Outbound
}

// @dev Define an enum to distinguish between net and gross accounting types for rate limits.
enum RateLimitAccountingType {
    Net,
    Gross
}

/**
 * @notice Interface for the SkyRateLimiter.
 * @dev This interface defines the functions and events for managing rate limits for both inbound and outbound flows.
 */
interface ISkyRateLimiter {
    /**
     * @notice Emitted when _setRateLimits occurs.
     * @param rateLimitConfigs An array of `RateLimitConfig` structs representing configurations set per endpoint id.
     * - `eid`: The source / destination endpoint id (depending on direction).
     * - `window`: Defines the duration of the rate limiting window.
     * - `limit`: This represents the maximum allowed amount within a given window.
     * @param direction Specifies whether the outbound or inbound rates were changed.
     */
    event RateLimitsChanged(RateLimitConfig[] rateLimitConfigs, RateLimitDirection direction);
    event RateLimitAccountingTypeSet(RateLimitAccountingType newRateLimitAccountingType);
    event RateLimitsReset(uint32[] eids, RateLimitDirection direction);

    // @dev Error that is thrown when an amount exceeds the rate limit for a given direction.
    error RateLimitExceeded();

    /**
     * @notice Get the current amount that can be sent to this destination endpoint id for the given rate limit window.
     * @param dstEid The destination endpoint id.
     * @return currentAmountInFlight The current amount that was sent in this window.
     * @return amountCanBeSent The amount that can be sent.
     */
    function getAmountCanBeSent(
        uint32 dstEid
    ) external view returns (uint256 currentAmountInFlight, uint256 amountCanBeSent);

    /**
     * @notice Get the current amount that can be received from the source endpoint id for the given rate limit window.
     * @param srcEid The source endpoint id.
     * @return currentAmountInFlight The current amount that has been received in this window.
     * @return amountCanBeReceived The amount that can be received.
     */
    function getAmountCanBeReceived(
        uint32 srcEid
    ) external view returns (uint256 currentAmountInFlight, uint256 amountCanBeReceived);
}
SkyOFTAdapter.sol 133 lines
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.22;

import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

import { ISkyOFTAdapter } from "./interfaces/ISkyOFTAdapter.sol";
import { SkyOFTCore, RateLimitDirection } from "./SkyOFTCore.sol";

/**
 * @title SkyOFTAdapter Contract
 * @dev OFTAdapter is a contract that adapts an ERC-20 token to the OFT functionality.
 * @dev This contract extends the SkyOFTCore, which extends the SkyRateLimiter containing rate limiting functionality.
 * @dev It allows for the configuration of rate limits for both outbound and inbound directions.
 * @dev It also allows for the setting of the rate limit accounting type to be net or gross.
 *
 * @dev For existing ERC20 tokens, this can be used to convert the token to cross-chain compatibility.
 * @dev WARNING: ONLY 1 of these should exist for a given global mesh.
 */
contract SkyOFTAdapter is ISkyOFTAdapter, SkyOFTCore {
    using SafeERC20 for IERC20;

    uint256 public feeBalance;

    /**
     * @notice Initializes the SkyOFTAdapter contract.
     *
     * @param _token The address of the underlying ERC20 token.
     * @param _lzEndpoint The LayerZero endpoint address.
     * @param _delegate The address of the delegate.
     */
    constructor(
        address _token,
        address _lzEndpoint,
        address _delegate
    ) SkyOFTCore(_token, _lzEndpoint, _delegate) {}

    /**
     * @notice Withdraws accumulated fees to a specified address.
     * @param _to The address to which the fees will be withdrawn.
     * @param _amountLD The amount of tokens to withdraw in local decimals.
     *
     * @dev Doesn't allow owner to pull from the locked assets of the contract, only from accumulated fees.
     */
    function withdrawFees(address _to, uint256 _amountLD) external onlyOwner {
        uint256 balance = feeBalance;
        if (_amountLD > balance) revert InsufficientFeeBalance(_amountLD, balance);

        // @dev Deduct the amount from the fee balance before transferring.
        feeBalance -= _amountLD;

        innerToken.safeTransfer(_to, _amountLD);
        emit FeesWithdrawn(_to, _amountLD);
    }

    /**
     * @notice Migrates all locked tokens to a specified address, less the accumulated fees.
     * @param _to The address to which the locked tokens will be migrated.
     *
     * @dev This function is intended to be called by the owner to migrate all locked tokens
     * from this contract to another address, effectively allowing for a migration of the contract's state.
     * @dev The migration EXCLUDES accumulated fees.
     */
    function migrateLockedTokens(address _to) external onlyOwner {
        // @dev Block sending directly to the zero address.
        if (_to == address(0)) revert InvalidAddressZero();

        // @dev Do not include the fee balance in the migration.
        uint256 balance = innerToken.balanceOf(address(this)) - feeBalance;

        innerToken.safeTransfer(_to, balance);
        emit LockedTokensMigrated(_to, balance);
    }

    /**
     * @dev Locks tokens from the sender's specified balance in this contract.
     * @param _from The address to debit from.
     * @param _amountLD The amount of tokens to send in local decimals.
     * @param _minAmountLD The minimum amount to send in local decimals.
     * @param _dstEid The destination chain ID.
     * @return amountSentLD The amount sent in local decimals.
     * @return amountReceivedLD The amount received in local decimals on the remote.
     *
     * @dev msg.sender will need to approve this _amountLD of tokens to be locked inside of the contract.
     * @dev WARNING: The default OFTAdapter implementation assumes LOSSLESS transfers, ie. 1 token in, 1 token out.
     * IF the 'innerToken' applies something like a transfer fee, the default will NOT work...
     * a pre/post balance check will need to be done to calculate the amountReceivedLD.
     */
    function _debit(
        address _from,
        uint256 _amountLD,
        uint256 _minAmountLD,
        uint32 _dstEid
    ) internal override returns (uint256 amountSentLD, uint256 amountReceivedLD) {
        (amountSentLD, amountReceivedLD) = _debitView(_amountLD, _minAmountLD, _dstEid);

        // @dev We are using amountReceivedLD because that is the amount of tokens leaving the chain.
        // @dev The fee remains on this chain, thus it is not included in the rate limit check.
        _checkAndUpdateRateLimit(_dstEid, amountReceivedLD, RateLimitDirection.Outbound);

        // @dev Lock tokens by moving them into this contract from the caller.
        innerToken.safeTransferFrom(_from, address(this), amountSentLD);

        // @dev Conditionally handle the fee.
        uint256 fee = amountSentLD - amountReceivedLD;
        if (fee > 0) feeBalance += fee;
    }

    /**
     * @notice Transfers tokens to the recipient.
     * @param _to The address to credit the tokens to.
     * @param _amountLD The amount of tokens to credit in local decimals.
     * @param _srcEid The source Endpoint ID.
     *
     * @return amountReceivedLD The amount of tokens ACTUALLY received in local decimals.
     */
    function _credit(
        address _to,
        uint256 _amountLD,
        uint32 _srcEid
    ) internal virtual override whenNotPaused returns (uint256 amountReceivedLD) {
        // @dev Check and update the rate limit based on the source endpoint ID (srcEid).
        _checkAndUpdateRateLimit(_srcEid, _amountLD, RateLimitDirection.Inbound);

        // @dev If recipient is the zero address or the inner token, reroute to the dead address.
        if (_to == address(0) || _to == token()) _to = address(0xdead);
        
        // @dev Unlock the tokens and transfer to the recipient.
        innerToken.safeTransfer(_to, _amountLD);

        return _amountLD;
    }
}
SkyOFTAdapterMintBurn.sol 116 lines
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.22;

import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

import { IMintBurnVoidReturn } from "./interfaces/IMintBurnVoidReturn.sol";
import { SkyOFTCore, RateLimitDirection } from "./SkyOFTCore.sol";

/**
 * @title SkyOFTAdapterMintBurn
 * @notice A variant of the standard OFT Adapter that uses an existing ERC20's mint and burn for cross-chain transfers.
 * @dev This contract needs mint permissions on the token.
 * @dev This contract burns the tokens from the sender's balance and transfers in the fee.
 *
 * @dev This contract extends the SkyOFTCore, which extends the SkyRateLimiter containing rate limiting functionality.
 * @dev It allows for the configuration of rate limits for both outbound and inbound directions.
 * @dev It also allows for the setting of the rate limit accounting type to be net or gross.
 */
contract SkyOFTAdapterMintBurn is SkyOFTCore {
    using SafeERC20 for IERC20;

    /**
     * @notice Initializes the SkyOFTAdapterMintBurn contract.
     *
     * @param _token The address of the underlying ERC20 token.
     * @param _lzEndpoint The LayerZero endpoint address.
     * @param _delegate The address of the delegate.
     */
    constructor(
        address _token,
        address _lzEndpoint,
        address _delegate
    ) SkyOFTCore(_token, _lzEndpoint, _delegate) {}

    /**
     * @notice Returns the balance of fees accumulated in the contract.
     * @return amountLD The balance of fees in local decimals.
     *
     * @dev This function is used to check the fee balance before withdrawal.
     */
    function feeBalance() public view returns (uint256 amountLD) {
        return innerToken.balanceOf(address(this));
    }

    /**
     * @notice Withdraws accumulated fees to a specified address.
     * @param _to The address to which the fees will be withdrawn.
     * @param _amountLD The amount of tokens to withdraw in local decimals.
     *
     * @dev This also allows for owner to rescue tokens that are otherwise burned/lost.
     */
    function withdrawFees(address _to, uint256 _amountLD) external onlyOwner {
        uint256 balance = feeBalance();
        if (_amountLD > balance) revert InsufficientFeeBalance(_amountLD, balance);

        innerToken.safeTransfer(_to, _amountLD);
        emit FeesWithdrawn(_to, _amountLD);
    }

    /**
     * @notice Burns tokens from the sender's balance to prepare for sending.
     *
     * @param _from The address to debit the tokens from.
     * @param _amountLD The amount of tokens to send in local decimals.
     * @param _minAmountLD The minimum amount to send in local decimals.
     * @param _dstEid The destination chain ID.
     *
     * @return amountSentLD The amount sent in local decimals.
     * @return amountReceivedLD The amount received in local decimals on the remote.
     */
    function _debit(
        address _from,
        uint256 _amountLD,
        uint256 _minAmountLD,
        uint32 _dstEid
    ) internal override returns (uint256 amountSentLD, uint256 amountReceivedLD) {
        (amountSentLD, amountReceivedLD) = _debitView(_amountLD, _minAmountLD, _dstEid);

        // @dev We are using amountReceivedLD because that is the amount of tokens leaving the chain.
        // @dev The fee remains on this chain, thus it is not included in the rate limit check.
        _checkAndUpdateRateLimit(_dstEid, amountReceivedLD, RateLimitDirection.Outbound);

        // @dev Burn the total amount sent, and mint the difference (i.e. the fee) to this contract.
        IMintBurnVoidReturn(token()).burn(_from, amountSentLD);

        // @dev Conditionally handle the fee.
        uint256 fee = amountSentLD - amountReceivedLD;
        if (fee > 0) IMintBurnVoidReturn(token()).mint(address(this), fee);
    }

    /**
     * @notice Mints tokens to the recipient.
     * @param _to The address to credit the tokens to.
     * @param _amountLD The amount of tokens to credit in local decimals.
     * @param _srcEid The source Endpoint ID.
     *
     * @return amountReceivedLD The amount of tokens actually received in local decimals.
     */
    function _credit(
        address _to,
        uint256 _amountLD,
        uint32 _srcEid
    ) internal virtual override whenNotPaused returns (uint256 amountReceivedLD) {
        // @dev Check and update the rate limit based on the source endpoint ID (srcEid).
        _checkAndUpdateRateLimit(_srcEid, _amountLD, RateLimitDirection.Inbound);

        // @dev If recipient is the zero address or the inner token, reroute to the dead address.
        if (_to == address(0) || _to == token()) _to = address(0xdead);

        // @dev Mints the tokens to the recipient.
        IMintBurnVoidReturn(token()).mint(_to, _amountLD);

        return _amountLD;
    }
}
SkyOFTCore.sol 211 lines
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.22;

import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20, IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

import { Fee } from "@layerzerolabs/oft-evm/contracts/Fee.sol";
import { OFTCore, SendParam, OFTLimit, OFTFeeDetail, OFTReceipt } from "@layerzerolabs/oft-evm/contracts/OFTCore.sol";

import { ISkyOFT } from "./interfaces/ISkyOFT.sol";
import {
    RateLimitConfig,
    RateLimitDirection,
    RateLimitAccountingType,
    SkyRateLimiter
} from "./SkyRateLimiter.sol";

/**
 * @title SkyOFTCore
 * @notice The SkyOFTCore contract, which manages cross-chain transfer rate limits and fees.
 * @dev This contracts defines the core functionalities of the SkyOFT system, including rate limit management,
 * pauser management, and fee withdrawal.
 */
abstract contract SkyOFTCore is ISkyOFT, OFTCore, SkyRateLimiter, Fee, Pausable {
    using SafeERC20 for IERC20;

    mapping(address pauser => bool canPause) public pausers;

    IERC20 internal immutable innerToken;

    /**
     * @notice Initializes the SkyOFTCore contract.
     *
     * @param _token The address of the underlying ERC20 token.
     * @param _lzEndpoint The LayerZero endpoint address.
     * @param _delegate The address of the delegate.
     */
    constructor(
        address _token,
        address _lzEndpoint,
        address _delegate
    ) OFTCore(IERC20Metadata(_token).decimals(), _lzEndpoint, _delegate) Ownable(_delegate){
        innerToken = IERC20(_token);
    }

    /**
     * @dev Retrieves the address of the underlying ERC20 implementation.
     * @return The address of the adapted ERC20 token.
     *
     * @dev In the case of OFTAdapter, address(this) and ERC20 are NOT the same contract.
     */
    function token() public view returns (address) {
        return address(innerToken);
    }

    /**
     * @notice Indicates whether the OFT contract requires approval of the 'token()' to send.
     * @return requiresApproval Needs approval of the underlying token implementation.
     */
    function approvalRequired() external pure virtual override returns (bool requiresApproval) {
        return true;
    }

    /**
     * @notice Provides the fee breakdown and settings data for an OFT. Unused in the default implementation.
     * @param _sendParam The parameters for the send operation.
     * @return oftLimit The OFT limit information.
     * @return oftFeeDetails The details of OFT fees.
     * @return oftReceipt The OFT receipt information.
     */
    function quoteOFT(
        SendParam calldata _sendParam
    )
        external
        view
        virtual
        override
        returns (OFTLimit memory oftLimit, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory oftReceipt)
    {
        uint256 minAmountLD = 0;
        (/*uint256 currentAmountInFlight*/, uint256 maxAmountLD) = getAmountCanBeSent(_sendParam.dstEid);
        oftLimit = OFTLimit(minAmountLD, maxAmountLD);

        // @dev This is the same as the send() operation, but without the actual send.
        // - amountSentLD is the amount in local decimals that would be sent from the sender.
        // - amountReceivedLD is the amount in local decimals that will be credited to the recipient on the remote OFT.
        // @dev The amountSentLD MIGHT not equal the amount the user actually receives. HOWEVER, the default does.
        (uint256 amountSentLD, uint256 amountReceivedLD) = _debitView(
            _sendParam.amountLD,
            _sendParam.minAmountLD,
            _sendParam.dstEid
        );
        oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD);

        // Return empty array if no fee is charged, otherwise include fee details.
        if (amountSentLD == amountReceivedLD) {
            oftFeeDetails = new OFTFeeDetail[](0);
        } else {
            oftFeeDetails = new OFTFeeDetail[](1);
            oftFeeDetails[0] = OFTFeeDetail(
                int256(amountSentLD - amountReceivedLD), // The fee amount in local decimals.
                'SkyOFT: cross-chain transfer fee' // Fee description.
            );
        }
    }

    /**
     * @notice Sets the cross-chain tx rate limits for specific endpoints based on provided configurations.
     * It allows configuration of rate limits either for outbound and inbound directions.
     * This method is designed to be called by contract admins for updating the system's rate limiting behavior.
     * 
     * @notice WARNING: Changing rate limits without first calling resetRateLimits() MIGHT result in unexpected behavior.
     * DYOR on Rate Limits across every VM to ensure compatibility.
     * Especially consider inflight decay rates when reducing limits.
     * 
     * @param _rateLimitConfigsInbound Array of INBOUND `RateLimitConfig` structs that specify new rate limit settings.
     * @param _rateLimitConfigsOutbound Array of OUTBOUND `RateLimitConfig` structs that specify new rate limit settings.
     *
     * @dev Each struct includes an endpoint ID, the limit value, and the window duration.
     * @dev The direction (inbound or outbound) specifies whether the eid passed should be considered a srcEid or dstEid.
     */
    function setRateLimits(
        RateLimitConfig[] calldata _rateLimitConfigsInbound,
        RateLimitConfig[] calldata _rateLimitConfigsOutbound
    ) external onlyOwner {
        _setRateLimits(_rateLimitConfigsInbound, RateLimitDirection.Inbound);
        _setRateLimits(_rateLimitConfigsOutbound, RateLimitDirection.Outbound);
    }

    /**
     * @notice Resets the rate limits for the given endpoint ids.
     * @param _eidsInbound The endpoint ids to reset the rate limits for inbound.
     * @param _eidsOutbound The endpoint ids to reset the rate limits for outbound.
     */
    function resetRateLimits(uint32[] calldata _eidsInbound, uint32[] calldata _eidsOutbound) external onlyOwner {
        _resetRateLimits(_eidsInbound, RateLimitDirection.Inbound);
        _resetRateLimits(_eidsOutbound, RateLimitDirection.Outbound);
    }

    /**
     * @notice Sets the rate limit accounting type.
     * @param _rateLimitAccountingType The new rate limit accounting type.
     * @dev You may want to call `resetRateLimits` after changing the rate limit accounting type.
     */
    function setRateLimitAccountingType(RateLimitAccountingType _rateLimitAccountingType) external onlyOwner {
        _setRateLimitAccountingType(_rateLimitAccountingType);
    }

    /**
     * @notice Sets the pauser status for a given address.
     * @param _pauser The address to set the pauser status for.
     * @param _canPause Boolean indicating ability to pause cross-chain transfers.
     */
    function setPauser(address _pauser, bool _canPause) public onlyOwner {
        // @dev Perform an idempotency check to prevent unnecessary state changes.
        // @dev Also prevents redundant event emissions.
        if (pausers[_pauser] == _canPause) revert PauserIdempotent(_pauser);

        pausers[_pauser] = _canPause;
        emit PauserSet(_pauser, _canPause);
    }

    /**
     * @notice Pauses the contract if the caller is a pauser.
     * @dev Only pausers can pause the contract.
     */
    function pause() external {
        if (!pausers[msg.sender]) revert OnlyPauser(msg.sender);
        _pause();
    }

    /**
     * @notice Unpauses the contract.
     * @dev Only the owner can unpause the contract.
     */
    function unpause() external onlyOwner {
        _unpause();
    }

    /**
     * @dev Internal function to mock the amount mutation from a OFT debit() operation.
     * @param _amountLD The amount to send in local decimals.
     * @param _minAmountLD The minimum amount to send in local decimals.
     * @param _dstEid The destination endpoint ID.
     * @return amountSentLD The amount sent, in local decimals.
     * @return amountReceivedLD The amount to be received on the remote chain, in local decimals.
     *
     * @dev This function applies the fee to the amount, removes dust, and checks for slippage.
     * @dev This view function will revert if cross-chain transfers are paused.
     */
    function _debitView(
        uint256 _amountLD,
        uint256 _minAmountLD,
        uint32 _dstEid
    ) internal view virtual override whenNotPaused returns (uint256 amountSentLD, uint256 amountReceivedLD) {
        amountSentLD = _amountLD;

        // @dev Apply the fee, then de-dust the amount afterwards.
        // This means the fee is taken from the amount before the dust is removed.
        uint256 fee = getFee(_dstEid, _amountLD);
        // @dev The fee technically also includes the dust.
        amountReceivedLD = _removeDust(_amountLD - fee);

        // @dev Check for slippage.
        if (amountReceivedLD < _minAmountLD) {
            revert SlippageExceeded(amountReceivedLD, _minAmountLD);
        }
    }
} 
SkyRateLimiter.sol 219 lines
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.22;

import {
    RateLimit,
    RateLimitConfig,
    RateLimitDirection,
    RateLimitAccountingType,
    ISkyRateLimiter
} from "./interfaces/ISkyRateLimiter.sol";

/**
 * @title SkyRateLimiter
 * @dev Abstract contract for implementing net and gross rate limiting functionality.
 * @dev Toggle between net and gross accounting by calling `_setRateLimitAccountingType`.
 * ---------------------------------------------------------------------------------------------------------------------
 * Net accounting allows two operations to offset each other's net impact (e.g., inflow v.s. outflow of assets).
 * A flexible rate limit that grows during congestive periods and shrinks during calm periods could give some
 * leeway when someone tries to forcefully congest the network, while still preventing huge amounts to be sent at once.
 * ---------------------------------------------------------------------------------------------------------------------
 * Gross accounting does not allow any offsetting and will revert if the amount to be sent or received,
 * is greater than the available capacity.
 * Designed to be inherited by other contracts requiring rate limiting to protect resources/services from excessive use.
 */
abstract contract SkyRateLimiter is ISkyRateLimiter {
    RateLimitAccountingType public rateLimitAccountingType;

    // Tracks rate limits for outbound transactions to a dstEid.
    mapping(uint32 dstEid => RateLimit) public outboundRateLimits;
    // Tracks rate limits for inbound transactions from a srcEid.
    mapping(uint32 srcEid => RateLimit) public inboundRateLimits;

    /**
     * @notice Get the current amount that can be sent to this destination endpoint id for the given rate limit window.
     * @param _dstEid The destination endpoint id.
     * @return currentAmountInFlight The current amount that was sent in this window.
     * @return amountCanBeSent The amount that can be sent.
     */
    function getAmountCanBeSent(
        uint32 _dstEid
    ) public view virtual returns (uint256 currentAmountInFlight, uint256 amountCanBeSent) {
        RateLimit storage orl = outboundRateLimits[_dstEid];
        return _amountCanBeSent(orl.amountInFlight, orl.lastUpdated, orl.limit, orl.window);
    }

    /**
     * @notice Get the current amount that can be received from the source endpoint id for the given rate limit window.
     * @param _srcEid The source endpoint id.
     * @return currentAmountInFlight The current amount that has been received in this window.
     * @return amountCanBeReceived The amount that can be received.
     */
    function getAmountCanBeReceived(
        uint32 _srcEid
    ) public view virtual returns (uint256 currentAmountInFlight, uint256 amountCanBeReceived) {
        RateLimit storage irl = inboundRateLimits[_srcEid];
        return _amountCanBeReceived(irl.amountInFlight, irl.lastUpdated, irl.limit, irl.window);
    }

    /**
     * @notice Sets the rate limits.
     * @param _rateLimitConfigs A `RateLimitConfig[]` array representing the rate limit configurations.
     * @param _direction Indicates whether the rate limits being set are for outbound or inbound.
     */
    function _setRateLimits(RateLimitConfig[] memory _rateLimitConfigs, RateLimitDirection _direction) internal virtual {
        unchecked {
            for (uint256 i = 0; i < _rateLimitConfigs.length; i++) {
                RateLimit storage rateLimit = _direction == RateLimitDirection.Outbound
                    ? outboundRateLimits[_rateLimitConfigs[i].eid]
                    : inboundRateLimits[_rateLimitConfigs[i].eid];

                // Checkpoint the existing rate limit to not retroactively apply the new decay rate.
                _checkAndUpdateRateLimit(_rateLimitConfigs[i].eid, 0, _direction);

                // Does NOT reset the amountInFlight/lastUpdated of an existing rate limit.
                rateLimit.limit = _rateLimitConfigs[i].limit;
                rateLimit.window = _rateLimitConfigs[i].window;
            }
        }
        emit RateLimitsChanged(_rateLimitConfigs, _direction);
    }

    /**
     * @notice Resets the rate limits (sets amountInFlight to 0) for the given endpoint ids.
     * @dev This is useful when the rate limit accounting type is changed.
     * @param _eids The endpoint ids to reset the rate limits for.
     * @param _direction The direction of the rate limits to reset.
     */
    function _resetRateLimits(uint32[] memory _eids, RateLimitDirection _direction) internal virtual {
        for (uint256 i = 0; i < _eids.length; i++) {
            RateLimit storage rateLimit = _direction == RateLimitDirection.Outbound
                ? outboundRateLimits[_eids[i]]
                : inboundRateLimits[_eids[i]];

            rateLimit.amountInFlight = 0;
            rateLimit.lastUpdated = uint128(block.timestamp);
        }
        emit RateLimitsReset(_eids, _direction);
    }

     /**
     * @notice Sets the rate limit accounting type.
     * @dev You may want to call `_resetRateLimits` after changing the rate limit accounting type.
     * @param _rateLimitAccountingType The new rate limit accounting type.
     */
    function _setRateLimitAccountingType(RateLimitAccountingType _rateLimitAccountingType) internal {
        rateLimitAccountingType = _rateLimitAccountingType;
        emit RateLimitAccountingTypeSet(_rateLimitAccountingType);
    }

    /**
     * @dev Calculates current amount in flight and the available capacity based on configuration and time elapsed.
     * Applies a linear decay to compute how much 'amountInFlight' remains based on the time elapsed since last update.
     * @param _amountInFlight The total amount that was in flight at the last update.
     * @param _lastUpdated The timestamp (in seconds) when the last update occurred.
     * @param _limit The maximum allowable amount within the specified window.
     * @param _window The time window (in seconds) for which the limit applies.
     *
     * @return currentAmountInFlight The decayed amount of in-flight based on the elapsed time since lastUpdated.
     * @return availableCapacity The amount of capacity available for new activity.
     * @dev If the time since lastUpdated exceeds the window:
     *      - currentAmountInFlight is 0.
     *      - availableCapacity is the full limit.
     */
    function _calculateDecay(
        uint256 _amountInFlight,
        uint128 _lastUpdated,
        uint256 _limit,
        uint48 _window
    ) internal view returns (uint256 currentAmountInFlight, uint256 availableCapacity) {
        uint256 timeSinceLastUpdate = block.timestamp - _lastUpdated;
        if (timeSinceLastUpdate >= _window) {
            return (0, _limit);
        } else {
            uint256 decay = (_limit * timeSinceLastUpdate) / _window;
            currentAmountInFlight = _amountInFlight > decay ? _amountInFlight - decay : 0;
            availableCapacity = _limit > currentAmountInFlight ? _limit - currentAmountInFlight : 0;
        }
    }

    /**
     * @notice Checks current amount in flight and amount that can be sent for a given rate limit window.
     * @param _amountInFlight The amount in the current window.
     * @param _lastUpdated Timestamp representing the last time the rate limit was checked or updated.
     * @param _limit This represents the maximum allowed amount within a given window.
     * @param _window Defines the duration of the rate limiting window.
     * @return currentAmountInFlight The amount in the current window.
     * @return amountCanBeSent The amount that can be sent.
     */
    function _amountCanBeSent(
        uint256 _amountInFlight,
        uint128 _lastUpdated,
        uint256 _limit,
        uint48 _window
    ) internal view virtual returns (uint256 currentAmountInFlight, uint256 amountCanBeSent) {
        (currentAmountInFlight, amountCanBeSent) = _calculateDecay(_amountInFlight, _lastUpdated, _limit, _window);
    }

    /**
     * @notice Checks current amount in flight and amount that can be received for a given rate limit window.
     * @param _amountInFlight The amount in the current window.
     * @param _lastUpdated Timestamp representing the last time the rate limit was checked or updated.
     * @param _limit This represents the maximum allowed amount within a given window.
     * @param _window Defines the duration of the rate limiting window.
     * @return currentAmountInFlight The amount in the current window.
     * @return amountCanBeReceived The amount that can be received.
     */
    function _amountCanBeReceived(
        uint256 _amountInFlight,
        uint128 _lastUpdated,
        uint256 _limit,
        uint48 _window
    ) internal view virtual returns (uint256 currentAmountInFlight, uint256 amountCanBeReceived) {
        (currentAmountInFlight, amountCanBeReceived) = _calculateDecay(_amountInFlight, _lastUpdated, _limit, _window);
    }
    
    /**
     * @notice Checks and updates the rate limit based on the endpoint ID and amount.
     * @param _eid The endpoint ID for which the rate limit needs to be checked and updated.
     * @param _amount The amount to add to the current amount in flight.
     * @param _direction The direction (inbound or outbound) of the rate limits being checked.
     */
    function _checkAndUpdateRateLimit(uint32 _eid, uint256 _amount, RateLimitDirection _direction) internal {
        // Select the correct mapping based on the direction of the rate limit
        RateLimit storage rl = _direction == RateLimitDirection.Outbound
            ? outboundRateLimits[_eid]
            : inboundRateLimits[_eid];

        // Calculate current amount in flight and available capacity
        (uint256 currentAmountInFlight, uint256 availableCapacity) = _calculateDecay(
            rl.amountInFlight,
            rl.lastUpdated,
            rl.limit,
            rl.window
        );

        // Check if the requested amount exceeds the available capacity
        if (_amount > availableCapacity) revert RateLimitExceeded();

        // Update the rate limit with the new amount in flight and the current timestamp
        rl.amountInFlight = currentAmountInFlight + _amount;
        rl.lastUpdated = uint128(block.timestamp);

        if (rateLimitAccountingType == RateLimitAccountingType.Net) {
            RateLimit storage oppositeRL = _direction == RateLimitDirection.Outbound
                ? inboundRateLimits[_eid]
                : outboundRateLimits[_eid];
            (uint256 otherCurrentAmountInFlight,) = _calculateDecay(
                oppositeRL.amountInFlight,
                oppositeRL.lastUpdated,
                oppositeRL.limit,
                oppositeRL.window
            );
            unchecked {
                oppositeRL.amountInFlight = otherCurrentAmountInFlight > _amount ? otherCurrentAmountInFlight - _amount : 0;
            }
            oppositeRL.lastUpdated = uint128(block.timestamp);
        }
    }
}

Read Contract

BPS_DENOMINATOR 0xe1a45218 → uint16
SEND 0x1f5e1334 → uint16
SEND_AND_CALL 0x134d4f25 → uint16
allowInitializePath 0xbfe94e81 → bool
approvalRequired 0x9f68b964 → bool
combineOptions 0xbc70b354 → bytes
decimalConversionRate 0x963efcaa → uint256
defaultFeeBps 0xbcae25a4 → uint16
endpoint 0x5e280f11 → address
enforcedOptions 0x5535d461 → bytes
feeBalance 0x60b71d4e → uint256
feeBps 0x3194c180 → uint16, bool
getAmountCanBeReceived 0x703d3768 → uint256, uint256
getAmountCanBeSent 0xc272198d → uint256, uint256
getFee 0x5bf9c226 → uint256
inboundRateLimits 0x55b56c0c → uint128, uint48, uint256, uint256
isComposeMsgSender 0x8833c245 → bool
isPeer 0x5a0dfe4d → bool
msgInspector 0x111ecdad → address
nextNonce 0x7d25a05e → uint64
oApp 0x52ae2879 → address
oAppVersion 0x17442b70 → uint64, uint64
oftVersion 0x156a0d0f → bytes4, uint64
outboundRateLimits 0x51c32a88 → uint128, uint48, uint256, uint256
owner 0x8da5cb5b → address
paused 0x5c975abb → bool
pausers 0x80f51c12 → bool
peers 0xbb0b6a53 → bytes32
preCrime 0xb731ea0a → address
quoteOFT 0xe6343d44 → tuple, tuple[], tuple
quoteSend 0x2f603a24 → tuple
rateLimitAccountingType 0x44b00256 → uint8
sharedDecimals 0x857749b0 → uint8
token 0xfc0c546a → address

Write Contract 21 functions

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

lzReceive 0xbf282d99
tuple _origin
bytes32 _guid
bytes _message
address _executor
bytes _extraData
lzReceiveAndRevert 0x215f7f2f
tuple[] _packets
lzReceiveSimulate 0xa454778b
tuple _origin
bytes32 _guid
bytes _message
address _executor
bytes _extraData
migrateLockedTokens 0x81bde774
address _to
pause 0x8456cb59
No parameters
renounceOwnership 0x715018a6
No parameters
resetRateLimits 0xaeebf207
uint32[] _eidsInbound
uint32[] _eidsOutbound
send 0xccfc9451
tuple _sendParam
tuple _fee
address _refundAddress
returns: tuple, tuple
setDefaultFeeBps 0x4488b652
uint16 _feeBps
setDelegate 0xca5eb5e1
address _delegate
setEnforcedOptions 0xd833f371
tuple[] _enforcedOptions
setFeeBps 0x6db7bcdb
uint32 _dstEid
uint16 _feeBps
bool _enabled
setMsgInspector 0x6fc1b31e
address _msgInspector
setPauser 0x7180c8ca
address _pauser
bool _canPause
setPeer 0x3400288b
uint32 _eid
bytes32 _peer
setPreCrime 0xd4243885
address _preCrime
setRateLimitAccountingType 0x75f1b82c
uint8 _rateLimitAccountingType
setRateLimits 0x5723b7ee
tuple[] _rateLimitConfigsInbound
tuple[] _rateLimitConfigsOutbound
transferOwnership 0xf2fde38b
address newOwner
unpause 0x3f4ba83a
No parameters
withdrawFees 0xad3b1b47
address _to
uint256 _amountLD

Top Interactions

AddressTxnsSentReceived
0x99298b15...Ce39 1 1

Recent Transactions

CSV
|
Hash Method Block Age From/To Value Txn Fee Type
0xa9970dbb...eaad94 0xc7c7f5b3 24,427,637 IN 0x99298b15...Ce39 0.000221425 ETH EIP-1559