Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0x934635de453A1161D02Ce395F2F59E775597fE13
Balance 0 ETH
Nonce 1
Code Size 13351 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

13351 bytes
0x608060405234801561000f575f80fd5b506004361061017e575f3560e01c806301ffc9a714610182578063181f5a77146101aa57806321df0da7146101ed578063240028e81461021c57806324f65ee71461025c578063390775371461028d5780634c5ef0ed146102af57806354c8a4f3146102c257806362ddd3c4146102d75780636d3d1a58146102ea578063715018a6146102fb57806379ba5097146103035780637d54534e1461030b5780638926f54f1461031e5780638da5cb5b14610331578063962d4020146103395780639a4575b91461034c578063a42a7b8b1461036c578063a7cd63b71461038c578063acfecf91146103a1578063af58d59f146103b4578063b0f479a11461041a578063b79465801461042b578063c0d786551461043e578063c4bffe2b14610451578063c75eea9c14610466578063cf7401f314610479578063dc0bd9711461048c578063e0351e13146104b2578063e30c3978146104d8578063e8a1da17146104e0578063f2fde38b146104f3575b5f80fd5b61019561019036600461276d565b610506565b60405190151581526020015b60405180910390f35b6101e0604051806040016040528060178152602001764275726e4d696e74546f6b656e506f6f6c20312e352e3160481b81525081565b6040516101a191906127d7565b7f0000000000000000000000005e53aebe377efc92213514ec07f8ef3af426dd1d5b6040516101a191906127e9565b61019561022a366004612811565b7f0000000000000000000000005e53aebe377efc92213514ec07f8ef3af426dd1d6001600160a01b0390811691161490565b60405160ff7f00000000000000000000000000000000000000000000000000000000000000121681526020016101a1565b6102a061029b36600461282c565b610557565b604051905181526020016101a1565b6101956102bd36600461287e565b6106d2565b6102d56102d0366004612940565b610719565b005b6102d56102e536600461287e565b610792565b6009546001600160a01b031661020f565b6102d561080f565b6102d5610822565b6102d5610319366004612811565b610861565b61019561032c3660046129a6565b6108bf565b61020f6108d4565b6102d56103473660046129ff565b6108e2565b61035f61035a366004612a91565b6109fd565b6040516101a19190612ac7565b61037f61037a3660046129a6565b610ad6565b6040516101a19190612aff565b610394610c38565b6040516101a19190612b61565b6102d56103af36600461287e565b610c49565b6103c76103c23660046129a6565b610d22565b6040516101a1919081516001600160801b03908116825260208084015163ffffffff1690830152604080840151151590830152606080840151821690830152608092830151169181019190915260a00190565b6004546001600160a01b031661020f565b6101e06104393660046129a6565b610dab565b6102d561044c366004612811565b610e57565b610459610ee7565b6040516101a19190612bad565b6103c76104743660046129a6565b610f9a565b6102d5610487366004612cea565b611020565b7f000000000000000000000000411de17f12d1a34ecc7f45f49844626267c75e8161020f565b7f0000000000000000000000000000000000000000000000000000000000000000610195565b61020f61107f565b6102d56104ee366004612940565b61108e565b6102d5610501366004612811565b6114a8565b5f6001600160e01b0319821663aff2afbf60e01b148061053657506001600160e01b03198216630e64dd2960e01b145b8061055157506001600160e01b031982166301ffc9a760e01b145b92915050565b60408051602081019091525f815261056e8261150e565b5f6105c560608401356105c061058760c0870187612d2c565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525061169492505050565b611723565b90506001600160a01b037f0000000000000000000000005e53aebe377efc92213514ec07f8ef3af426dd1d166340c10f196106066060860160408701612811565b6040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602481018490526044015f604051808303815f87803b15801561064b575f80fd5b505af115801561065d573d5f803e3d5ffd5b50610672925050506060840160408501612811565b6001600160a01b0316336001600160a01b03167f9d228d69b5fdb8d273a2336f8fb8612d039631024ea9bf09c424a9503aa078f0836040516106b691815260200190565b60405180910390a3604080516020810190915290815292915050565b5f61071183836040516106e6929190612d6e565b60408051918290039091206001600160401b0387165f908152600760205291909120600501906118c7565b949350505050565b6107216118d9565b61078c8484808060200260200160405190810160405280939291908181526020018383602002808284375f92019190915250506040805160208088028281018201909352878252909350879250869182918501908490808284375f9201919091525061190b92505050565b50505050565b61079a6118d9565b6107a3836108bf565b6107cb5782604051631e670e4b60e01b81526004016107c29190612d7d565b60405180910390fd5b61080a8383838080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250611a6592505050565b505050565b6108176118d9565b6108205f611b28565b565b338061082c61107f565b6001600160a01b031614610855578060405163118cdaa760e01b81526004016107c291906127e9565b61085e81611b28565b50565b6108696118d9565b600980546001600160a01b0319166001600160a01b0383161790556040517f44676b5284b809a22248eba0da87391d79098be38bb03154be88a58bf4d09174906108b49083906127e9565b60405180910390a150565b5f61055160056001600160401b0384166118c7565b5f546001600160a01b031690565b6009546001600160a01b0316331480159061091657506109006108d4565b6001600160a01b0316336001600160a01b031614155b15610936573360405163472511eb60e11b81526004016107c291906127e9565b84831415806109455750848114155b1561096357604051632b477e7160e11b815260040160405180910390fd5b5f5b858110156109f4576109ec87878381811061098257610982612d91565b905060200201602081019061099791906129a6565b8686848181106109a9576109a9612d91565b9050606002018036038101906109bf9190612da5565b8585858181106109d1576109d1612d91565b9050606002018036038101906109e79190612da5565b611b41565b600101610965565b50505050505050565b6040805180820190915260608082526020820152610a1a82611c02565b610a278260600135611d3a565b6040516060830135815233907f696de425f79f4a40bc6d2122ca50507f0efbeabbff86a84871b7196ab8ea8df79060200160405180910390a26040518060400160405280610a8184602001602081019061043991906129a6565b8152602001610ace6040805160ff7f000000000000000000000000000000000000000000000000000000000000001216602082015260609101604051602081830303815290604052905090565b905292915050565b6001600160401b0381165f90815260076020526040812060609190610afd90600501611dab565b90505f81516001600160401b03811115610b1957610b19612bed565b604051908082528060200260200182016040528015610b4c57816020015b6060815260200190600190039081610b375790505b5090505f5b8251811015610c305760085f848381518110610b6f57610b6f612d91565b602002602001015181526020019081526020015f208054610b8f90612dbf565b80601f0160208091040260200160405190810160405280929190818152602001828054610bbb90612dbf565b8015610c065780601f10610bdd57610100808354040283529160200191610c06565b820191905f5260205f20905b815481529060010190602001808311610be957829003601f168201915b5050505050828281518110610c1d57610c1d612d91565b6020908102919091010152600101610b51565b509392505050565b6060610c446002611dab565b905090565b610c516118d9565b610c5a836108bf565b610c795782604051631e670e4b60e01b81526004016107c29190612d7d565b610cb78282604051610c8c929190612d6e565b60408051918290039091206001600160401b0386165f90815260076020529190912060050190611db7565b610cda57828282604051631d3c8f1f60e21b81526004016107c293929190612e1f565b826001600160401b03167f52d00ee4d9bd51b40168f2afc5848837288ce258784ad914278791464b3f4d768383604051610d15929190612e43565b60405180910390a2505050565b610d2a6126da565b6001600160401b0382165f90815260076020908152604091829020825160a08101845260028201546001600160801b038082168352600160801b80830463ffffffff1695840195909552600160a01b90910460ff16151594820194909452600390910154808416606083015291909104909116608082015261055190611dc2565b6001600160401b0381165f908152600760205260409020600401805460609190610dd490612dbf565b80601f0160208091040260200160405190810160405280929190818152602001828054610e0090612dbf565b8015610e4b5780601f10610e2257610100808354040283529160200191610e4b565b820191905f5260205f20905b815481529060010190602001808311610e2e57829003601f168201915b50505050509050919050565b610e5f6118d9565b6001600160a01b038116610e86576040516342bcdf7f60e11b815260040160405180910390fd5b600480546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527f02dc5c233404867c793b749c6d644beb2277536d18a7e7974d3f238e4c6f1684910160405180910390a15050565b60605f610ef46005611dab565b90505f81516001600160401b03811115610f1057610f10612bed565b604051908082528060200260200182016040528015610f39578160200160208202803683370190505b5090505f5b8251811015610f9357828181518110610f5957610f59612d91565b6020026020010151828281518110610f7357610f73612d91565b6001600160401b0390921660209283029190910190910152600101610f3e565b5092915050565b610fa26126da565b6001600160401b0382165f90815260076020908152604091829020825160a08101845281546001600160801b038082168352600160801b80830463ffffffff1695840195909552600160a01b90910460ff16151594820194909452600190910154808416606083015291909104909116608082015261055190611dc2565b6009546001600160a01b03163314801590611054575061103e6108d4565b6001600160a01b0316336001600160a01b031614155b15611074573360405163472511eb60e11b81526004016107c291906127e9565b61080a838383611b41565b6001546001600160a01b031690565b6110966118d9565b5f5b8381101561122e575f8585838181106110b3576110b3612d91565b90506020020160208101906110c891906129a6565b90506110de60056001600160401b038316611db7565b6110fd5780604051631e670e4b60e01b81526004016107c29190612d7d565b6001600160401b0381165f90815260076020526040812061112090600501611dab565b90505f5b81518110156111875761117e82828151811061114257611142612d91565b602002602001015160075f866001600160401b03166001600160401b031681526020019081526020015f20600501611db790919063ffffffff16565b50600101611124565b506001600160401b0382165f90815260076020526040812080546001600160a81b0319908116825560018201839055600282018054909116905560038101829055906111d66004830182612707565b600582015f81816111e7828261273e565b5050505050507f5204aec90a3c794d8e90fded8b46ae9c7c552803e7e832e0c1d358396d8599168260405161121c9190612d7d565b60405180910390a15050600101611098565b505f5b818110156114a1575f83838381811061124c5761124c612d91565b905060200281019061125e9190612e56565b61126790612ee0565b905061127781606001515f611e2c565b61128581608001515f611e2c565b8060400151515f036112aa576040516342bcdf7f60e11b815260040160405180910390fd5b80516112c1906005906001600160401b0316611ef1565b6112e1578051604051631d5ad3c560e01b81526107c29190600401612d7d565b80516001600160401b03165f90815260076020908152604091829020825160a08082018552606080870180518601516001600160801b0390811680865263ffffffff42168689018190528351511515878b0181905284518a0151841686890181905294518b0151841660809889018190528954600160a01b92830260ff60a01b19600160801b8087026001600160a01b031994851690981788178216929092178d5592810290971760018c01558c519889018d52898e0180518d01518716808b528a8e019590955280515115158a8f018190528151909d01518716988a01899052518d0151909516979098018790526002890180549a9091029990931617179094169590951790925590920290911760038201559082015160048201906114089082613042565b505f5b82602001515181101561144a57611442835f01518460200151838151811061143557611435612d91565b6020026020010151611a65565b60010161140b565b507f8d340f17e19058004c20453540862a9c62778504476f6756755cb33bcd6c38c2825f015183604001518460600151856080015160405161148f949392919061312b565b60405180910390a15050600101611231565b5050505050565b6114b06118d9565b600180546001600160a01b0319166001600160a01b0383169081179091556114d66108d4565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b61152161022a60a0830160808401612811565b61154f5761153560a0820160808301612811565b60405163961c9a4f60e01b81526004016107c291906127e9565b6001600160a01b037f000000000000000000000000411de17f12d1a34ecc7f45f49844626267c75e8116632cbc26bb61158e60408401602085016129a6565b6001600160401b031660801b6040518263ffffffff1660e01b81526004016115b6919061316c565b602060405180830381865afa1580156115d1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115f59190613181565b1561161357604051630a75a23b60e31b815260040160405180910390fd5b61162b61162660408301602084016129a6565b611efc565b61164b61163e60408301602084016129a6565b6102bd60a0840184612d2c565b6116775761165c60a0820182612d2c565b6040516324eb47e560e01b81526004016107c2929190612e43565b61085e61168a60408301602084016129a6565b8260600135611fbd565b5f81515f036116c457507f0000000000000000000000000000000000000000000000000000000000000012919050565b81516020146116e8578160405163953576f760e01b81526004016107c291906127d7565b5f828060200190518101906116fd919061319c565b905060ff811115610551578260405163953576f760e01b81526004016107c291906127d7565b5f7f000000000000000000000000000000000000000000000000000000000000001260ff168260ff1603611758575081610551565b7f000000000000000000000000000000000000000000000000000000000000001260ff168260ff16111561181b575f6117b17f0000000000000000000000000000000000000000000000000000000000000012846131c7565b9050604d8160ff1611156117fe57827f00000000000000000000000000000000000000000000000000000000000000128560405163a9cb113d60e01b81526004016107c2939291906131e0565b61180981600a6132de565b61181390856132ec565b915050610551565b5f611846837f00000000000000000000000000000000000000000000000000000000000000126131c7565b9050604d8160ff16118061186e575061186081600a6132de565b61186b905f196132ec565b84115b156118b257827f00000000000000000000000000000000000000000000000000000000000000128560405163a9cb113d60e01b81526004016107c2939291906131e0565b6118bd81600a6132de565b610711908561330b565b5f6118d28383612002565b9392505050565b336118e26108d4565b6001600160a01b031614610820573360405163118cdaa760e01b81526004016107c291906127e9565b7f0000000000000000000000000000000000000000000000000000000000000000611949576040516335f4a7b360e01b815260040160405180910390fd5b5f5b82518110156119cb575f83828151811061196757611967612d91565b6020026020010151905061198581600261201990919063ffffffff16565b156119c2577f800671136ab6cfee9fbe5ed1fb7ca417811aca3cf864800d127b927adedf7566816040516119b991906127e9565b60405180910390a15b5060010161194b565b505f5b815181101561080a575f8282815181106119ea576119ea612d91565b602002602001015190505f6001600160a01b0316816001600160a01b031603611a135750611a5d565b611a1e60028261202d565b15611a5b577f2640d4d76caf8bf478aabfa982fa4e1c4eb71a37f93cd15e80dbc657911546d881604051611a5291906127e9565b60405180910390a15b505b6001016119ce565b80515f03611a86576040516342bcdf7f60e11b815260040160405180910390fd5b80516020808301919091206001600160401b0384165f90815260079092526040909120611ab69060050182611ef1565b611ad7578282604051631c9dc56960e11b81526004016107c2929190613322565b5f818152600860205260409020611aee8382613042565b50826001600160401b03167f7d628c9a1796743d365ab521a8b2a4686e419b3269919dc9145ea2ce853b54ea83604051610d1591906127d7565b600180546001600160a01b031916905561085e81612041565b611b4a836108bf565b611b695782604051631e670e4b60e01b81526004016107c29190612d7d565b611b73825f611e2c565b6001600160401b0383165f908152600760205260409020611b949083612090565b611b9e815f611e2c565b6001600160401b0383165f908152600760205260409020611bc29060020182612090565b7f0350d63aa5f270e01729d00d627eeb8f3429772b1818c016c66a588a864f912b838383604051611bf593929190613345565b60405180910390a1505050565b611c1561022a60a0830160808401612811565b611c295761153560a0820160808301612811565b6001600160a01b037f000000000000000000000000411de17f12d1a34ecc7f45f49844626267c75e8116632cbc26bb611c6860408401602085016129a6565b6001600160401b031660801b6040518263ffffffff1660e01b8152600401611c90919061316c565b602060405180830381865afa158015611cab573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ccf9190613181565b15611ced57604051630a75a23b60e31b815260040160405180910390fd5b611d05611d006060830160408401612811565b61219c565b611d1d611d1860408301602084016129a6565b6121ec565b61085e611d3060408301602084016129a6565b82606001356122b5565b604051630852cd8d60e31b8152600481018290527f0000000000000000000000005e53aebe377efc92213514ec07f8ef3af426dd1d6001600160a01b0316906342966c68906024015f604051808303815f87803b158015611d99575f80fd5b505af11580156114a1573d5f803e3d5ffd5b60605f6118d2836122f7565b5f6118d2838361234f565b611dca6126da565b611e1182606001516001600160801b0316835f01516001600160801b0316846020015163ffffffff1642611dfe919061336f565b85608001516001600160801b0316612432565b6001600160801b031682525063ffffffff4216602082015290565b815115611eaa5781602001516001600160801b031682604001516001600160801b0316101580611e67575060408201516001600160801b0316155b15611e875781604051632008344960e21b81526004016107c29190613382565b8015611ea65760405163433fc33d60e01b815260040160405180910390fd5b5050565b60408201516001600160801b0316151580611ed1575060208201516001600160801b031615155b15611ea657816040516335a2be7360e21b81526004016107c29190613382565b5f6118d28383612459565b611f05816108bf565b611f2457806040516354c8163f60e11b81526004016107c29190612d7d565b600480546040516383826b2b60e01b81526001600160401b038416928101929092523360248301526001600160a01b0316906383826b2b90604401602060405180830381865afa158015611f7a573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f9e9190613181565b61085e573360405163728fe07b60e01b81526004016107c291906127e9565b6001600160401b0382165f908152600760205260409020611ea690600201827f0000000000000000000000005e53aebe377efc92213514ec07f8ef3af426dd1d6124a0565b5f9081526001919091016020526040902054151590565b5f6118d2836001600160a01b03841661234f565b5f6118d2836001600160a01b038416612459565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b81545f906120ab90600160801b900463ffffffff164261336f565b9050801561210957600183015483546120dd916001600160801b03808216928116918591600160801b90910416612432565b83546001600160801b03919091166001600160a01b031990911617600160801b4263ffffffff16021783555b60208201518354612126916001600160801b0390811691166126b1565b835483511515600160a01b02600164ff0000000160801b03199091166001600160801b039283161717845560208301516040808501518316600160801b0291909216176001850155517f9ea3374b67bf275e6bb9c8ae68f9cae023e1c528b4b27e092f0bb209d3531c1990611bf5908490613382565b7f00000000000000000000000000000000000000000000000000000000000000001561085e576121cd6002826126c6565b61085e57806040516368692cbb60e11b81526004016107c291906127e9565b6121f5816108bf565b61221457806040516354c8163f60e11b81526004016107c29190612d7d565b6004805460405163a8d87a3b60e01b81526001600160a01b039091169163a8d87a3b9161224391859101612d7d565b602060405180830381865afa15801561225e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906122829190613390565b6001600160a01b0316336001600160a01b03161461085e573360405163728fe07b60e01b81526004016107c291906127e9565b6001600160401b0382165f908152600760205260409020611ea690827f0000000000000000000000005e53aebe377efc92213514ec07f8ef3af426dd1d6124a0565b6060815f01805480602002602001604051908101604052809291908181526020018280548015610e4b57602002820191905f5260205f20905b8154815260200190600101908083116123305750505050509050919050565b5f8181526001830160205260408120548015612429575f61237160018361336f565b85549091505f906123849060019061336f565b90508082146123e3575f865f0182815481106123a2576123a2612d91565b905f5260205f200154905080875f0184815481106123c2576123c2612d91565b5f918252602080832090910192909255918252600188019052604090208390555b85548690806123f4576123f46133ab565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f905560019350505050610551565b5f915050610551565b5f61245085612441848661330b565b61244b90876133bf565b6126b1565b95945050505050565b5f6124648383612002565b61249957508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155610551565b505f610551565b8254600160a01b900460ff1615806124b6575081155b156124c057505050565b825460018401546001600160801b03808316929116905f906124ef90600160801b900463ffffffff164261336f565b9050801561255b578183111561251857604051634b92ca1560e11b815260040160405180910390fd5b600186015461253c90839085908490600160801b90046001600160801b0316612432565b865463ffffffff60801b1916600160801b4263ffffffff160217875592505b848210156125b3576001600160a01b0384166125945760405163f94ebcd160e01b815260048101839052602481018690526044016107c2565b818585604051630d3b2b9560e11b81526004016107c2939291906133d2565b8483101561265057600186810154600160801b90046001600160801b0316905f9082906125e0908261336f565b6125ea878a61336f565b6125f491906133bf565b6125fe91906132ec565b90506001600160a01b038616612631576040516302a4f38160e31b815260048101829052602481018690526044016107c2565b808587604051636864691d60e11b81526004016107c2939291906133d2565b61265a858461336f565b86546001600160801b0319166001600160801b0382161787556040518681529093507f1871cdf8010e63f2eb8384381a68dfa7416dc571a5517e66e88b2d2d0c0a690a9060200160405180910390a1505050505050565b5f8183106126bf57816118d2565b5090919050565b5f6118d2836001600160a01b038416612002565b6040805160a0810182525f8082526020820181905291810182905260608101829052608081019190915290565b50805461271390612dbf565b5f825580601f10612722575050565b601f0160209004905f5260205f209081019061085e9190612755565b5080545f8255905f5260205f209081019061085e91905b5b80821115612769575f8155600101612756565b5090565b5f6020828403121561277d575f80fd5b81356001600160e01b0319811681146118d2575f80fd5b5f81518084525f5b818110156127b85760208185018101518683018201520161279c565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f6118d26020830184612794565b6001600160a01b0391909116815260200190565b6001600160a01b038116811461085e575f80fd5b5f60208284031215612821575f80fd5b81356118d2816127fd565b5f6020828403121561283c575f80fd5b81356001600160401b03811115612851575f80fd5b820161010081850312156118d2575f80fd5b80356001600160401b0381168114612879575f80fd5b919050565b5f805f60408486031215612890575f80fd5b61289984612863565b925060208401356001600160401b03808211156128b4575f80fd5b818601915086601f8301126128c7575f80fd5b8135818111156128d5575f80fd5b8760208285010111156128e6575f80fd5b6020830194508093505050509250925092565b5f8083601f840112612909575f80fd5b5081356001600160401b0381111561291f575f80fd5b6020830191508360208260051b8501011115612939575f80fd5b9250929050565b5f805f8060408587031215612953575f80fd5b84356001600160401b0380821115612969575f80fd5b612975888389016128f9565b9096509450602087013591508082111561298d575f80fd5b5061299a878288016128f9565b95989497509550505050565b5f602082840312156129b6575f80fd5b6118d282612863565b5f8083601f8401126129cf575f80fd5b5081356001600160401b038111156129e5575f80fd5b602083019150836020606083028501011115612939575f80fd5b5f805f805f8060608789031215612a14575f80fd5b86356001600160401b0380821115612a2a575f80fd5b612a368a838b016128f9565b90985096506020890135915080821115612a4e575f80fd5b612a5a8a838b016129bf565b90965094506040890135915080821115612a72575f80fd5b50612a7f89828a016129bf565b979a9699509497509295939492505050565b5f60208284031215612aa1575f80fd5b81356001600160401b03811115612ab6575f80fd5b820160a081850312156118d2575f80fd5b602081525f825160406020840152612ae26060840182612794565b90506020840151601f198483030160408501526124508282612794565b5f60208083016020845280855180835260408601915060408160051b8701019250602087015f5b82811015612b5457603f19888603018452612b42858351612794565b94509285019290850190600101612b26565b5092979650505050505050565b602080825282518282018190525f9190848201906040850190845b81811015612ba15783516001600160a01b031683529284019291840191600101612b7c565b50909695505050505050565b602080825282518282018190525f9190848201906040850190845b81811015612ba15783516001600160401b031683529284019291840191600101612bc8565b634e487b7160e01b5f52604160045260245ffd5b60405160a081016001600160401b0381118282101715612c2357612c23612bed565b60405290565b604051601f8201601f191681016001600160401b0381118282101715612c5157612c51612bed565b604052919050565b801515811461085e575f80fd5b80356001600160801b0381168114612879575f80fd5b5f60608284031215612c8c575f80fd5b604051606081016001600160401b0381118282101715612cae57612cae612bed565b6040529050808235612cbf81612c59565b8152612ccd60208401612c66565b6020820152612cde60408401612c66565b60408201525092915050565b5f805f60e08486031215612cfc575f80fd5b612d0584612863565b9250612d148560208601612c7c565b9150612d238560808601612c7c565b90509250925092565b5f808335601e19843603018112612d41575f80fd5b8301803591506001600160401b03821115612d5a575f80fd5b602001915036819003821315612939575f80fd5b818382375f9101908152919050565b6001600160401b0391909116815260200190565b634e487b7160e01b5f52603260045260245ffd5b5f60608284031215612db5575f80fd5b6118d28383612c7c565b600181811c90821680612dd357607f821691505b602082108103612df157634e487b7160e01b5f52602260045260245ffd5b50919050565b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b6001600160401b03841681526040602082018190525f906124509083018486612df7565b602081525f610711602083018486612df7565b5f823561011e19833603018112612e6b575f80fd5b9190910192915050565b5f82601f830112612e84575f80fd5b81356001600160401b03811115612e9d57612e9d612bed565b612eb0601f8201601f1916602001612c29565b818152846020838601011115612ec4575f80fd5b816020850160208301375f918101602001919091529392505050565b5f6101208236031215612ef1575f80fd5b612ef9612c01565b612f0283612863565b81526020838101356001600160401b0380821115612f1e575f80fd5b9085019036601f830112612f30575f80fd5b813581811115612f4257612f42612bed565b8060051b612f51858201612c29565b9182528381018501918581019036841115612f6a575f80fd5b86860192505b83831015612fa457823585811115612f86575f80fd5b612f943689838a0101612e75565b8352509186019190860190612f70565b8087890152505050506040860135925080831115612fc0575f80fd5b5050612fce36828601612e75565b604083015250612fe13660608501612c7c565b6060820152612ff33660c08501612c7c565b608082015292915050565b601f82111561080a57805f5260205f20601f840160051c810160208510156130235750805b601f840160051c820191505b818110156114a1575f815560010161302f565b81516001600160401b0381111561305b5761305b612bed565b61306f816130698454612dbf565b84612ffe565b602080601f8311600181146130a2575f841561308b5750858301515b5f19600386901b1c1916600185901b1785556130f9565b5f85815260208120601f198616915b828110156130d0578886015182559484019460019091019084016130b1565b50858210156130ed57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b8051151582526020808201516001600160801b039081169184019190915260409182015116910152565b6001600160401b0385168152610100602082018190525f9061314f83820187612794565b91505061315f6040830185613101565b61245060a0830184613101565b6001600160801b031991909116815260200190565b5f60208284031215613191575f80fd5b81516118d281612c59565b5f602082840312156131ac575f80fd5b5051919050565b634e487b7160e01b5f52601160045260245ffd5b60ff8281168282160390811115610551576105516131b3565b60ff9384168152919092166020820152604081019190915260600190565b600181815b8085111561323857815f190482111561321e5761321e6131b3565b8085161561322b57918102915b93841c9390800290613203565b509250929050565b5f8261324e57506001610551565b8161325a57505f610551565b8160018114613270576002811461327a57613296565b6001915050610551565b60ff84111561328b5761328b6131b3565b50506001821b610551565b5060208310610133831016604e8410600b84101617156132b9575081810a610551565b6132c383836131fe565b805f19048211156132d6576132d66131b3565b029392505050565b5f6118d260ff841683613240565b5f8261330657634e487b7160e01b5f52601260045260245ffd5b500490565b8082028115828204841417610551576105516131b3565b6001600160401b03831681526040602082018190525f9061071190830184612794565b6001600160401b038416815260e081016133626020830185613101565b6107116080830184613101565b81810381811115610551576105516131b3565b606081016105518284613101565b5f602082840312156133a0575f80fd5b81516118d2816127fd565b634e487b7160e01b5f52603160045260245ffd5b80820180821115610551576105516131b3565b92835260208301919091526001600160a01b031660408201526060019056fea2646970667358221220b3d8c11f7925959360f6b9e6237be3f214ece31c073ff956779b2e4360bfd28e64736f6c63430008170033

Verified Source Code Full Match

Compiler: v0.8.23+commit.f704f362 EVM: shanghai Optimization: Yes (8 runs)
IBurnMintERC20.sol 29 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

interface IBurnMintERC20 is IERC20 {
    /// @notice Mints new tokens for a given address.
    /// @param account The address to mint the new tokens to.
    /// @param amount The number of tokens to be minted.
    /// @dev this function increases the total supply.
    function mint(address account, uint256 amount) external;

    /// @notice Burns tokens from the sender.
    /// @param amount The number of tokens to be burned.
    /// @dev this function decreases the total supply.
    function burn(uint256 amount) external;

    /// @notice Burns tokens from a given address..
    /// @param account The address to burn tokens from.
    /// @param amount The number of tokens to be burned.
    /// @dev this function decreases the total supply.
    function burn(address account, uint256 amount) external;

    /// @notice Burns tokens from a given address..
    /// @param account The address to burn tokens from.
    /// @param amount The number of tokens to be burned.
    /// @dev this function decreases the total supply.
    function burnFrom(address account, uint256 amount) external;
}
ITypeAndVersion.sol 6 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

interface ITypeAndVersion {
    function typeAndVersion() external pure returns (string memory);
}
IPool.sol 37 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

import {Pool} from "../libraries/Pool.sol";

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

/// @notice Shared public interface for multiple V1 pool types.
/// Each pool type handles a different child token model e.g. lock/unlock, mint/burn.
interface IPoolV1 is IERC165 {
    /// @notice Lock tokens into the pool or burn the tokens.
    /// @param lockOrBurnIn Encoded data fields for the processing of tokens on the source chain.
    /// @return lockOrBurnOut Encoded data fields for the processing of tokens on the destination chain.
    function lockOrBurn(Pool.LockOrBurnInV1 calldata lockOrBurnIn)
        external
        returns (Pool.LockOrBurnOutV1 memory lockOrBurnOut);

    /// @notice Releases or mints tokens to the receiver address.
    /// @param releaseOrMintIn All data required to release or mint tokens.
    /// @return releaseOrMintOut The amount of tokens released or minted on the local chain, denominated
    /// in the local token's decimals.
    /// @dev The offramp asserts that the balanceOf of the receiver has been incremented by exactly the number
    /// of tokens that is returned in ReleaseOrMintOutV1.destinationAmount. If the amounts do not match, the tx reverts.
    function releaseOrMint(Pool.ReleaseOrMintInV1 calldata releaseOrMintIn)
        external
        returns (Pool.ReleaseOrMintOutV1 memory);

    /// @notice Checks whether a remote chain is supported in the token pool.
    /// @param remoteChainSelector The selector of the remote chain.
    /// @return true if the given chain is a permissioned remote chain.
    function isSupportedChain(uint64 remoteChainSelector) external view returns (bool);

    /// @notice Returns if the token pool supports the given token.
    /// @param token The address of the token.
    /// @return true if the token is supported by the pool.
    function isSupportedToken(address token) external view returns (bool);
}
IRMN.sol 21 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

/// @notice This interface contains the only RMN-related functions that might be used on-chain by other CCIP contracts.
interface IRMN {
    /// @notice A Merkle root tagged with the address of the commit store contract it is destined for.
    struct TaggedRoot {
        address commitStore;
        bytes32 root;
    }

    /// @notice Callers MUST NOT cache the return value as a blessed tagged root could become unblessed.
    function isBlessed(TaggedRoot calldata taggedRoot) external view returns (bool);

    /// @notice Iff there is an active global or legacy curse, this function returns true.
    function isCursed() external view returns (bool);

    /// @notice Iff there is an active global curse, or an active curse for `subject`, this function returns true.
    /// @param subject To check whether a particular chain is cursed, set to bytes16(uint128(chainSelector)).
    function isCursed(bytes16 subject) external view returns (bool);
}
IRouter.sol 35 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

import {Client} from "../libraries/Client.sol";

interface IRouter {
    error OnlyOffRamp();

    /// @notice Route the message to its intended receiver contract.
    /// @param message Client.Any2EVMMessage struct.
    /// @param gasForCallExactCheck of params for exec.
    /// @param gasLimit set of params for exec.
    /// @param receiver set of params for exec.
    /// @dev if the receiver is a contracts that signals support for CCIP execution through EIP-165.
    /// the contract is called. If not, only tokens are transferred.
    /// @return success A boolean value indicating whether the ccip message was received without errors.
    /// @return retBytes A bytes array containing return data form CCIP receiver.
    /// @return gasUsed the gas used by the external customer call. Does not include any overhead.
    function routeMessage(
        Client.Any2EVMMessage calldata message,
        uint16 gasForCallExactCheck,
        uint256 gasLimit,
        address receiver
    ) external returns (bool success, bytes memory retBytes, uint256 gasUsed);

    /// @notice Returns the configured onramp for a specific destination chain.
    /// @param destChainSelector The destination chain Id to get the onRamp for.
    /// @return onRampAddress The address of the onRamp.
    function getOnRamp(uint64 destChainSelector) external view returns (address onRampAddress);

    /// @notice Return true if the given offRamp is a configured offRamp for the given source chain.
    /// @param sourceChainSelector The source chain selector to check.
    /// @param offRamp The address of the offRamp to check.
    function isOffRamp(uint64 sourceChainSelector, address offRamp) external view returns (bool isOffRamp);
}
Client.sol 100 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

// End consumer library.
library Client {
    /// @dev RMN depends on this struct, if changing, please notify the RMN maintainers.
    struct EVMTokenAmount {
        address token; // token address on the local chain.
        uint256 amount; // Amount of tokens.
    }

    struct Any2EVMMessage {
        bytes32 messageId; // MessageId corresponding to ccipSend on source.
        uint64 sourceChainSelector; // Source chain selector.
        bytes sender; // abi.decode(sender) if coming from an EVM chain.
        bytes data; // payload sent in original message.
        EVMTokenAmount[] destTokenAmounts; // Tokens and their amounts in their destination chain representation.
    }

    // If extraArgs is empty bytes, the default is 200k gas limit.
    struct EVM2AnyMessage {
        bytes receiver; // abi.encode(receiver address) for dest EVM chains.
        bytes data; // Data payload.
        EVMTokenAmount[] tokenAmounts; // Token transfers.
        address feeToken; // Address of feeToken. address(0) means you will send msg.value.
        bytes extraArgs; // Populate this with _argsToBytes(EVMExtraArgsV2).
    }

    // Tag to indicate only a gas limit. Only usable for EVM as destination chain.
    bytes4 public constant EVM_EXTRA_ARGS_V1_TAG = 0x97a657c9;

    struct EVMExtraArgsV1 {
        uint256 gasLimit;
    }

    function _argsToBytes(EVMExtraArgsV1 memory extraArgs) internal pure returns (bytes memory bts) {
        return abi.encodeWithSelector(EVM_EXTRA_ARGS_V1_TAG, extraArgs);
    }

    // Tag to indicate a gas limit (or dest chain equivalent processing units) and Out Of Order Execution. This tag is
    // available for multiple chain families. If there is no chain family specific tag, this is the default available
    // for a chain.
    // Note: not available for Solana VM based chains.
    bytes4 public constant GENERIC_EXTRA_ARGS_V2_TAG = 0x181dcf10;

    /// @param gasLimit: gas limit for the callback on the destination chain.
    /// @param allowOutOfOrderExecution: if true, it indicates that the message can be executed in any order relative to
    /// other messages from the same sender. This value's default varies by chain. On some chains, a particular value is
    /// enforced, meaning if the expected value is not set, the message request will revert.
    /// @dev Fully compatible with the previously existing EVMExtraArgsV2.
    struct GenericExtraArgsV2 {
        uint256 gasLimit;
        bool allowOutOfOrderExecution;
    }

    // Extra args tag for chains that use the Solana VM.
    bytes4 public constant SVM_EXTRA_ARGS_V1_TAG = 0x1f3b3aba;

    struct SVMExtraArgsV1 {
        uint32 computeUnits;
        uint64 accountIsWritableBitmap;
        bool allowOutOfOrderExecution;
        bytes32 tokenReceiver;
        // Additional accounts needed for execution of CCIP receiver. Must be empty if message.receiver is zero.
        // Token transfer related accounts are specified in the token pool lookup table on SVM.
        bytes32[] accounts;
    }

    /// @dev The maximum number of accounts that can be passed in SVMExtraArgs.
    uint256 public constant SVM_EXTRA_ARGS_MAX_ACCOUNTS = 64;

    /// @dev The expected static payload size of a token transfer when Borsh encoded and submitted to SVM.
    /// TokenPool extra data and offchain data sizes are dynamic, and should be accounted for separately.
    uint256 public constant SVM_TOKEN_TRANSFER_DATA_OVERHEAD = (4 + 32) // source_pool
        + 32 // token_address
        + 4 // gas_amount
        + 4 // extra_data overhead
        + 32 // amount
        + 32 // size of the token lookup table account
        + 32 // token-related accounts in the lookup table, over-estimated to 32, typically between 11 - 13
        + 32 // token account belonging to the token receiver, e.g ATA, not included in the token lookup table
        + 32 // per-chain token pool config, not included in the token lookup table
        + 32 // per-chain token billing config, not always included in the token lookup table
        + 32; // OffRamp pool signer PDA, not included in the token lookup table

    /// @dev Number of overhead accounts needed for message execution on SVM.
    /// @dev These are message.receiver, and the OffRamp Signer PDA specific to the receiver.
    uint256 public constant SVM_MESSAGING_ACCOUNTS_OVERHEAD = 2;

    /// @dev The size of each SVM account address in bytes.
    uint256 public constant SVM_ACCOUNT_BYTE_SIZE = 32;

    function _argsToBytes(GenericExtraArgsV2 memory extraArgs) internal pure returns (bytes memory bts) {
        return abi.encodeWithSelector(GENERIC_EXTRA_ARGS_V2_TAG, extraArgs);
    }

    function _svmArgsToBytes(SVMExtraArgsV1 memory extraArgs) internal pure returns (bytes memory bts) {
        return abi.encodeWithSelector(SVM_EXTRA_ARGS_V1_TAG, extraArgs);
    }
}
Pool.sol 57 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

/// @notice This library contains various token pool functions to aid constructing the return data.
library Pool {
    // The tag used to signal support for the pool v1 standard.
    // bytes4(keccak256("CCIP_POOL_V1"))
    bytes4 public constant CCIP_POOL_V1 = 0xaff2afbf;

    // The number of bytes in the return data for a pool v1 releaseOrMint call.
    // This should match the size of the ReleaseOrMintOutV1 struct.
    uint16 public constant CCIP_POOL_V1_RET_BYTES = 32;

    // The default max number of bytes in the return data for a pool v1 lockOrBurn call.
    // This data can be used to send information to the destination chain token pool. Can be overwritten
    // in the TokenTransferFeeConfig.destBytesOverhead if more data is required.
    uint32 public constant CCIP_LOCK_OR_BURN_V1_RET_BYTES = 32;

    struct LockOrBurnInV1 {
        bytes receiver; //  The recipient of the tokens on the destination chain, abi encoded.
        uint64 remoteChainSelector; // ─╮ The chain ID of the destination chain.
        address originalSender; // ─────╯ The original sender of the tx on the source chain.
        uint256 amount; //  The amount of tokens to lock or burn, denominated in the source token's decimals.
        address localToken; //  The address on this chain of the token to lock or burn.
    }

    struct LockOrBurnOutV1 {
        // The address of the destination token, abi encoded in the case of EVM chains.
        // This value is UNTRUSTED as any pool owner can return whatever value they want.
        bytes destTokenAddress;
        // Optional pool data to be transferred to the destination chain. Be default this is capped at
        // CCIP_LOCK_OR_BURN_V1_RET_BYTES bytes. If more data is required, the TokenTransferFeeConfig.destBytesOverhead
        // has to be set for the specific token.
        bytes destPoolData;
    }

    struct ReleaseOrMintInV1 {
        bytes originalSender; //          The original sender of the tx on the source chain.
        uint64 remoteChainSelector; // ─╮ The chain ID of the source chain.
        address receiver; // ───────────╯ The recipient of the tokens on the destination chain.
        uint256 amount; //                The amount of tokens to release or mint, denominated in the source token's decimals.
        address localToken; //            The address on this chain of the token to release or mint.
        /// @dev WARNING: sourcePoolAddress should be checked prior to any processing of funds. Make sure it matches the
        /// expected pool address for the given remoteChainSelector.
        bytes sourcePoolAddress; //       The address of the source pool, abi encoded in the case of EVM chains.
        bytes sourcePoolData; //          The data received from the source pool to process the release or mint.
        /// @dev WARNING: offchainTokenData is untrusted data.
        bytes offchainTokenData; //       The offchain data to process the release or mint.
    }

    struct ReleaseOrMintOutV1 {
        // The number of tokens released or minted on the destination chain, denominated in the local token's decimals.
        // This value is expected to be equal to the ReleaseOrMintInV1.amount in the case where the source and destination
        // chain have the same number of decimals.
        uint256 destinationAmount;
    }
}
RateLimiter.sol 153 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.23;

/// @notice Implements Token Bucket rate limiting.
/// @dev uint128 is safe for rate limiter state.
/// - For USD value rate limiting, it can adequately store USD value in 18 decimals.
/// - For ERC20 token amount rate limiting, all tokens that will be listed will have at most a supply of uint128.max
/// tokens, and it will therefore not overflow the bucket. In exceptional scenarios where tokens consumed may be larger
/// than uint128, e.g. compromised issuer, an enabled RateLimiter will check and revert.
library RateLimiter {
    error BucketOverfilled();
    error OnlyCallableByAdminOrOwner();
    error TokenMaxCapacityExceeded(uint256 capacity, uint256 requested, address tokenAddress);
    error TokenRateLimitReached(uint256 minWaitInSeconds, uint256 available, address tokenAddress);
    error AggregateValueMaxCapacityExceeded(uint256 capacity, uint256 requested);
    error AggregateValueRateLimitReached(uint256 minWaitInSeconds, uint256 available);
    error InvalidRateLimitRate(Config rateLimiterConfig);
    error DisabledNonZeroRateLimit(Config config);
    error RateLimitMustBeDisabled();

    event TokensConsumed(uint256 tokens);
    event ConfigChanged(Config config);

    struct TokenBucket {
        uint128 tokens; // ──────╮ Current number of tokens that are in the bucket.
        uint32 lastUpdated; //   │ Timestamp in seconds of the last token refill, good for 100+ years.
        bool isEnabled; // ──────╯ Indication whether the rate limiting is enabled or not.
        uint128 capacity; // ────╮ Maximum number of tokens that can be in the bucket.
        uint128 rate; // ────────╯ Number of tokens per second that the bucket is refilled.
    }

    struct Config {
        bool isEnabled; // Indication whether the rate limiting should be enabled.
        uint128 capacity; // ────╮ Specifies the capacity of the rate limiter.
        uint128 rate; //  ───────╯ Specifies the rate of the rate limiter.
    }

    /// @notice _consume removes the given tokens from the pool, lowering the rate tokens allowed to be
    /// consumed for subsequent calls.
    /// @param requestTokens The total tokens to be consumed from the bucket.
    /// @param tokenAddress The token to consume capacity for, use 0x0 to indicate aggregate value capacity.
    /// @dev Reverts when requestTokens exceeds bucket capacity or available tokens in the bucket.
    /// @dev emits removal of requestTokens if requestTokens is > 0.
    function _consume(TokenBucket storage s_bucket, uint256 requestTokens, address tokenAddress) internal {
        // If there is no value to remove or rate limiting is turned off, skip this step to reduce gas usage.
        if (!s_bucket.isEnabled || requestTokens == 0) {
            return;
        }

        uint256 tokens = s_bucket.tokens;
        uint256 capacity = s_bucket.capacity;
        uint256 timeDiff = block.timestamp - s_bucket.lastUpdated;

        if (timeDiff != 0) {
            if (tokens > capacity) revert BucketOverfilled();

            // Refill tokens when arriving at a new block time.
            tokens = _calculateRefill(capacity, tokens, timeDiff, s_bucket.rate);

            s_bucket.lastUpdated = uint32(block.timestamp);
        }

        if (capacity < requestTokens) {
            // Token address 0 indicates consuming aggregate value rate limit capacity.
            if (tokenAddress == address(0)) revert AggregateValueMaxCapacityExceeded(capacity, requestTokens);
            revert TokenMaxCapacityExceeded(capacity, requestTokens, tokenAddress);
        }
        if (tokens < requestTokens) {
            uint256 rate = s_bucket.rate;
            // Wait required until the bucket is refilled enough to accept this value, round up to next higher second.
            // Consume is not guaranteed to succeed after wait time passes if there is competing traffic.
            // This acts as a lower bound of wait time.
            uint256 minWaitInSeconds = ((requestTokens - tokens) + (rate - 1)) / rate;

            if (tokenAddress == address(0)) revert AggregateValueRateLimitReached(minWaitInSeconds, tokens);
            revert TokenRateLimitReached(minWaitInSeconds, tokens, tokenAddress);
        }
        tokens -= requestTokens;

        // Downcast is safe here, as tokens is not larger than capacity.
        s_bucket.tokens = uint128(tokens);
        emit TokensConsumed(requestTokens);
    }

    /// @notice Gets the token bucket with its values for the block it was requested at.
    /// @return The token bucket.
    function _currentTokenBucketState(TokenBucket memory bucket) internal view returns (TokenBucket memory) {
        // We update the bucket to reflect the status at the exact time of the call. This means we might need to refill a
        // part of the bucket based on the time that has passed since the last update.
        bucket.tokens =
            uint128(_calculateRefill(bucket.capacity, bucket.tokens, block.timestamp - bucket.lastUpdated, bucket.rate));
        bucket.lastUpdated = uint32(block.timestamp);
        return bucket;
    }

    /// @notice Sets the rate limited config.
    /// @param s_bucket The token bucket.
    /// @param config The new config.
    function _setTokenBucketConfig(TokenBucket storage s_bucket, Config memory config) internal {
        // First update the bucket to make sure the proper rate is used for all the time up until the config change.
        uint256 timeDiff = block.timestamp - s_bucket.lastUpdated;
        if (timeDiff != 0) {
            s_bucket.tokens = uint128(_calculateRefill(s_bucket.capacity, s_bucket.tokens, timeDiff, s_bucket.rate));

            s_bucket.lastUpdated = uint32(block.timestamp);
        }

        s_bucket.tokens = uint128(_min(config.capacity, s_bucket.tokens));
        s_bucket.isEnabled = config.isEnabled;
        s_bucket.capacity = config.capacity;
        s_bucket.rate = config.rate;

        emit ConfigChanged(config);
    }

    /// @notice Validates the token bucket config.
    function _validateTokenBucketConfig(Config memory config, bool mustBeDisabled) internal pure {
        if (config.isEnabled) {
            if (config.rate >= config.capacity || config.rate == 0) {
                revert InvalidRateLimitRate(config);
            }
            if (mustBeDisabled) {
                revert RateLimitMustBeDisabled();
            }
        } else {
            if (config.rate != 0 || config.capacity != 0) {
                revert DisabledNonZeroRateLimit(config);
            }
        }
    }

    /// @notice Calculate refilled tokens.
    /// @param capacity bucket capacity.
    /// @param tokens current bucket tokens.
    /// @param timeDiff block time difference since last refill.
    /// @param rate bucket refill rate.
    /// @return the value of tokens after refill.
    function _calculateRefill(uint256 capacity, uint256 tokens, uint256 timeDiff, uint256 rate)
        private
        pure
        returns (uint256)
    {
        return _min(capacity, tokens + timeDiff * rate);
    }

    /// @notice Return the smallest of two integers.
    /// @param a first int.
    /// @param b second int.
    /// @return smallest.
    function _min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }
}
BurnMintTokenPool.sol 31 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.23;

import {ITypeAndVersion} from "../../../../../interfaces/ITypeAndVersion.sol";
import {IBurnMintERC20} from "../../../../../interfaces/IBurnMintERC20.sol";

import {BurnMintTokenPoolAbstract} from "./BurnMintTokenPoolAbstract.sol";
import {TokenPool} from "./TokenPool.sol";

/// @notice This pool mints and burns a 3rd-party token.
/// @dev Pool whitelisting mode is set in the constructor and cannot be modified later.
/// It either accepts any address as originalSender, or only accepts whitelisted originalSender.
/// The only way to change whitelisting mode is to deploy a new pool.
/// If that is expected, please make sure the token's burner/minter roles are adjustable.
/// @dev This contract is a variant of BurnMintTokenPool that uses `burn(amount)`.
contract BurnMintTokenPool is BurnMintTokenPoolAbstract, ITypeAndVersion {
    string public constant override typeAndVersion = "BurnMintTokenPool 1.5.1";

    constructor(
        IBurnMintERC20 token,
        uint8 localTokenDecimals,
        address[] memory allowlist,
        address rmnProxy,
        address router
    ) TokenPool(token, localTokenDecimals, allowlist, rmnProxy, router) {}

    /// @inheritdoc BurnMintTokenPoolAbstract
    function _burn(uint256 amount) internal virtual override {
        IBurnMintERC20(address(i_token)).burn(amount);
    }
}
BurnMintTokenPoolAbstract.sol 56 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.23;

import {IBurnMintERC20} from "../../../../../interfaces/IBurnMintERC20.sol";

import {Pool} from "../libraries/Pool.sol";
import {TokenPool} from "./TokenPool.sol";

abstract contract BurnMintTokenPoolAbstract is TokenPool {
    /// @notice Contains the specific burn call for a pool.
    /// @dev overriding this method allows us to create pools with different burn signatures
    /// without duplicating the underlying logic.
    function _burn(uint256 amount) internal virtual;

    /// @notice Burn the token in the pool
    /// @dev The _validateLockOrBurn check is an essential security check
    function lockOrBurn(Pool.LockOrBurnInV1 calldata lockOrBurnIn)
        external
        virtual
        override
        returns (Pool.LockOrBurnOutV1 memory)
    {
        _validateLockOrBurn(lockOrBurnIn);

        _burn(lockOrBurnIn.amount);

        emit Burned(msg.sender, lockOrBurnIn.amount);

        return Pool.LockOrBurnOutV1({
            destTokenAddress: getRemoteToken(lockOrBurnIn.remoteChainSelector),
            destPoolData: _encodeLocalDecimals()
        });
    }

    /// @notice Mint tokens from the pool to the recipient
    /// @dev The _validateReleaseOrMint check is an essential security check
    function releaseOrMint(Pool.ReleaseOrMintInV1 calldata releaseOrMintIn)
        public
        virtual
        override
        returns (Pool.ReleaseOrMintOutV1 memory)
    {
        _validateReleaseOrMint(releaseOrMintIn);

        // Calculate the local amount
        uint256 localAmount =
            _calculateLocalAmount(releaseOrMintIn.amount, _parseRemoteDecimals(releaseOrMintIn.sourcePoolData));

        // Mint to the receiver
        IBurnMintERC20(address(i_token)).mint(releaseOrMintIn.receiver, localAmount);

        emit Minted(msg.sender, releaseOrMintIn.receiver, localAmount);

        return Pool.ReleaseOrMintOutV1({destinationAmount: localAmount});
    }
}
TokenPool.sol 652 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.23;

import {IPoolV1} from "../interfaces/IPool.sol";
import {IRMN} from "../interfaces/IRMN.sol";
import {IRouter} from "../interfaces/IRouter.sol";

import {Pool} from "../libraries/Pool.sol";
import {RateLimiter} from "../libraries/RateLimiter.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

/// @notice Base abstract class with common functions for all token pools.
/// A token pool serves as isolated place for holding tokens and token specific logic
/// that may execute as tokens move across the bridge.
/// @dev This pool supports different decimals on different chains but using this feature could impact the total number
/// of tokens in circulation. Since all of the tokens are locked/burned on the source, and a rounded amount is
/// minted/released on the destination, the number of tokens minted/released could be less than the number of tokens
/// burned/locked. This is because the source chain does not know about the destination token decimals. This is not a
/// problem if the decimals are the same on both chains.
///
/// Example:
/// Assume there is a token with 6 decimals on chain A and 3 decimals on chain B.
/// - 1.234567 tokens are burned on chain A.
/// - 1.234    tokens are minted on chain B.
/// When sending the 1.234 tokens back to chain A, you will receive 1.234000 tokens on chain A, effectively losing
/// 0.000567 tokens.
/// In the case of a burnMint pool on chain A, these funds are burned in the pool on chain A.
/// In the case of a lockRelease pool on chain A, these funds accumulate in the pool on chain A.
abstract contract TokenPool is IPoolV1, Ownable2Step {
    using EnumerableSet for EnumerableSet.Bytes32Set;
    using EnumerableSet for EnumerableSet.AddressSet;
    using EnumerableSet for EnumerableSet.UintSet;
    using RateLimiter for RateLimiter.TokenBucket;

    error CallerIsNotARampOnRouter(address caller);
    error ZeroAddressNotAllowed();
    error SenderNotAllowed(address sender);
    error AllowListNotEnabled();
    error NonExistentChain(uint64 remoteChainSelector);
    error ChainNotAllowed(uint64 remoteChainSelector);
    error CursedByRMN();
    error ChainAlreadyExists(uint64 chainSelector);
    error InvalidSourcePoolAddress(bytes sourcePoolAddress);
    error InvalidToken(address token);
    error Unauthorized(address caller);
    error PoolAlreadyAdded(uint64 remoteChainSelector, bytes remotePoolAddress);
    error InvalidRemotePoolForChain(uint64 remoteChainSelector, bytes remotePoolAddress);
    error InvalidRemoteChainDecimals(bytes sourcePoolData);
    error MismatchedArrayLengths();
    error OverflowDetected(uint8 remoteDecimals, uint8 localDecimals, uint256 remoteAmount);
    error InvalidDecimalArgs(uint8 expected, uint8 actual);

    event Locked(address indexed sender, uint256 amount);
    event Burned(address indexed sender, uint256 amount);
    event Released(address indexed sender, address indexed recipient, uint256 amount);
    event Minted(address indexed sender, address indexed recipient, uint256 amount);
    event ChainAdded(
        uint64 remoteChainSelector,
        bytes remoteToken,
        RateLimiter.Config outboundRateLimiterConfig,
        RateLimiter.Config inboundRateLimiterConfig
    );
    event ChainConfigured(
        uint64 remoteChainSelector,
        RateLimiter.Config outboundRateLimiterConfig,
        RateLimiter.Config inboundRateLimiterConfig
    );
    event ChainRemoved(uint64 remoteChainSelector);
    event RemotePoolAdded(uint64 indexed remoteChainSelector, bytes remotePoolAddress);
    event RemotePoolRemoved(uint64 indexed remoteChainSelector, bytes remotePoolAddress);
    event AllowListAdd(address sender);
    event AllowListRemove(address sender);
    event RouterUpdated(address oldRouter, address newRouter);
    event RateLimitAdminSet(address rateLimitAdmin);

    struct ChainUpdate {
        uint64 remoteChainSelector; // Remote chain selector
        bytes[] remotePoolAddresses; // Address of the remote pool, ABI encoded in the case of a remote EVM chain.
        bytes remoteTokenAddress; // Address of the remote token, ABI encoded in the case of a remote EVM chain.
        RateLimiter.Config outboundRateLimiterConfig; // Outbound rate limited config, meaning the rate limits for all of the onRamps for the given chain
        RateLimiter.Config inboundRateLimiterConfig; // Inbound rate limited config, meaning the rate limits for all of the offRamps for the given chain
    }

    struct RemoteChainConfig {
        RateLimiter.TokenBucket outboundRateLimiterConfig; // Outbound rate limited config, meaning the rate limits for all of the onRamps for the given chain
        RateLimiter.TokenBucket inboundRateLimiterConfig; // Inbound rate limited config, meaning the rate limits for all of the offRamps for the given chain
        bytes remoteTokenAddress; // Address of the remote token, ABI encoded in the case of a remote EVM chain.
        EnumerableSet.Bytes32Set remotePools; // Set of remote pool hashes, ABI encoded in the case of a remote EVM chain.
    }

    /// @dev The bridgeable token that is managed by this pool. Pools could support multiple tokens at the same time if
    /// required, but this implementation only supports one token.
    IERC20 internal immutable i_token;
    /// @dev The number of decimals of the token managed by this pool.
    uint8 internal immutable i_tokenDecimals;
    /// @dev The address of the RMN proxy
    address internal immutable i_rmnProxy;
    /// @dev The immutable flag that indicates if the pool is access-controlled.
    bool internal immutable i_allowlistEnabled;
    /// @dev A set of addresses allowed to trigger lockOrBurn as original senders.
    /// Only takes effect if i_allowlistEnabled is true.
    /// This can be used to ensure only token-issuer specified addresses can move tokens.
    EnumerableSet.AddressSet internal s_allowlist;
    /// @dev The address of the router
    IRouter internal s_router;
    /// @dev A set of allowed chain selectors. We want the allowlist to be enumerable to
    /// be able to quickly determine (without parsing logs) who can access the pool.
    /// @dev The chain selectors are in uint256 format because of the EnumerableSet implementation.
    EnumerableSet.UintSet internal s_remoteChainSelectors;
    mapping(uint64 remoteChainSelector => RemoteChainConfig) internal s_remoteChainConfigs;
    /// @notice A mapping of hashed pool addresses to their unhashed form. This is used to be able to find the actually
    /// configured pools and not just their hashed versions.
    mapping(bytes32 poolAddressHash => bytes poolAddress) internal s_remotePoolAddresses;
    /// @notice The address of the rate limiter admin.
    /// @dev Can be address(0) if none is configured.
    address internal s_rateLimitAdmin;

    constructor(IERC20 token, uint8 localTokenDecimals, address[] memory allowlist, address rmnProxy, address router)
        Ownable(msg.sender)
    {
        if (address(token) == address(0) || router == address(0) || rmnProxy == address(0)) {
            revert ZeroAddressNotAllowed();
        }
        i_token = token;
        i_rmnProxy = rmnProxy;

        try IERC20Metadata(address(token)).decimals() returns (uint8 actualTokenDecimals) {
            if (localTokenDecimals != actualTokenDecimals) {
                revert InvalidDecimalArgs(localTokenDecimals, actualTokenDecimals);
            }
        } catch {
            // The decimals function doesn't exist, which is possible since it's optional in the ERC20 spec. We skip the check and
            // assume the supplied token decimals are correct.
        }
        i_tokenDecimals = localTokenDecimals;

        s_router = IRouter(router);

        // Pool can be set as permissioned or permissionless at deployment time only to save hot-path gas.
        i_allowlistEnabled = allowlist.length > 0;
        if (i_allowlistEnabled) {
            _applyAllowListUpdates(new address[](0), allowlist);
        }
    }

    /// @inheritdoc IPoolV1
    function isSupportedToken(address token) public view virtual returns (bool) {
        return token == address(i_token);
    }

    /// @notice Gets the IERC20 token that this pool can lock or burn.
    /// @return token The IERC20 token representation.
    function getToken() public view returns (IERC20 token) {
        return i_token;
    }

    /// @notice Get RMN proxy address
    /// @return rmnProxy Address of RMN proxy
    function getRmnProxy() public view returns (address rmnProxy) {
        return i_rmnProxy;
    }

    /// @notice Gets the pool's Router
    /// @return router The pool's Router
    function getRouter() public view returns (address router) {
        return address(s_router);
    }

    /// @notice Sets the pool's Router
    /// @param newRouter The new Router
    function setRouter(address newRouter) public onlyOwner {
        if (newRouter == address(0)) revert ZeroAddressNotAllowed();
        address oldRouter = address(s_router);
        s_router = IRouter(newRouter);

        emit RouterUpdated(oldRouter, newRouter);
    }

    /// @notice Signals which version of the pool interface is supported
    function supportsInterface(bytes4 interfaceId) public pure virtual override returns (bool) {
        return interfaceId == Pool.CCIP_POOL_V1 || interfaceId == type(IPoolV1).interfaceId
            || interfaceId == type(IERC165).interfaceId;
    }

    // ================================================================
    // │                         Validation                           │
    // ================================================================

    /// @notice Validates the lock or burn input for correctness on
    /// - token to be locked or burned
    /// - RMN curse status
    /// - allowlist status
    /// - if the sender is a valid onRamp
    /// - rate limit status
    /// @param lockOrBurnIn The input to validate.
    /// @dev This function should always be called before executing a lock or burn. Not doing so would allow
    /// for various exploits.
    function _validateLockOrBurn(Pool.LockOrBurnInV1 calldata lockOrBurnIn) internal {
        if (!isSupportedToken(lockOrBurnIn.localToken)) revert InvalidToken(lockOrBurnIn.localToken);
        if (IRMN(i_rmnProxy).isCursed(bytes16(uint128(lockOrBurnIn.remoteChainSelector)))) revert CursedByRMN();
        _checkAllowList(lockOrBurnIn.originalSender);

        _onlyOnRamp(lockOrBurnIn.remoteChainSelector);
        _consumeOutboundRateLimit(lockOrBurnIn.remoteChainSelector, lockOrBurnIn.amount);
    }

    /// @notice Validates the release or mint input for correctness on
    /// - token to be released or minted
    /// - RMN curse status
    /// - if the sender is a valid offRamp
    /// - if the source pool is valid
    /// - rate limit status
    /// @param releaseOrMintIn The input to validate.
    /// @dev This function should always be called before executing a release or mint. Not doing so would allow
    /// for various exploits.
    function _validateReleaseOrMint(Pool.ReleaseOrMintInV1 calldata releaseOrMintIn) internal {
        if (!isSupportedToken(releaseOrMintIn.localToken)) revert InvalidToken(releaseOrMintIn.localToken);
        if (IRMN(i_rmnProxy).isCursed(bytes16(uint128(releaseOrMintIn.remoteChainSelector)))) revert CursedByRMN();
        _onlyOffRamp(releaseOrMintIn.remoteChainSelector);

        // Validates that the source pool address is configured on this pool.
        if (!isRemotePool(releaseOrMintIn.remoteChainSelector, releaseOrMintIn.sourcePoolAddress)) {
            revert InvalidSourcePoolAddress(releaseOrMintIn.sourcePoolAddress);
        }

        _consumeInboundRateLimit(releaseOrMintIn.remoteChainSelector, releaseOrMintIn.amount);
    }

    // ================================================================
    // │                      Token decimals                          │
    // ================================================================

    /// @notice Gets the IERC20 token decimals on the local chain.
    function getTokenDecimals() public view virtual returns (uint8 decimals) {
        return i_tokenDecimals;
    }

    function _encodeLocalDecimals() internal view virtual returns (bytes memory) {
        return abi.encode(i_tokenDecimals);
    }

    function _parseRemoteDecimals(bytes memory sourcePoolData) internal view virtual returns (uint8) {
        // Fallback to the local token decimals if the source pool data is empty. This allows for backwards compatibility.
        if (sourcePoolData.length == 0) {
            return i_tokenDecimals;
        }
        if (sourcePoolData.length != 32) {
            revert InvalidRemoteChainDecimals(sourcePoolData);
        }
        uint256 remoteDecimals = abi.decode(sourcePoolData, (uint256));
        if (remoteDecimals > type(uint8).max) {
            revert InvalidRemoteChainDecimals(sourcePoolData);
        }
        return uint8(remoteDecimals);
    }

    /// @notice Calculates the local amount based on the remote amount and decimals.
    /// @param remoteAmount The amount on the remote chain.
    /// @param remoteDecimals The decimals of the token on the remote chain.
    /// @return The local amount.
    /// @dev This function protects against overflows. If there is a transaction that hits the overflow check, it is
    /// probably incorrect as that means the amount cannot be represented on this chain. If the local decimals have been
    /// wrongly configured, the token issuer could redeploy the pool with the correct decimals and manually re-execute the
    /// CCIP tx to fix the issue.
    function _calculateLocalAmount(uint256 remoteAmount, uint8 remoteDecimals)
        internal
        view
        virtual
        returns (uint256)
    {
        if (remoteDecimals == i_tokenDecimals) {
            return remoteAmount;
        }
        if (remoteDecimals > i_tokenDecimals) {
            uint8 decimalsDiff = remoteDecimals - i_tokenDecimals;
            if (decimalsDiff > 77) {
                // This is a safety check to prevent overflow in the next calculation.
                revert OverflowDetected(remoteDecimals, i_tokenDecimals, remoteAmount);
            }
            // Solidity rounds down so there is no risk of minting more tokens than the remote chain sent.
            return remoteAmount / (10 ** decimalsDiff);
        }

        // This is a safety check to prevent overflow in the next calculation.
        // More than 77 would never fit in a uint256 and would cause an overflow. We also check if the resulting amount
        // would overflow.
        uint8 diffDecimals = i_tokenDecimals - remoteDecimals;
        if (diffDecimals > 77 || remoteAmount > type(uint256).max / (10 ** diffDecimals)) {
            revert OverflowDetected(remoteDecimals, i_tokenDecimals, remoteAmount);
        }

        return remoteAmount * (10 ** diffDecimals);
    }

    // ================================================================
    // │                     Chain permissions                        │
    // ================================================================

    /// @notice Gets the pool address on the remote chain.
    /// @param remoteChainSelector Remote chain selector.
    /// @dev To support non-evm chains, this value is encoded into bytes
    function getRemotePools(uint64 remoteChainSelector) public view returns (bytes[] memory) {
        bytes32[] memory remotePoolHashes = s_remoteChainConfigs[remoteChainSelector].remotePools.values();

        bytes[] memory remotePools = new bytes[](remotePoolHashes.length);
        for (uint256 i = 0; i < remotePoolHashes.length; ++i) {
            remotePools[i] = s_remotePoolAddresses[remotePoolHashes[i]];
        }

        return remotePools;
    }

    /// @notice Checks if the pool address is configured on the remote chain.
    /// @param remoteChainSelector Remote chain selector.
    /// @param remotePoolAddress The address of the remote pool.
    function isRemotePool(uint64 remoteChainSelector, bytes calldata remotePoolAddress) public view returns (bool) {
        return s_remoteChainConfigs[remoteChainSelector].remotePools.contains(keccak256(remotePoolAddress));
    }

    /// @notice Gets the token address on the remote chain.
    /// @param remoteChainSelector Remote chain selector.
    /// @dev To support non-evm chains, this value is encoded into bytes
    function getRemoteToken(uint64 remoteChainSelector) public view returns (bytes memory) {
        return s_remoteChainConfigs[remoteChainSelector].remoteTokenAddress;
    }

    /// @notice Adds a remote pool for a given chain selector. This could be due to a pool being upgraded on the remote
    /// chain. We don't simply want to replace the old pool as there could still be valid inflight messages from the old
    /// pool. This function allows for multiple pools to be added for a single chain selector.
    /// @param remoteChainSelector The remote chain selector for which the remote pool address is being added.
    /// @param remotePoolAddress The address of the new remote pool.
    function addRemotePool(uint64 remoteChainSelector, bytes calldata remotePoolAddress) external onlyOwner {
        if (!isSupportedChain(remoteChainSelector)) revert NonExistentChain(remoteChainSelector);

        _setRemotePool(remoteChainSelector, remotePoolAddress);
    }

    /// @notice Removes the remote pool address for a given chain selector.
    /// @dev All inflight txs from the remote pool will be rejected after it is removed. To ensure no loss of funds, there
    /// should be no inflight txs from the given pool.
    function removeRemotePool(uint64 remoteChainSelector, bytes calldata remotePoolAddress) external onlyOwner {
        if (!isSupportedChain(remoteChainSelector)) revert NonExistentChain(remoteChainSelector);

        if (!s_remoteChainConfigs[remoteChainSelector].remotePools.remove(keccak256(remotePoolAddress))) {
            revert InvalidRemotePoolForChain(remoteChainSelector, remotePoolAddress);
        }

        emit RemotePoolRemoved(remoteChainSelector, remotePoolAddress);
    }

    /// @inheritdoc IPoolV1
    function isSupportedChain(uint64 remoteChainSelector) public view returns (bool) {
        return s_remoteChainSelectors.contains(remoteChainSelector);
    }

    /// @notice Get list of allowed chains
    /// @return list of chains.
    function getSupportedChains() public view returns (uint64[] memory) {
        uint256[] memory uint256ChainSelectors = s_remoteChainSelectors.values();
        uint64[] memory chainSelectors = new uint64[](uint256ChainSelectors.length);
        for (uint256 i = 0; i < uint256ChainSelectors.length; ++i) {
            chainSelectors[i] = uint64(uint256ChainSelectors[i]);
        }

        return chainSelectors;
    }

    /// @notice Sets the permissions for a list of chains selectors. Actual senders for these chains
    /// need to be allowed on the Router to interact with this pool.
    /// @param remoteChainSelectorsToRemove A list of chain selectors to remove.
    /// @param chainsToAdd A list of chains and their new permission status & rate limits. Rate limits
    /// are only used when the chain is being added through `allowed` being true.
    /// @dev Only callable by the owner
    function applyChainUpdates(uint64[] calldata remoteChainSelectorsToRemove, ChainUpdate[] calldata chainsToAdd)
        external
        virtual
        onlyOwner
    {
        for (uint256 i = 0; i < remoteChainSelectorsToRemove.length; ++i) {
            uint64 remoteChainSelectorToRemove = remoteChainSelectorsToRemove[i];
            // If the chain doesn't exist, revert
            if (!s_remoteChainSelectors.remove(remoteChainSelectorToRemove)) {
                revert NonExistentChain(remoteChainSelectorToRemove);
            }

            // Remove all remote pool hashes for the chain
            bytes32[] memory remotePools = s_remoteChainConfigs[remoteChainSelectorToRemove].remotePools.values();
            for (uint256 j = 0; j < remotePools.length; ++j) {
                s_remoteChainConfigs[remoteChainSelectorToRemove].remotePools.remove(remotePools[j]);
            }

            delete s_remoteChainConfigs[remoteChainSelectorToRemove];

            emit ChainRemoved(remoteChainSelectorToRemove);
        }

        for (uint256 i = 0; i < chainsToAdd.length; ++i) {
            ChainUpdate memory newChain = chainsToAdd[i];
            RateLimiter._validateTokenBucketConfig(newChain.outboundRateLimiterConfig, false);
            RateLimiter._validateTokenBucketConfig(newChain.inboundRateLimiterConfig, false);

            if (newChain.remoteTokenAddress.length == 0) {
                revert ZeroAddressNotAllowed();
            }

            // If the chain already exists, revert
            if (!s_remoteChainSelectors.add(newChain.remoteChainSelector)) {
                revert ChainAlreadyExists(newChain.remoteChainSelector);
            }

            RemoteChainConfig storage remoteChainConfig = s_remoteChainConfigs[newChain.remoteChainSelector];

            remoteChainConfig.outboundRateLimiterConfig = RateLimiter.TokenBucket({
                rate: newChain.outboundRateLimiterConfig.rate,
                capacity: newChain.outboundRateLimiterConfig.capacity,
                tokens: newChain.outboundRateLimiterConfig.capacity,
                lastUpdated: uint32(block.timestamp),
                isEnabled: newChain.outboundRateLimiterConfig.isEnabled
            });
            remoteChainConfig.inboundRateLimiterConfig = RateLimiter.TokenBucket({
                rate: newChain.inboundRateLimiterConfig.rate,
                capacity: newChain.inboundRateLimiterConfig.capacity,
                tokens: newChain.inboundRateLimiterConfig.capacity,
                lastUpdated: uint32(block.timestamp),
                isEnabled: newChain.inboundRateLimiterConfig.isEnabled
            });
            remoteChainConfig.remoteTokenAddress = newChain.remoteTokenAddress;

            for (uint256 j = 0; j < newChain.remotePoolAddresses.length; ++j) {
                _setRemotePool(newChain.remoteChainSelector, newChain.remotePoolAddresses[j]);
            }

            emit ChainAdded(
                newChain.remoteChainSelector,
                newChain.remoteTokenAddress,
                newChain.outboundRateLimiterConfig,
                newChain.inboundRateLimiterConfig
            );
        }
    }

    /// @notice Adds a pool address to the allowed remote token pools for a particular chain.
    /// @param remoteChainSelector The remote chain selector for which the remote pool address is being added.
    /// @param remotePoolAddress The address of the new remote pool.
    function _setRemotePool(uint64 remoteChainSelector, bytes memory remotePoolAddress) internal {
        if (remotePoolAddress.length == 0) {
            revert ZeroAddressNotAllowed();
        }

        bytes32 poolHash = keccak256(remotePoolAddress);

        // Check if the pool already exists.
        if (!s_remoteChainConfigs[remoteChainSelector].remotePools.add(poolHash)) {
            revert PoolAlreadyAdded(remoteChainSelector, remotePoolAddress);
        }

        // Add the pool to the mapping to be able to un-hash it later.
        s_remotePoolAddresses[poolHash] = remotePoolAddress;

        emit RemotePoolAdded(remoteChainSelector, remotePoolAddress);
    }

    // ================================================================
    // │                        Rate limiting                         │
    // ================================================================

    /// @dev The inbound rate limits should be slightly higher than the outbound rate limits. This is because many chains
    /// finalize blocks in batches. CCIP also commits messages in batches: the commit plugin bundles multiple messages in
    /// a single merkle root.
    /// Imagine the following scenario.
    /// - Chain A has an inbound and outbound rate limit of 100 tokens capacity and 1 token per second refill rate.
    /// - Chain B has an inbound and outbound rate limit of 100 tokens capacity and 1 token per second refill rate.
    ///
    /// At time 0:
    /// - Chain A sends 100 tokens to Chain B.
    /// At time 5:
    /// - Chain A sends 5 tokens to Chain B.
    /// At time 6:
    /// The epoch that contains blocks [0-5] is finalized.
    /// Both transactions will be included in the same merkle root and become executable at the same time. This means
    /// the token pool on chain B requires a capacity of 105 to successfully execute both messages at the same time.
    /// The exact additional capacity required depends on the refill rate and the size of the source chain epochs and the
    /// CCIP round time. For simplicity, a 5-10% buffer should be sufficient in most cases.

    /// @notice Sets the rate limiter admin address.
    /// @dev Only callable by the owner.
    /// @param rateLimitAdmin The new rate limiter admin address.
    function setRateLimitAdmin(address rateLimitAdmin) external onlyOwner {
        s_rateLimitAdmin = rateLimitAdmin;
        emit RateLimitAdminSet(rateLimitAdmin);
    }

    /// @notice Gets the rate limiter admin address.
    function getRateLimitAdmin() external view returns (address) {
        return s_rateLimitAdmin;
    }

    /// @notice Consumes outbound rate limiting capacity in this pool
    function _consumeOutboundRateLimit(uint64 remoteChainSelector, uint256 amount) internal {
        s_remoteChainConfigs[remoteChainSelector].outboundRateLimiterConfig._consume(amount, address(i_token));
    }

    /// @notice Consumes inbound rate limiting capacity in this pool
    function _consumeInboundRateLimit(uint64 remoteChainSelector, uint256 amount) internal {
        s_remoteChainConfigs[remoteChainSelector].inboundRateLimiterConfig._consume(amount, address(i_token));
    }

    /// @notice Gets the token bucket with its values for the block it was requested at.
    /// @return The token bucket.
    function getCurrentOutboundRateLimiterState(uint64 remoteChainSelector)
        external
        view
        returns (RateLimiter.TokenBucket memory)
    {
        return s_remoteChainConfigs[remoteChainSelector].outboundRateLimiterConfig._currentTokenBucketState();
    }

    /// @notice Gets the token bucket with its values for the block it was requested at.
    /// @return The token bucket.
    function getCurrentInboundRateLimiterState(uint64 remoteChainSelector)
        external
        view
        returns (RateLimiter.TokenBucket memory)
    {
        return s_remoteChainConfigs[remoteChainSelector].inboundRateLimiterConfig._currentTokenBucketState();
    }

    /// @notice Sets multiple chain rate limiter configs.
    /// @param remoteChainSelectors The remote chain selector for which the rate limits apply.
    /// @param outboundConfigs The new outbound rate limiter config, meaning the onRamp rate limits for the given chain.
    /// @param inboundConfigs The new inbound rate limiter config, meaning the offRamp rate limits for the given chain.
    function setChainRateLimiterConfigs(
        uint64[] calldata remoteChainSelectors,
        RateLimiter.Config[] calldata outboundConfigs,
        RateLimiter.Config[] calldata inboundConfigs
    ) external {
        if (msg.sender != s_rateLimitAdmin && msg.sender != owner()) revert Unauthorized(msg.sender);
        if (
            remoteChainSelectors.length != outboundConfigs.length
                || remoteChainSelectors.length != inboundConfigs.length
        ) {
            revert MismatchedArrayLengths();
        }

        for (uint256 i = 0; i < remoteChainSelectors.length; ++i) {
            _setRateLimitConfig(remoteChainSelectors[i], outboundConfigs[i], inboundConfigs[i]);
        }
    }

    /// @notice Sets the chain rate limiter config.
    /// @param remoteChainSelector The remote chain selector for which the rate limits apply.
    /// @param outboundConfig The new outbound rate limiter config, meaning the onRamp rate limits for the given chain.
    /// @param inboundConfig The new inbound rate limiter config, meaning the offRamp rate limits for the given chain.
    function setChainRateLimiterConfig(
        uint64 remoteChainSelector,
        RateLimiter.Config memory outboundConfig,
        RateLimiter.Config memory inboundConfig
    ) external {
        if (msg.sender != s_rateLimitAdmin && msg.sender != owner()) revert Unauthorized(msg.sender);

        _setRateLimitConfig(remoteChainSelector, outboundConfig, inboundConfig);
    }

    function _setRateLimitConfig(
        uint64 remoteChainSelector,
        RateLimiter.Config memory outboundConfig,
        RateLimiter.Config memory inboundConfig
    ) internal {
        if (!isSupportedChain(remoteChainSelector)) revert NonExistentChain(remoteChainSelector);
        RateLimiter._validateTokenBucketConfig(outboundConfig, false);
        s_remoteChainConfigs[remoteChainSelector].outboundRateLimiterConfig._setTokenBucketConfig(outboundConfig);
        RateLimiter._validateTokenBucketConfig(inboundConfig, false);
        s_remoteChainConfigs[remoteChainSelector].inboundRateLimiterConfig._setTokenBucketConfig(inboundConfig);
        emit ChainConfigured(remoteChainSelector, outboundConfig, inboundConfig);
    }

    // ================================================================
    // │                           Access                             │
    // ================================================================

    /// @notice Checks whether remote chain selector is configured on this contract, and if the msg.sender
    /// is a permissioned onRamp for the given chain on the Router.
    function _onlyOnRamp(uint64 remoteChainSelector) internal view {
        if (!isSupportedChain(remoteChainSelector)) revert ChainNotAllowed(remoteChainSelector);
        if (!(msg.sender == s_router.getOnRamp(remoteChainSelector))) revert CallerIsNotARampOnRouter(msg.sender);
    }

    /// @notice Checks whether remote chain selector is configured on this contract, and if the msg.sender
    /// is a permissioned offRamp for the given chain on the Router.
    function _onlyOffRamp(uint64 remoteChainSelector) internal view {
        if (!isSupportedChain(remoteChainSelector)) revert ChainNotAllowed(remoteChainSelector);
        if (!s_router.isOffRamp(remoteChainSelector, msg.sender)) revert CallerIsNotARampOnRouter(msg.sender);
    }

    // ================================================================
    // │                          Allowlist                           │
    // ================================================================

    function _checkAllowList(address sender) internal view {
        if (i_allowlistEnabled) {
            if (!s_allowlist.contains(sender)) {
                revert SenderNotAllowed(sender);
            }
        }
    }

    /// @notice Gets whether the allowlist functionality is enabled.
    /// @return true is enabled, false if not.
    function getAllowListEnabled() external view returns (bool) {
        return i_allowlistEnabled;
    }

    /// @notice Gets the allowed addresses.
    /// @return The allowed addresses.
    function getAllowList() external view returns (address[] memory) {
        return s_allowlist.values();
    }

    /// @notice Apply updates to the allow list.
    /// @param removes The addresses to be removed.
    /// @param adds The addresses to be added.
    function applyAllowListUpdates(address[] calldata removes, address[] calldata adds) external onlyOwner {
        _applyAllowListUpdates(removes, adds);
    }

    /// @notice Internal version of applyAllowListUpdates to allow for reuse in the constructor.
    function _applyAllowListUpdates(address[] memory removes, address[] memory adds) internal {
        if (!i_allowlistEnabled) revert AllowListNotEnabled();

        for (uint256 i = 0; i < removes.length; ++i) {
            address toRemove = removes[i];
            if (s_allowlist.remove(toRemove)) {
                emit AllowListRemove(toRemove);
            }
        }
        for (uint256 i = 0; i < adds.length; ++i) {
            address toAdd = adds[i];
            if (toAdd == address(0)) {
                continue;
            }
            if (s_allowlist.add(toAdd)) {
                emit AllowListAdd(toAdd);
            }
        }
    }
}
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);
    }
}
Ownable2Step.sol 67 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @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);
}
IERC20Metadata.sol 26 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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);
}
Arrays.sol 482 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.

pragma solidity ^0.8.20;

import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";

/**
 * @dev Collection of functions related to array types.
 */
library Arrays {
    using SlotDerivation for bytes32;
    using StorageSlot for bytes32;

    /**
     * @dev Sort an array of uint256 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        uint256[] memory array,
        function(uint256, uint256) pure returns (bool) comp
    ) internal pure returns (uint256[] memory) {
        _quickSort(_begin(array), _end(array), comp);
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of uint256 in increasing order.
     */
    function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
        sort(array, Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of address (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        address[] memory array,
        function(address, address) pure returns (bool) comp
    ) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of address in increasing order.
     */
    function sort(address[] memory array) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of bytes32 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        bytes32[] memory array,
        function(bytes32, bytes32) pure returns (bool) comp
    ) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
     */
    function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
     * at end (exclusive). Sorting follows the `comp` comparator.
     *
     * Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
     *
     * IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
     * be used only if the limits are within a memory array.
     */
    function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
        unchecked {
            if (end - begin < 0x40) return;

            // Use first element as pivot
            uint256 pivot = _mload(begin);
            // Position where the pivot should be at the end of the loop
            uint256 pos = begin;

            for (uint256 it = begin + 0x20; it < end; it += 0x20) {
                if (comp(_mload(it), pivot)) {
                    // If the value stored at the iterator's position comes before the pivot, we increment the
                    // position of the pivot and move the value there.
                    pos += 0x20;
                    _swap(pos, it);
                }
            }

            _swap(begin, pos); // Swap pivot into place
            _quickSort(begin, pos, comp); // Sort the left side of the pivot
            _quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
        }
    }

    /**
     * @dev Pointer to the memory location of the first element of `array`.
     */
    function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
        assembly ("memory-safe") {
            ptr := add(array, 0x20)
        }
    }

    /**
     * @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
     * that comes just after the last element of the array.
     */
    function _end(uint256[] memory array) private pure returns (uint256 ptr) {
        unchecked {
            return _begin(array) + array.length * 0x20;
        }
    }

    /**
     * @dev Load memory word (as a uint256) at location `ptr`.
     */
    function _mload(uint256 ptr) private pure returns (uint256 value) {
        assembly {
            value := mload(ptr)
        }
    }

    /**
     * @dev Swaps the elements memory location `ptr1` and `ptr2`.
     */
    function _swap(uint256 ptr1, uint256 ptr2) private pure {
        assembly {
            let value1 := mload(ptr1)
            let value2 := mload(ptr2)
            mstore(ptr1, value2)
            mstore(ptr2, value1)
        }
    }

    /// @dev Helper: low level cast address memory array to uint256 memory array
    function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 memory array to uint256 memory array
    function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast address comp function to uint256 comp function
    function _castToUint256Comp(
        function(address, address) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 comp function to uint256 comp function
    function _castToUint256Comp(
        function(bytes32, bytes32) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /**
     * @dev Searches a sorted `array` and returns the first index that contains
     * a value greater or equal to `element`. If no such index exists (i.e. all
     * values in the array are strictly less than `element`), the array length is
     * returned. Time complexity O(log n).
     *
     * NOTE: The `array` is expected to be sorted in ascending order, and to
     * contain no repeated elements.
     *
     * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
     * support for repeated elements in the array. The {lowerBound} function should
     * be used instead.
     */
    function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
        if (low > 0 && unsafeAccess(array, low - 1).value == element) {
            return low - 1;
        } else {
            return low;
        }
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value greater or equal than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
     */
    function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value strictly greater than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
     */
    function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Same as {lowerBound}, but with an array in memory.
     */
    function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Same as {upperBound}, but with an array in memory.
     */
    function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getAddressSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getBytes32Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getUint256Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(address[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(uint256[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }
}
Comparators.sol 19 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides a set of functions to compare values.
 *
 * _Available since v5.1._
 */
library Comparators {
    function lt(uint256 a, uint256 b) internal pure returns (bool) {
        return a < b;
    }

    function gt(uint256 a, uint256 b) internal pure returns (bool) {
        return a > b;
    }
}
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;
    }
}
Panic.sol 57 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}
SlotDerivation.sol 155 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/SlotDerivation.sol)
// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
 * corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
 * the solidity language / compiler.
 *
 * See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
 *
 * Example usage:
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using StorageSlot for bytes32;
 *     using SlotDerivation for bytes32;
 *
 *     // Declare a namespace
 *     string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
 *
 *     function setValueInNamespace(uint256 key, address newValue) internal {
 *         _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
 *     }
 *
 *     function getValueInNamespace(uint256 key) internal view returns (address) {
 *         return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {StorageSlot}.
 *
 * NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
 * upgrade safety will ignore the slots accessed through this library.
 *
 * _Available since v5.1._
 */
library SlotDerivation {
    /**
     * @dev Derive an ERC-7201 slot from a string (namespace).
     */
    function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
        assembly ("memory-safe") {
            mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
            slot := and(keccak256(0x00, 0x20), not(0xff))
        }
    }

    /**
     * @dev Add an offset to a slot to get the n-th element of a structure or an array.
     */
    function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
        unchecked {
            return bytes32(uint256(slot) + pos);
        }
    }

    /**
     * @dev Derive the location of the first element in an array from the slot where the length is stored.
     */
    function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, slot)
            result := keccak256(0x00, 0x20)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, and(key, shr(96, not(0))))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, iszero(iszero(key)))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }
}
StorageSlot.sol 143 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

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

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

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

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

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

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

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

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

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

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

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

pragma solidity ^0.8.20;

/**
 * @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);
}
Math.sol 749 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}
SafeCast.sol 1162 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}
EnumerableSet.sol 422 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

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

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 * - Set can be cleared (all elements removed) in O(n).
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function _clear(Set storage set) private {
        uint256 len = _length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(Bytes32Set storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(AddressSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(UintSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }
}

Read Contract

getAllowList 0xa7cd63b7 → address[]
getAllowListEnabled 0xe0351e13 → bool
getCurrentInboundRateLimiterState 0xaf58d59f → tuple
getCurrentOutboundRateLimiterState 0xc75eea9c → tuple
getRateLimitAdmin 0x6d3d1a58 → address
getRemotePools 0xa42a7b8b → bytes[]
getRemoteToken 0xb7946580 → bytes
getRmnProxy 0xdc0bd971 → address
getRouter 0xb0f479a1 → address
getSupportedChains 0xc4bffe2b → uint64[]
getToken 0x21df0da7 → address
getTokenDecimals 0x24f65ee7 → uint8
isRemotePool 0x4c5ef0ed → bool
isSupportedChain 0x8926f54f → bool
isSupportedToken 0x240028e8 → bool
owner 0x8da5cb5b → address
pendingOwner 0xe30c3978 → address
supportsInterface 0x01ffc9a7 → bool
typeAndVersion 0x181f5a77 → string

Write Contract 13 functions

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

acceptOwnership 0x79ba5097
No parameters
addRemotePool 0x62ddd3c4
uint64 remoteChainSelector
bytes remotePoolAddress
applyAllowListUpdates 0x54c8a4f3
address[] removes
address[] adds
applyChainUpdates 0xce715906
uint64[] remoteChainSelectorsToRemove
tuple[] chainsToAdd
lockOrBurn 0xbdd8bb53
tuple lockOrBurnIn
returns: tuple
releaseOrMint 0xf4ecccc0
tuple releaseOrMintIn
returns: tuple
removeRemotePool 0xacfecf91
uint64 remoteChainSelector
bytes remotePoolAddress
renounceOwnership 0x715018a6
No parameters
setChainRateLimiterConfig 0x0061d1ac
uint64 remoteChainSelector
tuple outboundConfig
tuple inboundConfig
setChainRateLimiterConfigs 0x30eef268
uint64[] remoteChainSelectors
tuple[] outboundConfigs
tuple[] inboundConfigs
setRateLimitAdmin 0x7d54534e
address rateLimitAdmin
setRouter 0xc0d78655
address newRouter
transferOwnership 0xf2fde38b
address newOwner

Recent Transactions

No transactions found for this address