Address Contract Partially Verified
Address
0x4813B5fAACF2d641f16b6664e18D5A0Fa7d8a4BC
Balance
0 ETH
Nonce
3
Code Size
15143 bytes
Creator
0x448dAe92...5d41 at tx 0x5db5746f...3f26c2
Indexed Transactions
0
Contract Bytecode
15143 bytes
0x608080604052600436101561001357600080fd5b60003560e01c90816389a3027114610c8d575080638b0f9bf814610c5e578063c25c3e1814610c42578063d6d9b34c146100b8578063eae1a64e1461009a5763ec30286b1461006157600080fd5b346100955760003660031901126100955761009161007d610d75565b604051918291602083526020830190610d50565b0390f35b600080fd5b34610095576000366003190112610095576020600054604051908152f35b3461009557600319608036820112610095576004356001600160a01b038116900361009557602435906001600160a01b0382168203610095576001600160401b036044351161009557366023604435011215610095576001600160401b0360443560040135116100955736602460443560040135604435010111610095576001600160401b03606435116100955760809060643536030112610095576101676064803501606435600401610d9d565b15610c2c578035601e1982360301811215610095576001600160401b03818301351161009557818101602081019035360381136100955780356001600160e01b0319169260048382013510610c09575b5050506001600160e01b031916633357162b60e01b14610bf75760005490600282018211610be157600282016000819055607f106108c257604051606b60f91b6020820152602560fa1b60218201523060601b6001600160601b03191660228201526002830160f81b6001600160f81b03191660368201526017815261023c81610ccf565b80516020909101206001600160a01b031690610256610d75565b926102bc602360405186610274829851809260208086019101610d2d565b8101600160fd1b6020820152600560fb1b60218201526044356004013560246044350160228301376044356004013501602960f81b6022820152036003810187520185610cea565b6102c4610d0b565b60405163e5a6b10f60e01b81529094906000816004817f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486001600160a01b03165afa90811561071457600091610830575b5060405163313ce56760e01b8152906020826004817f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486001600160a01b03165afa918215610714576000926107f2575b50604051968760808101106001600160401b0360808a0111176107205760ff93608089016040528852602088015260408701521660608501526103ac606435600401610dd2565b936103bb602460643501610dd2565b946103cf6064803501606435600401610d9d565b60409391935197889388602086015260018060a01b0316604085015260018060a01b0316606084015260a0608084015260ff606061044f61041d8551608060c0890152610140880190610d50565b61043960208701519160bf1992838a83030160e08b0152610d50565b9060408701519088830301610100890152610d50565b93015116610120840152601f198383030160a0840152808252602082019060208160051b84010192856000915b83831061077a57505050505061049b925003601f198101865285610cea565b6044606435013563ffffffff811681036100955760029460209263ffffffff6104e09360405198899586956251ef5560e01b875260a0600488015260a4870190610d50565b930160248501526004356001600160a01b031660448501527313b0d85ccb8bf860b6b79af3029fca081ae9bef26064850152166084830152038173c0784ec9250109a204ece1a06460dec4d8eaacaa5af492831561071457600093610736575b50604051606b60f91b60208201908152602560fa1b6021830152606085901b6001600160601b0319166022830152600360f81b60368301526017825261058582610ccf565b60018060a01b03915190201690604051612a388082018281106001600160401b0382111761072057846105ff9184936110ba85396001600160a01b037f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48811682526004358116602083015291909116604082015260600190565b03906000f080156107145760405163189acdbd60e31b60208201526001600160a01b03909216602480840191909152825260608201916001600160401b0383118184101761072057826040526102d38082019260608401918583106001600160401b0384111761072057610de786396001600160a01b0316905260406080830152605f19916106919060a00182610d50565b0301906000f01561071457604080516001600160a01b038481168252858116602083015283169181019190915261009191907fcccc4f8a3a087b06fc390663263fe07ebd765688740bdc56b78bdfe38e38f8dd90606090a1604080516001600160a01b039485168152948416602086015292169183019190915281906060820190565b6040513d6000823e3d90fd5b634e487b7160e01b600052604160045260246000fd5b9092506020813d602011610772575b8161075260209383610cea565b8101031261009557516001600160a01b0381168103610095579183610540565b3d9150610745565b919395509193601f19828203018652601e19833603018735121561009557828735016001600160401b038135116100955780353603602082011361009557602080600193838294358252803583820184840137600083823584010152601f801991350116010198019601930190918a9596949261047c565b9091506020813d602011610828575b8161080e60209383610cea565b81010312610095575160ff81168103610095579087610365565b3d9150610801565b3d9150816000823e6108428282610cea565b6020818381010312610095578051906001600160401b03821161009557828101601f8383010112156100955781810151906001600160401b0382116107205760405193610899601f8401601f191660200186610cea565b82855281016020838584010101116100955760206108bc93818601920101610d2d565b86610315565b60ff60028301116109295760405160d760f81b6020820152602560fa1b60218201523060601b6001600160601b0319166022820152608160f81b60368201526002830160f81b6001600160f81b03191660378201526018815261092481610ccf565b61023c565b61ffff600283011161098c57604051601b60fb1b6020820152602560fa1b60218201523060601b6001600160601b0319166022820152604160f91b60368201526002830160f01b6001600160f01b03191660378201526019815261092481610ccf565b62ffffff60028301116109f05760405160d960f81b6020820152602560fa1b60218201523060601b6001600160601b0319166022820152608360f81b60368201526002830160e81b6001600160e81b0319166037820152601a815261092481610ccf565b63ffffffff6002830111610a5557604051606d60f91b6020820152602560fa1b60218201523060601b6001600160601b0319166022820152602160fa1b60368201526002830160e01b6001600160e01b0319166037820152601b815261092481610ccf565b64ffffffffff6002830111610abb5760405160db60f81b6020820152602560fa1b60218201523060601b6001600160601b0319166022820152608560f81b60368201526002830160d81b6001600160d81b0319166037820152601c815261092481610ccf565b65ffffffffffff6002830111610b2257604051603760fa1b6020820152602560fa1b60218201523060601b6001600160601b0319166022820152604360f91b60368201526002830160d01b6001600160d01b0319166037820152601d815261092481610ccf565b66ffffffffffffff6002830111610b8a5760405160dd60f81b6020820152602560fa1b60218201523060601b6001600160601b0319166022820152608760f81b60368201526002830160c81b6001600160c81b0319166037820152601e815261092481610ccf565b604051606f60f91b6020820152602560fa1b60218201523060601b6001600160601b0319166022820152601160fb1b60368201526002830160c01b6001600160c01b0319166037820152601f815261092481610ccf565b634e487b7160e01b600052601160045260246000fd5b6040516340852a3f60e11b8152600490fd5b6001600160e01b031992013560040360031b82901b9035161690508280806101b7565b634e487b7160e01b600052603260045260246000fd5b346100955760003660031901126100955761009161007d610d0b565b346100955760003660031901126100955760206040517313b0d85ccb8bf860b6b79af3029fca081ae9bef28152f35b34610095576000366003190112610095577f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486001600160a01b03168152602090f35b604081019081106001600160401b0382111761072057604052565b90601f801991011681019081106001600160401b0382111761072057604052565b60405190610d1882610ccf565b6006825265555344432e6560d01b6020830152565b60005b838110610d405750506000910152565b8181015183820152602001610d30565b90602091610d6981518092818552858086019101610d2d565b601f01601f1916010190565b60405190610d8282610ccf565b600c82526b42726964676564205553444360a01b6020830152565b903590601e198136030182121561009557018035906001600160401b03821161009557602001918160051b3603831361009557565b356001600160a01b0381168103610095579056fe60806040526102d38038038061001481610194565b92833981019060408183031261018f5780516001600160a01b03811680820361018f5760208381015190936001600160401b03821161018f570184601f8201121561018f5780519061006d610068836101cf565b610194565b9582875285838301011161018f57849060005b83811061017b57505060009186010152813b15610163577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b03191682179055604051907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b600080a28351156101455750600080848461012c96519101845af4903d1561013c573d61011c610068826101cf565b908152600081943d92013e6101ea565b505b6040516085908161024e8239f35b606092506101ea565b9250505034610154575061012e565b63b398979f60e01b8152600490fd5b60249060405190634c9c8ce360e01b82526004820152fd5b818101830151888201840152869201610080565b600080fd5b6040519190601f01601f191682016001600160401b038111838210176101b957604052565b634e487b7160e01b600052604160045260246000fd5b6001600160401b0381116101b957601f01601f191660200190565b9061021157508051156101ff57805190602001fd5b604051630a12f52160e11b8152600490fd5b81511580610244575b610222575090565b604051639996b31560e01b81526001600160a01b039091166004820152602490fd5b50803b1561021a56fe60806040527f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc54600090819081906001600160a01b0316368280378136915af43d82803e15604b573d90f35b3d90fdfea2646970667358221220e2caa0bccec41f42746d3537b85eff9c858b9f8470c314eb958c447b0eff6a5c64736f6c63430008190033610100346101ce57601f612a3838819003918201601f19168301926001600160401b03929091838511838610176101d35781606092849260409788528339810103126101ce5761004e816101e9565b906100668461005f602084016101e9565b92016101e9565b913060805260a05260e05260c0527ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a009081549060ff82851c166101bd578080831603610179575b835161283a90816101fe82396080518181816113760152611590015260a0518181816101ea01528181610e3101528181610f75015281816111980152818161147d0152818161179c01528181611b4b015261215e015260c0518181816102d101528181610511015281816106d901528181611279015281816114ee01528181611a0001528181611a680152612206015260e05181818161027b015281816104940152818161060201528181610d7a0152818161122301528181611409015281816118a501526121b90152f35b6001600160401b0319909116811790915581519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d290602090a13880806100ad565b835163f92ee8a960e01b8152600490fd5b600080fd5b634e487b7160e01b600052604160045260246000fd5b51906001600160a01b03821682036101ce5756fe608080604052600436101561001357600080fd5b600090813560e01c9081631902f06814611a97575080632c8a6ae114611a5257806332b3a987146118795780633bbcb44b14611850578063486a7e6b146118325780634c598b561461174c5780634f1ef286146115415780634f872ec3146113e057806352d1902d146113635780635f8f4e9d1461131a5780635fae6025146111c557806367bd044d1461116d578063715018a61461110257806384b0196e14610fa457806389a3027114610f5f5780638a5e52bb14610ddf5780638da5cb5b14610da9578063927ede2d14610d64578063ad3cb1cc14610d1a578063adbcea7514610cae578063aef2654914610c5f578063bb416b3514610c37578063c4d66de814610740578063cc43f3d3146105e3578063cdb9d2ea146103ef578063e1ceec34146103b4578063f2fde38b14610387578063f68d1b9f1461021c5763fbea60221461016057600080fd5b3461021957604036600319011261021957610179611edf565b7fc47b52177930ba2672bfc1f75da55cf82adb3c61c2df74e28bdfefbf52ae9e0560206101a4611ef5565b9261020f60018060a01b038092168087526002845260408720958381169687600052855260406000205493849289526002865260408920886000528652886040600020557f00000000000000000000000000000000000000000000000000000000000000001661229a565b604051908152a280f35b80fd5b503461021957602036600319011261021957610236611f1e565b61023e6122dd565b815460ff811661024d81612012565b8015159081610372575b506103605760ff19166001178255604051634384a98f60e01b6020820152600481527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169183916102af81611f44565b833b1561035c57604051633dbb202b60e01b8152918391839182916102f991907f000000000000000000000000000000000000000000000000000000000000000060048501612069565b038183875af1801561035157610339575b507fc19ffaed16cc79d2c0c853889a5b1fd248a9208d0478bc07dd2da1cda4e89992602083604051908152a180f35b61034290611f31565b61034d57813861030a565b5080fd5b6040513d84823e3d90fd5b8280fd5b604051636a14cf2360e01b8152600490fd5b6001915061037f81612012565b141538610257565b5034610219576020366003190112610219576103b16103a4611edf565b6103ac6122dd565b61209b565b80f35b503461021957806003193601126102195760206040517f87e4683aad14f1869b43140e06b846bd1b00c2e08e9825f6719d163b4cfef2a68152f35b503461021957608036600319011261021957610409611edf565b610411611ef5565b610419611f0b565b916064359263ffffffff84168094036105de576104346122dd565b6001600160a01b0391821691821580156105d4575b6105c25785549360ff851661045d81612012565b80151590816105ad575b5061036057816002911694856bffffffffffffffffffffffff60a01b603654161760365560ff19161786557f00000000000000000000000000000000000000000000000000000000000000001693604051926369c5f5f360e01b6020850152602484015260448301526044825260808201908282106001600160401b0383111761059757859282604052853b1561059357633dbb202b60e01b835283918391607f199161053990827f000000000000000000000000000000000000000000000000000000000000000060848201612069565b03018183885af180156103515761057f575b507f06aeee5a19965b1536947b7571a17a681add9aad3efd41c1bec130257eaab6c96040848482519182526020820152a180f35b61058890611f31565b61035c57823861054b565b8380fd5b634e487b7160e01b600052604160045260246000fd5b600291506105ba81612012565b141538610467565b604051635432922d60e01b8152600490fd5b5080841615610449565b600080fd5b5034610219576020366003190112610219576004356001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811633811480159291906106ac575b505061069a578154600260ff821661064781612012565b03610688578160036020927f38acaebd0e3affc51737125878fe1e25cb5fdb627b3778416219d82f81ef42f89460355560ff1916178455604051908152a180f35b6040516314ca5c1760e21b8152600490fd5b60405163040e613d60e21b8152600490fd5b604051636e296e4560e01b81529250602090839060049082905afa918215610735578492610704575b50807f000000000000000000000000000000000000000000000000000000000000000016911614153880610630565b61072791925060203d60201161072e575b61071f8183611f5f565b81019061204a565b90386106d5565b503d610715565b6040513d86823e3d90fd5b50346102195760203660031901126102195761075a611edf565b906000805160206127e583398151915254916001600160401b03831680159081610c27575b6001149081610c1d575b159081610c14575b50610c02576107d59060016001600160401b03198516176000805160206127e58339815191525560ff8460401c1615610bd5575b6107cd612547565b6103ac612547565b604051916107e283611f44565b601383527227b82aa9a221a13934b233b2a0b230b83a32b960691b60208401526040519261080f84611f44565b60058452640312e302e360dc1b6020850152610829612547565b610831612547565b80516001600160401b038111610aaa578061085a60008051602061278583398151915254612316565b92601f93848111610b54575b50602090848311600114610ac9578692610abe575b50508160011b916000199060031b1c191617600080516020612785833981519152555b83516001600160401b038111610aaa577fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d103916108da8354612316565b818111610a4b575b5060209082116001146109c8578190859660ff96926109bd575b50508160011b916000199060031b1c19161790555b827fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10055827fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1015560401c16156109635780f35b68ff0000000000000000196000805160206127e583398151915254166000805160206127e5833981519152557fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2602060405160018152a180f35b0151905038806108fc565b8285527f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b7595601f198316865b818110610a3357509160ff969791846001959410610a1a575b505050811b019055610911565b015160001960f88460031b161c19169055388080610a0d565b838301518955600190980197602093840193016109f4565b8386527f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b758280850160051c82019260208610610aa1575b0160051c01905b818110610a9657506108e2565b868155600101610a89565b92508192610a82565b634e487b7160e01b84526041600452602484fd5b01519050388061087b565b60008051602061278583398151915287526000805160206127c58339815191529250601f198416875b818110610b3c5750908460019594939210610b23575b505050811b016000805160206127858339815191525561089e565b015160001960f88460031b161c19169055388080610b08565b92936020600181928786015181550195019301610af2565b90915060008051602061278583398151915286528380840160051c6000805160206127c5833981519152019160208510610bbf575b90849392910160051c6000805160206127c583398151915201905b818110610bb15750610866565b878155849350600101610ba4565b6000805160206127c58339815191529250610b89565b68ffffffffffffffffff19841668010000000000000001176000805160206127e5833981519152556107c5565b60405163f92ee8a960e01b8152600490fd5b90501538610791565b303b159150610789565b604085901c60ff1615915061077f565b50346102195780600319360112610219575460405160209160ff16610c5b81612012565b8152f35b503461021957604036600319011261021957610c79611edf565b6040610c83611ef5565b9260018060a01b03809316815260026020522091166000526020526020604060002054604051908152f35b50346102195760203660031901126102195733808252600160208181526040808520600435808752908352818620805460ff19169094179093558051938452908301919091527f0e6a4f4985873f666a9aa21268ce8c462bedf4231c9ed2811360ce956701cb2891a180f35b5034610219578060031936011261021957610d60604051610d3a81611f44565b60058152640352e302e360dc1b6020820152604051918291602083526020830190611fd2565b0390f35b50346102195780600319360112610219576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346102195780600319360112610219576000805160206127a5833981519152546040516001600160a01b039091168152602090f35b50346102195780600319360112610219576036546001600160a01b03908116330361069a57600360ff835416610e1481612012565b03610f4d576035546040516370a0823160e01b81523060048201527f0000000000000000000000000000000000000000000000000000000000000000909216918391602082602481875afa918215610f42578392610f0e575b5081811115610f065750915b82610ec2575b50603555603680546001600160a01b03191690556040519081527f82691da855159f603f5aecf930c44c33ed2b5838cbb20d7009074b3853c6a31d90602090a180f35b803b1561034d57818091602460405180948193630852cd8d60e31b83528860048401525af180156103515715610e7f57610efb90611f31565b61034d578138610e7f565b905091610e79565b9091506020813d602011610f3a575b81610f2a60209383611f5f565b8101031261035c57519038610e6d565b3d9150610f1d565b6040513d85823e3d90fd5b60405163622facd560e11b8152600490fd5b50346102195780600319360112610219576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346102195780600319360112610219577fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1005415806110d9575b1561109c57610feb612350565b90610ff4612414565b906040519060209060208301938385106001600160401b03861117610597579284926020611052889661104498604052858552604051988998600f60f81b8a5260e0858b015260e08a0190611fd2565b9088820360408a0152611fd2565b924660608801523060808801528460a088015286840360c088015251928381520193925b82811061108557505050500390f35b835185528695509381019392810192600101611076565b60405162461bcd60e51b81526020600482015260156024820152741152540dcc4c8e88155b9a5b9a5d1a585b1a5e9959605a1b6044820152606490fd5b507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1015415610fde565b503461021957806003193601126102195761111b6122dd565b6000805160206127a583398151915280546001600160a01b031981169091556000906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b503461021957604036600319011261021957611187611edf565b30330361069a576103b190602435907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031661229a565b5034610219576020366003190112610219576111df611f1e565b6111e76122dd565b815460ff81166111f681612012565b60018114159081611307575b506112f55760ff1916825560405163fc8b55c760e01b6020820152600481527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031691839161125781611f44565b833b1561035c57604051633dbb202b60e01b8152918391839182916112a191907f000000000000000000000000000000000000000000000000000000000000000060048501612069565b038183875af18015610351576112e1575b507ff1e9473f25478fe3af97fb26517a1882c3addc66e942ce3c98a2aeffaec54a58602083604051908152a180f35b6112ea90611f31565b61034d5781386112b2565b604051637812aefb60e11b8152600490fd5b905061131281612012565b151538611202565b50346102195760403660031901126102195760209060ff906040906001600160a01b03611345611edf565b16815260018452818120602435825284522054166040519015158152f35b50346102195780600319360112610219577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031630036113ce5760206040517f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8152f35b60405163703e46dd60e11b8152600490fd5b5034610219576040366003190112610219576113fa611edf565b602435906001600160a01b03907f00000000000000000000000000000000000000000000000000000000000000008216338114801591906114c0575b5061069a57600360ff85541661144b81612012565b036114ae5781816114a2856020947fc47b52177930ba2672bfc1f75da55cf82adb3c61c2df74e28bdfefbf52ae9e05967f00000000000000000000000000000000000000000000000000000000000000001661229a565b6040519485521692a280f35b604051639e76a5b960e01b8152600490fd5b604051636e296e4560e01b81529150602090829060049082905afa908115611536578591611517575b5082167f00000000000000000000000000000000000000000000000000000000000000008316141538611436565b611530915060203d60201161072e5761071f8183611f5f565b386114e9565b6040513d87823e3d90fd5b50604036600319011261021957611556611edf565b6024356001600160401b03811161035c573660238201121561035c57611586903690602481600401359101611f9b565b6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811630811490811561171e575b506113ce576115c96122dd565b8216916040516352d1902d60e01b8152602081600481875afa8591816116ea575b5061160857604051634c9c8ce360e01b815260048101859052602490fd5b9284937f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc908181036116d25750823b156116b95780546001600160a01b0319168217905560405184917fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b8380a283511561169d57508083602061169995519101845af46116936125b2565b91612672565b5080f35b92505050346116aa575080f35b63b398979f60e01b8152600490fd5b604051634c9c8ce360e01b815260048101839052602490fd5b60249060405190632a87526960e21b82526004820152fd5b9091506020813d602011611716575b8161170660209383611f5f565b810103126105de575190386115ea565b3d91506116f9565b9050817f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc54161415386115bc565b503461021957606036600319011261021957611766611edf565b61176e611f0b565b6001600160a01b0382811680156105c25760209060246040518094819363fe575a8760e01b835260048301527f0000000000000000000000000000000000000000000000000000000000000000165afa908115610735578491611803575b506117f15760ff8354166117df81612012565b610360576103b191602435903361210f565b604051636e7fdaf760e11b8152600490fd5b611825915060203d60201161182b575b61181d8183611f5f565b810190612032565b386117cc565b503d611813565b50346102195780600319360112610219576020603554604051908152f35b50346102195780600319360112610219576036546040516001600160a01b039091168152602090f35b503461021957606036600319011261021957611893611edf565b61189b611ef5565b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081169291604435903385148015906119d6575b61069a57303b156119d2576040516367bd044d60e01b81526001600160a01b038516600482015260248101839052868160448183305af190816119bf575b506119895782169182865260026020526040862093169283600052602052604060002080549082820180921161197557556040519081527f57b0fa6deabbc9b92da071a794e0ee49fda25fca31a9e5a0336632a6731bda8490602090a480f35b634e487b7160e01b87526011600452602487fd5b92827f6bf7034bf4a66e25fc097062a5aad392485138a48987ad77209e332e25359156929360209260405195865216941692a480f35b6119cb90979197611f31565b9538611915565b8580fd5b50604051636e296e4560e01b8152602081600481895afa908115611a47578791611a28575b5083167f0000000000000000000000000000000000000000000000000000000000000000841614156118d7565b611a41915060203d60201161072e5761071f8183611f5f565b386119fb565b6040513d89823e3d90fd5b50346102195780600319360112610219576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b90503461034d5760e036600319011261034d57611ab2611edf565b90611abb611ef5565b906001600160401b036064351161059357366023606435011215610593576001600160401b03606435600401351161059357366024606435600401356064350101116105935763ffffffff60c4351660c43503610593576001600160a01b03821615611ed0575060405163fe575a8760e01b81526001600160a01b038281166004830152602090829060249082907f0000000000000000000000000000000000000000000000000000000000000000165afa908115610735578491611eb1575b506117f15760ff835416611b8e81612012565b610360576001600160a01b0382168352600160209081526040808520608435865290915283205460ff16611e9f5760a4354211611e8d576040518060a08101106001600160401b0360a083011117610aaa5760a0810160405260018060a01b0382168152604435602082015260a43560408201526084356060820152608063ffffffff60c4351691015260405160208101907f87e4683aad14f1869b43140e06b846bd1b00c2e08e9825f6719d163b4cfef2a6825260018060a01b0383166040820152604435606082015260a435608082015260843560a082015263ffffffff60c4351660c082015260c0815260e081018181106001600160401b03821117611e7957604052519020611cad3660643560040135602460643501611f9b565b90611cb66126d5565b90611cbf61273f565b6040519060208201937f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8552604083015260608201524660808201523060a082015260a0815260c08101928184106001600160401b03851117611e655760408490528151902061190160f01b845260c282015260e201526042902084611d458383612576565b50611d5281959295612012565b159384611e4f575b508315611dba575b50505015611da8576001600160a01b038216835260016020818152604080862060843587529091528420805460ff191690911790556103b19160c435916044359161210f565b6040516398ceb44f60e01b8152600490fd5b81929350604051611dfd81611def6020820194630b135d3f60e11b988987526024840152604060448401526064830190611fd2565b03601f198101835282611f5f565b5190865afa90611e0b6125b2565b82611e41575b82611e21575b5050388481611d62565b909150602081805181010312611e3d5760200151143880611e17565b8480fd5b915060208251101591611e11565b6001600160a01b03878116911614935038611d5a565b634e487b7160e01b88526041600452602488fd5b634e487b7160e01b86526041600452602486fd5b604051633c3c667760e01b8152600490fd5b6040516308be5f9d60e31b8152600490fd5b611eca915060203d60201161182b5761181d8183611f5f565b38611b7b565b635432922d60e01b8152600490fd5b600435906001600160a01b03821682036105de57565b602435906001600160a01b03821682036105de57565b6044359063ffffffff821682036105de57565b6004359063ffffffff821682036105de57565b6001600160401b03811161059757604052565b604081019081106001600160401b0382111761059757604052565b90601f801991011681019081106001600160401b0382111761059757604052565b6001600160401b03811161059757601f01601f191660200190565b929192611fa782611f80565b91611fb56040519384611f5f565b8294818452818301116105de578281602093846000960137010152565b919082519283825260005b848110611ffe575050826000602080949584010152601f8019910116010190565b602081830181015184830182015201611fdd565b6004111561201c57565b634e487b7160e01b600052602160045260246000fd5b908160209103126105de575180151581036105de5790565b908160209103126105de57516001600160a01b03811681036105de5790565b9161209463ffffffff9160409396959660018060a01b03168552606060208601526060850190611fd2565b9416910152565b6001600160a01b039081169081156120f6576000805160206127a583398151915280546001600160a01b031981168417909155167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a3565b604051631e4fbdf760e01b815260006004820152602490fd5b604080516323b872dd60e01b60208201526001600160a01b03838116602483015230604483015260648083018790528252601f199693959492939092916121839061215b608482611f5f565b847f0000000000000000000000000000000000000000000000000000000000000000166124d5565b83516332b3a98760e01b60208201526001600160a01b0383811660248301528716604482015260648101869052608497880181527f00000000000000000000000000000000000000000000000000000000000000008416976121e59082611f5f565b873b156105de5760008261222e9287519384928392633dbb202b60e01b84527f000000000000000000000000000000000000000000000000000000000000000060048501612069565b0381838c5af1801561228f57849391927fb8fa5fd165287d2cb897cb3ee53488b768ead242c87070b349394d2639824d4c96959363ffffffff92612280575b50855197885216602087015216941692a4565b61228990611f31565b3861226d565b85513d6000823e3d90fd5b60405163a9059cbb60e01b60208201526001600160a01b039290921660248301526044808301939093529181526122db916122d6606483611f5f565b6124d5565b565b6000805160206127a5833981519152546001600160a01b031633036122fe57565b60405163118cdaa760e01b8152336004820152602490fd5b90600182811c92168015612346575b602083101461233057565b634e487b7160e01b600052602260045260246000fd5b91607f1691612325565b604051906000826000805160206127858339815191529182549261237384612316565b808452936020916001918281169081156123ee575060011461239f575b5050506122db92500383611f5f565b60009081526000805160206127c58339815191529590935091905b8284106123d657506122db945050508101602001388080612390565b855488850183015294850194879450928101926123ba565b92505050602092506122db94915060ff191682840152151560051b820101388080612390565b604051906000827fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1039182549261244984612316565b808452936020916001918281169081156123ee5750600114612474575050506122db92500383611f5f565b60009081527f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b759590935091905b8284106124bd57506122db945050508101602001388080612390565b855488850183015294850194879450928101926124a1565b6000806124fe9260018060a01b03169360208151910182865af16124f76125b2565b9083612672565b805190811515918261252c575b50506125145750565b60249060405190635274afe760e01b82526004820152fd5b61253f9250602080918301019101612032565b15388061250b565b60ff6000805160206127e58339815191525460401c161561256457565b604051631afcd79f60e31b8152600490fd5b81519190604183036125a7576125a092506020820151906060604084015193015160001a906125e2565b9192909190565b505060009160029190565b3d156125dd573d906125c382611f80565b916125d16040519384611f5f565b82523d6000602084013e565b606090565b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0841161266657926020929160ff608095604051948552168484015260408301526060820152600092839182805260015afa1561265a5780516001600160a01b0381161561265157918190565b50809160019190565b604051903d90823e3d90fd5b50505060009160039190565b90612699575080511561268757805190602001fd5b604051630a12f52160e11b8152600490fd5b815115806126cc575b6126aa575090565b604051639996b31560e01b81526001600160a01b039091166004820152602490fd5b50803b156126a2565b6126dd612350565b80519081156126ed576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10054801561271a5790565b507fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47090565b612747612414565b8051908115612757576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10154801561271a579056fea16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1029016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930042ad5d3e1f2e6e70edcf6d991b8a3023d3fca8047a131592f9edb9fd9b89d57df0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00a26469706673582212200e37df5eea88d57c32006e2252777f176a3809f74f9c1296a299673340c836f464736f6c63430008190033a26469706673582212208ebbf5481b24d5e880f2df1c7073ec6cce3717163cfa5dc3cf1f71491d3aaabc64736f6c63430008190033
Verified Source Code Partial Match
Compiler: v0.8.25+commit.b61c2a91
EVM: paris
Optimization: Yes (200 runs)
OwnableUpgradeable.sol 119 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @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.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
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) {
OwnableStorage storage $ = _getOwnableStorage();
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 {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Initializable.sol 228 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
UUPSUpgradeable.sol 153 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.20;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC1967-compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
ContextUpgradeable.sol 34 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
EIP712Upgradeable.sol 210 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.20;
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*/
abstract contract EIP712Upgradeable is Initializable, IERC5267 {
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/// @custom:storage-location erc7201:openzeppelin.storage.EIP712
struct EIP712Storage {
/// @custom:oz-renamed-from _HASHED_NAME
bytes32 _hashedName;
/// @custom:oz-renamed-from _HASHED_VERSION
bytes32 _hashedVersion;
string _name;
string _version;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.EIP712")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100;
function _getEIP712Storage() private pure returns (EIP712Storage storage $) {
assembly {
$.slot := EIP712StorageLocation
}
}
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
EIP712Storage storage $ = _getEIP712Storage();
$._name = name;
$._version = version;
// Reset prior values in storage if upgrading
$._hashedName = 0;
$._hashedVersion = 0;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator();
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {IERC-5267}.
*/
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
EIP712Storage storage $ = _getEIP712Storage();
// If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized
// and the EIP712 domain is not reliable, as it will be missing name and version.
require($._hashedName == 0 && $._hashedVersion == 0, "EIP712: Uninitialized");
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Name() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._name;
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Version() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._version;
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
*/
function _EIP712NameHash() internal view returns (bytes32) {
EIP712Storage storage $ = _getEIP712Storage();
string memory name = _EIP712Name();
if (bytes(name).length > 0) {
return keccak256(bytes(name));
} else {
// If the name is empty, the contract may have been upgraded without initializing the new storage.
// We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.
bytes32 hashedName = $._hashedName;
if (hashedName != 0) {
return hashedName;
} else {
return keccak256("");
}
}
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
*/
function _EIP712VersionHash() internal view returns (bytes32) {
EIP712Storage storage $ = _getEIP712Storage();
string memory version = _EIP712Version();
if (bytes(version).length > 0) {
return keccak256(bytes(version));
} else {
// If the version is empty, the contract may have been upgraded without initializing the new storage.
// We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
bytes32 hashedVersion = $._hashedVersion;
if (hashedVersion != 0) {
return hashedVersion;
} else {
return keccak256("");
}
}
}
}
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);
}
}
IERC1271.sol 17 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1271.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
IERC5267.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.20;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}
draft-IERC1822.sol 20 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
ERC1967Proxy.sol 40 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.20;
import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "./ERC1967Utils.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
* encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
*
* Requirements:
*
* - If `data` is empty, `msg.value` must be zero.
*/
constructor(address implementation, bytes memory _data) payable {
ERC1967Utils.upgradeToAndCall(implementation, _data);
}
/**
* @dev Returns the current implementation address.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function _implementation() internal view virtual override returns (address) {
return ERC1967Utils.getImplementation();
}
}
ERC1967Utils.sol 193 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.20;
import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*/
library ERC1967Utils {
// We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
// This will be fixed in Solidity 0.8.21. At that point we should remove these events.
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
Proxy.sol 69 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)
pragma solidity ^0.8.20;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback
* function and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
}
IBeacon.sol 16 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
IERC20Permit.sol 90 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
SafeERC20.sol 118 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
Address.sol 159 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
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;
}
}
StorageSlot.sol 135 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
Strings.sol 94 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
ECDSA.sol 174 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError, bytes32) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
MessageHashUtils.sol 86 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}
SignatureChecker.sol 48 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.20;
import {ECDSA} from "./ECDSA.sol";
import {IERC1271} from "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
* signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
* Argent and Safe Wallet (previously Gnosis Safe).
*/
library SignatureChecker {
/**
* @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
* signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error, ) = ECDSA.tryRecover(hash, signature);
return
(error == ECDSA.RecoverError.NoError && recovered == signer) ||
isValidERC1271SignatureNow(signer, hash, signature);
}
/**
* @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
* against the signer smart contract using ERC1271.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidERC1271SignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(bool success, bytes memory result) = signer.staticcall(
abi.encodeCall(IERC1271.isValidSignature, (hash, signature))
);
return (success &&
result.length >= 32 &&
abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
}
}
Math.sol 415 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return 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.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev 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 {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 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 prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, 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 {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
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^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// 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^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice 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) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @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 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @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;
}
}
SignedMath.sol 43 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
L1OpUSDCBridgeAdapter.sol 335 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {OpUSDCBridgeAdapter} from 'contracts/universal/OpUSDCBridgeAdapter.sol';
import {IL1OpUSDCBridgeAdapter} from 'interfaces/IL1OpUSDCBridgeAdapter.sol';
import {IL2OpUSDCBridgeAdapter} from 'interfaces/IL2OpUSDCBridgeAdapter.sol';
import {IOpUSDCBridgeAdapter} from 'interfaces/IOpUSDCBridgeAdapter.sol';
import {ICrossDomainMessenger} from 'interfaces/external/ICrossDomainMessenger.sol';
import {IUSDC} from 'interfaces/external/IUSDC.sol';
/**
* @title L1OpUSDCBridgeAdapter
* @notice L1OpUSDCBridgeAdapter is a contract that bridges Bridged USDC from L1 to L2 and and receives it from L2.
* It is also in charge of pausing and resuming messaging between the L1 and L2 adapters, and properly initiating the
* migration process to the for bridged USDC to native.
*/
contract L1OpUSDCBridgeAdapter is IL1OpUSDCBridgeAdapter, OpUSDCBridgeAdapter {
using SafeERC20 for IUSDC;
/// @inheritdoc IL1OpUSDCBridgeAdapter
uint256 public burnAmount;
/// @inheritdoc IL1OpUSDCBridgeAdapter
address public burnCaller;
/// @notice Reserve 50 more storage slots to be safe on future upgrades
uint256[50] private __gap;
/**
* @notice Construct the OpUSDCBridgeAdapter contract
* @param _usdc The address of the USDC Contract to be used by the adapter
* @param _messenger The address of the L1 messenger
* @param _linkedAdapter The address of the linked adapter
* @dev The constructor is only used to initialize the OpUSDCBridgeAdapter immutable variables
*/
constructor(
address _usdc,
address _messenger,
address _linkedAdapter
) OpUSDCBridgeAdapter(_usdc, _messenger, _linkedAdapter) {}
/**
* @notice Sets the owner of the contract
* @param _owner The address of the owner
* @dev This function needs only used during the deployment of the proxy contract, and it is disabled for the
* implementation contract
*/
function initialize(address _owner) external virtual override initializer {
__Ownable_init(_owner);
string memory _name = 'OpUSDCBridgeAdapter';
string memory _version = '1.0.0';
__EIP712_init(_name, _version);
}
/*///////////////////////////////////////////////////////////////
MIGRATION
///////////////////////////////////////////////////////////////*/
/**
* @notice Initiates the process to migrate the bridged USDC to native USDC
* @param _roleCaller The address that will be allowed to transfer the usdc roles
* @param _burnCaller The address that will be allowed to call this contract to burn the USDC tokens
* @param _minGasLimitReceiveOnL2 Minimum gas limit that the message can be executed with on L2
* @param _minGasLimitSetBurnAmount Minimum gas limit that the message can be executed with to set the burn amount
* @dev Migrating to native is irreversible and will deprecate these adapters
*/
function migrateToNative(
address _roleCaller,
address _burnCaller,
uint32 _minGasLimitReceiveOnL2,
uint32 _minGasLimitSetBurnAmount
) external onlyOwner {
// Leave this flow open to resend upgrading flow in case message fails on L2
// Circle's USDC implementation of `transferOwnership` reverts on address(0)
if (_roleCaller == address(0) || _burnCaller == address(0)) revert IOpUSDCBridgeAdapter_InvalidAddress();
// Ensure messaging is enabled
if (messengerStatus != Status.Active && messengerStatus != Status.Upgrading) {
revert IOpUSDCBridgeAdapter_MessagingDisabled();
}
burnCaller = _burnCaller;
messengerStatus = Status.Upgrading;
ICrossDomainMessenger(MESSENGER).sendMessage(
LINKED_ADAPTER,
abi.encodeCall(IL2OpUSDCBridgeAdapter.receiveMigrateToNative, (_roleCaller, _minGasLimitSetBurnAmount)),
_minGasLimitReceiveOnL2
);
emit MigratingToNative(MESSENGER, _burnCaller);
}
/**
* @notice Sets the amount of USDC tokens that will be burned when the burnLockedUSDC function is called
* @param _amount The amount of USDC tokens that will be burned
* @dev Only callable by a whitelisted messenger during its migration process
*/
function setBurnAmount(uint256 _amount) external onlyLinkedAdapter {
if (messengerStatus != Status.Upgrading) revert IOpUSDCBridgeAdapter_NotUpgrading();
burnAmount = _amount;
messengerStatus = Status.Deprecated;
emit BurnAmountSet(_amount);
}
/**
* @notice Burns the USDC tokens locked in the contract
* @dev The amount is determined by the burnAmount variable, which is set in the setBurnAmount function
*/
function burnLockedUSDC() external {
if (msg.sender != burnCaller) revert IOpUSDCBridgeAdapter_InvalidSender();
// If the adapter is not deprecated the burn amount has not been set
if (messengerStatus != Status.Deprecated) revert IOpUSDCBridgeAdapter_BurnAmountNotSet();
// NOTE: This is a very edge case and will only happen if the chain operator adds a second minter on L2
// So now this adapter doesnt have the full backing supply locked in this contract
// in case the bridged usdc token has other minters and the supply sent is greater then what we have
// We need to burn the full amount stored in this contract
// This could also cause in-flight messages to fail because of the multiple supply sources
uint256 _burnAmount = burnAmount;
uint256 _balanceOf = IUSDC(USDC).balanceOf(address(this));
_burnAmount = _burnAmount > _balanceOf ? _balanceOf : _burnAmount;
// Burn the USDC tokens
if (_burnAmount != 0) {
IUSDC(USDC).burn(_burnAmount);
}
// Set the burn amount to 0
burnAmount = 0;
burnCaller = address(0);
emit MigrationComplete(_burnAmount);
}
/*///////////////////////////////////////////////////////////////
ADMIN CONTROL
///////////////////////////////////////////////////////////////*/
/**
* @notice Send a message to the linked adapter to call receiveStopMessaging() and stop outgoing messages.
* @dev Only callable by the owner of the adapter
* @param _minGasLimit Minimum gas limit that the message can be executed with
*/
function stopMessaging(uint32 _minGasLimit) external onlyOwner {
// Ensure messaging is enabled
// If its paused we still leave this function open to be called in case the message fails on L2
if (messengerStatus != Status.Active && messengerStatus != Status.Paused) {
revert IOpUSDCBridgeAdapter_MessagingDisabled();
}
messengerStatus = Status.Paused;
ICrossDomainMessenger(MESSENGER).sendMessage(
LINKED_ADAPTER, abi.encodeCall(IL2OpUSDCBridgeAdapter.receiveStopMessaging, ()), _minGasLimit
);
emit MessagingStopped(MESSENGER);
}
/**
* @notice Resume messaging on the messenger
* @dev Only callable by the owner
* @dev Can't resume deprecated or upgrading messengers
* @param _minGasLimit Minimum gas limit that the message can be executed with
*/
function resumeMessaging(uint32 _minGasLimit) external onlyOwner {
// Ensure messaging is disabled
// If its active we still leave this function open to be called in case the message fails on L2
if (messengerStatus != Status.Paused && messengerStatus != Status.Active) {
revert IOpUSDCBridgeAdapter_MessagingEnabled();
}
messengerStatus = Status.Active;
ICrossDomainMessenger(MESSENGER).sendMessage(
LINKED_ADAPTER, abi.encodeCall(IL2OpUSDCBridgeAdapter.receiveResumeMessaging, ()), _minGasLimit
);
emit MessagingResumed(MESSENGER);
}
/*///////////////////////////////////////////////////////////////
MESSAGING
///////////////////////////////////////////////////////////////*/
/**
* @notice Send tokens to another chain through the linked adapter
* @param _to The target address on the destination chain
* @param _amount The amount of tokens to send
* @param _minGasLimit Minimum gas limit that the message can be executed with
*/
function sendMessage(address _to, uint256 _amount, uint32 _minGasLimit) external override {
if (_to == address(0)) revert IOpUSDCBridgeAdapter_InvalidAddress();
// Ensure the address is not blacklisted
if (IUSDC(USDC).isBlacklisted(_to)) revert IOpUSDCBridgeAdapter_BlacklistedAddress();
// Ensure messaging is enabled
if (messengerStatus != Status.Active) revert IOpUSDCBridgeAdapter_MessagingDisabled();
_sendMessage(msg.sender, _to, _amount, _minGasLimit);
}
/**
* @notice Send signer tokens to another chain through the linked adapter
* @param _signer The address of the user sending the message
* @param _to The target address on the destination chain
* @param _amount The amount of tokens to send
* @param _signature The signature of the user
* @param _nonce The nonce of the user
* @param _deadline The deadline for the message to be executed
* @param _minGasLimit Minimum gas limit that the message can be executed with
*/
function sendMessage(
address _signer,
address _to,
uint256 _amount,
bytes calldata _signature,
uint256 _nonce,
uint256 _deadline,
uint32 _minGasLimit
) external override {
if (_to == address(0)) revert IOpUSDCBridgeAdapter_InvalidAddress();
// Ensure the address is not blacklisted
if (IUSDC(USDC).isBlacklisted(_to)) revert IOpUSDCBridgeAdapter_BlacklistedAddress();
// Ensure messaging is enabled
if (messengerStatus != Status.Active) revert IOpUSDCBridgeAdapter_MessagingDisabled();
// Ensure the nonce has not already been used
if (userNonces[_signer][_nonce]) revert IOpUSDCBridgeAdapter_InvalidNonce();
// Ensure the deadline has not passed
if (block.timestamp > _deadline) revert IOpUSDCBridgeAdapter_MessageExpired();
BridgeMessage memory _message =
BridgeMessage({to: _to, amount: _amount, deadline: _deadline, nonce: _nonce, minGasLimit: _minGasLimit});
_checkSignature(_signer, _hashMessageStruct(_message), _signature);
// Mark the nonce as used
userNonces[_signer][_nonce] = true;
_sendMessage(_signer, _to, _amount, _minGasLimit);
}
/**
* @notice Receive the message from the other chain and transfer tokens to the user
* @dev This function should only be called when receiving a message to transfer tokens
* @dev If the transfer fails the funds might be recovered by calling withdrawLockedFunds
* @param _user The user to transfer the tokens to
* @param _spender The address that provided the tokens
* @param _amount The amount of tokens to transfer
*/
function receiveMessage(address _user, address _spender, uint256 _amount) external override onlyLinkedAdapter {
// Transfer the tokens to the user
try this.attemptTransfer(_user, _amount) {
emit MessageReceived(_spender, _user, _amount, MESSENGER);
} catch {
// If the transfer fails, the user could be locked for multiple reasons such as blacklist or usdc being paused
lockedFundsDetails[_spender][_user] += _amount;
emit MessageFailed(_spender, _user, _amount, MESSENGER);
}
}
/**
* @notice Receives a message from L2 if the adapter is deprecated and a user is withdrawing locked funds
* @dev If the _spender is still locked, the user will be forced to replay this message
* @param _spender The user that initially provided the tokens
* @param _amount The amount of tokens to withdraw
*/
function receiveWithdrawLockedFundsPostMigration(address _spender, uint256 _amount) external onlyLinkedAdapter {
if (messengerStatus != Status.Deprecated) revert IOpUSDCBridgeAdapter_NotMigrated();
// If the spender is still locked, the user will be forced to replay this message
IUSDC(USDC).safeTransfer(_spender, _amount);
emit LockedFundsWithdrawn(_spender, _amount);
}
/**
* @notice Withdraws the locked funds from the contract in case they get unlocked
* @param _spender The address that provided the tokens
* @param _user The user to withdraw the funds for
*/
function withdrawLockedFunds(address _spender, address _user) external override {
uint256 _amount = lockedFundsDetails[_spender][_user];
lockedFundsDetails[_spender][_user] = 0;
// The check for if the user is locked happens in USDC's contract
IUSDC(USDC).safeTransfer(_user, _amount);
emit LockedFundsWithdrawn(_user, _amount);
}
/**
* @notice Attempts to transfer the tokens to the user
* @param _to The target address on the destination chain
* @param _amount The amount of tokens to send
* @dev This function should only be called when receiving a message
* And is a workaround for the fact that try/catch
* Only works on external calls and SafeERC20 is an internal library
*/
function attemptTransfer(address _to, uint256 _amount) external {
if (msg.sender != address(this)) revert IOpUSDCBridgeAdapter_InvalidSender();
IUSDC(USDC).safeTransfer(_to, _amount);
}
/*///////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
///////////////////////////////////////////////////////////////*/
/**
* @notice Send the message to the linked adapter
* @param _from address that originated the message
* @param _to target address on the destination chain
* @param _amount amount of tokens to be bridged
* @param _minGasLimit minimum gas limit for the other chain to execute the message
*/
function _sendMessage(address _from, address _to, uint256 _amount, uint32 _minGasLimit) internal {
// Transfer the tokens to the contract
IUSDC(USDC).safeTransferFrom(_from, address(this), _amount);
// Send the message to the linked adapter
ICrossDomainMessenger(MESSENGER).sendMessage(
LINKED_ADAPTER, abi.encodeCall(IOpUSDCBridgeAdapter.receiveMessage, (_to, _from, _amount)), _minGasLimit
);
emit MessageSent(_from, _to, _amount, MESSENGER, _minGasLimit);
}
}
L1OpUSDCFactory.sol 123 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import {ERC1967Proxy} from '@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol';
import {L1OpUSDCBridgeAdapter} from 'contracts/L1OpUSDCBridgeAdapter.sol';
import {IL1OpUSDCFactory} from 'interfaces/IL1OpUSDCFactory.sol';
import {IL2OpUSDCDeploy} from 'interfaces/IL2OpUSDCDeploy.sol';
import {IUSDC} from 'interfaces/external/IUSDC.sol';
import {CrossChainDeployments} from 'libraries/CrossChainDeployments.sol';
import {OpUSDCBridgeAdapter} from 'src/contracts/universal/OpUSDCBridgeAdapter.sol';
/**
* @title L1OpUSDCFactory
* @notice Factory contract to deploy and setup the `L1OpUSDCBridgeAdapter` contract on L1, and
* triggers the deployment of the L2 factory, L2 adapter, and L2 USDC contracts.
* @dev The salt is always different for each deployed instance of this contract on the L1 Factory, and the L2 contracts
* are deployed with `CREATE` to guarantee that the addresses are unique among all the L2s, so we avoid a scenario where
* L2 contracts have the same address on different L2s when triggered by different owners.
*/
contract L1OpUSDCFactory is IL1OpUSDCFactory {
/// @inheritdoc IL1OpUSDCFactory
address public constant L2_CREATE2_DEPLOYER = 0x13b0D85CcB8bf860b6b79AF3029fCA081AE9beF2;
/// @inheritdoc IL1OpUSDCFactory
string public constant USDC_NAME = 'Bridged USDC';
/// @inheritdoc IL1OpUSDCFactory
string public constant USDC_SYMBOL = 'USDC.e';
/// @notice The selector of the `initialize(string,string,string,uint8,address,address,address,address)` function.
/// @dev Used to check the first init tx doesn't match it since it is already defined in the L2 factory contract
bytes4 internal constant _INITIALIZE_SELECTOR = 0x3357162b;
/// @notice The L2 Adapter proxy is the third of the L2 deployments so at that moment the nonce is 3
uint256 internal constant _L2_ADAPTER_DEPLOYMENT_NONCE = 3;
/// @inheritdoc IL1OpUSDCFactory
IUSDC public immutable USDC;
/// @inheritdoc IL1OpUSDCFactory
uint256 public deploymentsSaltCounter;
/**
* @notice Constructs the L1 factory contract
* @param _usdc The address of the USDC contract
*/
constructor(address _usdc) {
USDC = IUSDC(_usdc);
}
/**
* @notice Deploys the L1 Adapter, and sends the deployment txs for the L2 factory, L2 adapter and the L2 USDC through
* the L1 messenger
* @param _l1Messenger The address of the L1 messenger for the L2 Op chain
* @param _l1AdapterOwner The address of the owner of the L1 adapter
* @param _chainName The name of the L2 Op chain
* @param _l2Deployments The deployments data for the L2 adapter, and the L2 USDC contracts
* @return _l1Adapter The address of the L1 adapter
* @return _l2Deploy The address of the L2 deployer contract
* @return _l2Adapter The address of the L2 adapter
* @dev It can fail on L2 due to a gas miscalculation, but in that case the tx can be replayed. It only deploys 1 L2
* factory per L2 deployments, to make sure the nonce is being tracked correctly while precalculating addresses
* @dev The implementation of the USDC contract needs to be deployed on L2 before this is called
* Then set the `usdcImplAddr` in the L2Deployments struct to the address of the deployed USDC implementation contract
*
* @dev IMPORTANT!!!!
* The _l2Deployments.usdcInitTxs must be manually entered to correctly initialize the USDC contract on L2.
* If a function is not included in the init txs, it could lead to potential attack vectors.
* We currently hardcode the `initialize()` function in the L2 factory contract, to correctly configure the setup
* You must provide the following init txs:
* - initalizeV2
* - initilizeV2_1
* - initializeV2_2
*
* It is also important to note that circle may add more init functions in future implementations
* This is up to the deployer to check and be sure all init transactions are included
*/
function deploy(
address _l1Messenger,
address _l1AdapterOwner,
string calldata _chainName,
L2Deployments calldata _l2Deployments
) external returns (address _l1Adapter, address _l2Deploy, address _l2Adapter) {
// Checks that the first init tx selector is not equal to the `initialize()` function since we manually
// Construct this function on the L2 factory contract
if (bytes4(_l2Deployments.usdcInitTxs[0]) == _INITIALIZE_SELECTOR) revert IL1OpUSDCFactory_NoInitializeTx();
// Update the salt counter so the L2 factory is deployed with a different salt to a different address and get it
uint256 _currentNonce = deploymentsSaltCounter += 2;
// Precalculate the l1 adapter proxy address
_l1Adapter = CrossChainDeployments.precalculateCreateAddress(address(this), _currentNonce);
// Get the L1 USDC naming and decimals to ensure they are the same on the L2, guaranteeing the same standard
IL2OpUSDCDeploy.USDCInitializeData memory _usdcInitializeData = IL2OpUSDCDeploy.USDCInitializeData(
string.concat(USDC_NAME, ' ', '(', _chainName, ')'), USDC_SYMBOL, USDC.currency(), USDC.decimals()
);
// Use the nonce as salt to ensure always a different salt since the nonce is always increasing
bytes32 _salt = bytes32(_currentNonce);
// Get the L2 factory init code and precalculate its address
bytes memory _l2DeployCArgs = abi.encode(
_l1Adapter,
_l2Deployments.l2AdapterOwner,
_l2Deployments.usdcImplAddr,
_usdcInitializeData,
_l2Deployments.usdcInitTxs
);
// Send the L2 factory deployment tx
_l2Deploy = CrossChainDeployments.deployL2Factory(
_l2DeployCArgs, _salt, _l1Messenger, L2_CREATE2_DEPLOYER, _l2Deployments.minGasLimitDeploy
);
// Precalculate the L2 adapter address
_l2Adapter = CrossChainDeployments.precalculateCreateAddress(_l2Deploy, _L2_ADAPTER_DEPLOYMENT_NONCE);
// Deploy L1 Adapter implementation and proxy, initializing it with the owner
address _l1AdapterImpl = address(new L1OpUSDCBridgeAdapter(address(USDC), _l1Messenger, _l2Adapter));
new ERC1967Proxy(_l1AdapterImpl, abi.encodeCall(OpUSDCBridgeAdapter.initialize, _l1AdapterOwner));
emit ProtocolDeployed(_l1Adapter, _l2Deploy, _l2Adapter);
}
}
L2OpUSDCBridgeAdapter.sol 316 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {OpUSDCBridgeAdapter} from 'contracts/universal/OpUSDCBridgeAdapter.sol';
import {FallbackProxyAdmin} from 'contracts/utils/FallbackProxyAdmin.sol';
import {IL1OpUSDCBridgeAdapter} from 'interfaces/IL1OpUSDCBridgeAdapter.sol';
import {IL2OpUSDCBridgeAdapter} from 'interfaces/IL2OpUSDCBridgeAdapter.sol';
import {IOpUSDCBridgeAdapter} from 'interfaces/IOpUSDCBridgeAdapter.sol';
import {ICrossDomainMessenger} from 'interfaces/external/ICrossDomainMessenger.sol';
import {IUSDC} from 'interfaces/external/IUSDC.sol';
/**
* @title L2OpUSDCBridgeAdapter
* @notice L2OpUSDCBridgeAdapter is a contract that bridges Bridged USDC from L2 to L1 and and receives the it from L1.
* It finalizes the migration process of bridged USDC to native USDC on L2 after being triggered by the L1 adapter, and
* sends the amount to be burned back to the L1 adapter to finish the migration process.
* @dev The owner of this contract is capable of calling any USDC function, except the ownership or admin ones.
*/
contract L2OpUSDCBridgeAdapter is IL2OpUSDCBridgeAdapter, OpUSDCBridgeAdapter {
using SafeERC20 for IUSDC;
///@notice `transferOwnership(address)` USDC function selector
bytes4 internal constant _TRANSFER_OWNERSHIP_SELECTOR = 0xf2fde38b;
///@notice `changeAdmin(address)` USDC function selector
bytes4 internal constant _CHANGE_ADMIN_SELECTOR = 0x8f283970;
///@notice `upgradeTo(address)` USDC function selector
bytes4 internal constant _UPGRADE_TO_SELECTOR = 0x3659cfe6;
///@notice `upgradeToAndCall(address,bytes)` USDC function selector
bytes4 internal constant _UPGRADE_TO_AND_CALL_SELECTOR = 0x4f1ef286;
///@notice `updateMasterMinter(address)` USDC function selector
bytes4 internal constant _UPDATE_MASTER_MINTER_SELECTOR = 0xaa20e1e4;
/// @inheritdoc IL2OpUSDCBridgeAdapter
// solhint-disable-next-line var-name-mixedcase
FallbackProxyAdmin public FALLBACK_PROXY_ADMIN;
/// @inheritdoc IL2OpUSDCBridgeAdapter
address public roleCaller;
/// @notice Reserve 50 more storage slots to be safe on future upgrades
uint256[50] private __gap;
/**
* @notice Construct the OpUSDCBridgeAdapter contract
* @param _usdc The address of the USDC Contract to be used by the adapter
* @param _messenger The address of the messenger contract
* @param _linkedAdapter The address of the linked adapter
* @dev The constructor is only used to initialize the OpUSDCBridgeAdapter immutable variables
*/
/* solhint-disable no-unused-vars */
constructor(
address _usdc,
address _messenger,
address _linkedAdapter
) OpUSDCBridgeAdapter(_usdc, _messenger, _linkedAdapter) {}
/* solhint-enable no-unused-vars */
/**
* @notice Sets the owner of the contract
* @param _owner The address of the owner
* @dev This function needs only used during the deployment of the proxy contract, and it is disabled for the
* implementation contract
*/
function initialize(address _owner) external virtual override initializer {
__Ownable_init(_owner);
string memory _name = 'OpUSDCBridgeAdapter';
string memory _version = '1.0.0';
__EIP712_init(_name, _version);
FALLBACK_PROXY_ADMIN = new FallbackProxyAdmin(USDC);
}
/*///////////////////////////////////////////////////////////////
MIGRATION
///////////////////////////////////////////////////////////////*/
/**
* @notice Initiates the process to migrate the bridged USDC to native USDC
* @dev Full migration can't finish until L1 receives the message for setting the burn amount
* @param _roleCaller The address that will be allowed to transfer the USDC roles
* @param _setBurnAmountMinGasLimit Minimum gas limit that the setBurnAmount message can be executed on L1
*/
function receiveMigrateToNative(address _roleCaller, uint32 _setBurnAmountMinGasLimit) external onlyLinkedAdapter {
messengerStatus = Status.Deprecated;
roleCaller = _roleCaller;
uint256 _burnAmount = IUSDC(USDC).totalSupply();
// Remove the L2 Adapter as a minter
IUSDC(USDC).removeMinter(address(this));
ICrossDomainMessenger(MESSENGER).sendMessage(
LINKED_ADAPTER, abi.encodeCall(IL1OpUSDCBridgeAdapter.setBurnAmount, (_burnAmount)), _setBurnAmountMinGasLimit
);
emit MigratingToNative(MESSENGER, _roleCaller);
}
/**
* @notice Transfers the USDC roles to the new owner
* @param _owner The address to transfer ownership to
* @dev Can only be called by the role caller set in the migration process
*/
function transferUSDCRoles(address _owner) external {
if (msg.sender != roleCaller) revert IOpUSDCBridgeAdapter_InvalidCaller();
// Transfer ownership of the USDC contract to circle
IUSDC(USDC).transferOwnership(_owner);
// Transfer proxy admin ownership to the caller
FALLBACK_PROXY_ADMIN.changeAdmin(msg.sender);
}
/*///////////////////////////////////////////////////////////////
MESSAGING CONTROL
///////////////////////////////////////////////////////////////*/
/**
* @notice Receive the stop messaging message from the linked adapter and stop outgoing messages
*/
function receiveStopMessaging() external onlyLinkedAdapter {
if (messengerStatus == Status.Deprecated) revert IOpUSDCBridgeAdapter_MessagingDisabled();
messengerStatus = Status.Paused;
emit MessagingStopped(MESSENGER);
}
/**
* @notice Resume messaging after it was stopped
*/
function receiveResumeMessaging() external onlyLinkedAdapter {
if (messengerStatus == Status.Deprecated) revert IOpUSDCBridgeAdapter_MessagingDisabled();
messengerStatus = Status.Active;
emit MessagingResumed(MESSENGER);
}
/*///////////////////////////////////////////////////////////////
MESSAGING
///////////////////////////////////////////////////////////////*/
/**
* @notice Send tokens to another chain through the linked adapter
* @param _to The target address on the destination chain
* @param _amount The amount of tokens to send
* @param _minGasLimit Minimum gas limit that the message can be executed with
*/
function sendMessage(address _to, uint256 _amount, uint32 _minGasLimit) external override {
if (_to == address(0)) revert IOpUSDCBridgeAdapter_InvalidAddress();
// Ensure the address is not blacklisted
if (IUSDC(USDC).isBlacklisted(_to)) revert IOpUSDCBridgeAdapter_BlacklistedAddress();
// Ensure messaging is enabled
if (messengerStatus != Status.Active) revert IOpUSDCBridgeAdapter_MessagingDisabled();
_sendMessage(msg.sender, _to, _amount, _minGasLimit);
}
/**
* @notice Send signer tokens to another chain through the linked adapter
* @param _signer The address of the user sending the message
* @param _to The target address on the destination chain
* @param _amount The amount of tokens to send
* @param _signature The signature of the user
* @param _nonce The nonce of the user
* @param _deadline The deadline for the message to be executed
* @param _minGasLimit Minimum gas limit that the message can be executed with
*/
function sendMessage(
address _signer,
address _to,
uint256 _amount,
bytes calldata _signature,
uint256 _nonce,
uint256 _deadline,
uint32 _minGasLimit
) external override {
if (_to == address(0)) revert IOpUSDCBridgeAdapter_InvalidAddress();
// Ensure the address is not blacklisted
if (IUSDC(USDC).isBlacklisted(_to)) revert IOpUSDCBridgeAdapter_BlacklistedAddress();
// Ensure messaging is enabled
if (messengerStatus != Status.Active) revert IOpUSDCBridgeAdapter_MessagingDisabled();
// Ensure the nonce has not already been used
if (userNonces[_signer][_nonce]) revert IOpUSDCBridgeAdapter_InvalidNonce();
// Ensure the deadline has not passed
if (block.timestamp > _deadline) revert IOpUSDCBridgeAdapter_MessageExpired();
BridgeMessage memory _message =
BridgeMessage({to: _to, amount: _amount, deadline: _deadline, nonce: _nonce, minGasLimit: _minGasLimit});
_checkSignature(_signer, _hashMessageStruct(_message), _signature);
// Mark the nonce as used
userNonces[_signer][_nonce] = true;
_sendMessage(_signer, _to, _amount, _minGasLimit);
}
/**
* @notice Receive the message from the other chain and mint the bridged representation for the user
* @dev This function should only be called when receiving a message to mint the bridged representation
* @dev If the mint fails the funds might be recovered by calling withdrawLockedFunds
* @param _user The user to mint the bridged representation for
* @param _spender The address that provided the tokens
* @param _amount The amount of tokens to mint
*/
function receiveMessage(address _user, address _spender, uint256 _amount) external override onlyLinkedAdapter {
if (messengerStatus == Status.Deprecated) {
uint32 _minGasLimit = 150_000;
// Return the funds to the spender in case the target on L2 is a contract that can´t handle the funds on L1
ICrossDomainMessenger(MESSENGER).sendMessage(
LINKED_ADAPTER, abi.encodeCall(IOpUSDCBridgeAdapter.receiveMessage, (_spender, _spender, _amount)), _minGasLimit
);
emit ReplayedFundsSentBackToL1(_spender, _amount);
} else {
// Mint the tokens to the user
try IUSDC(USDC).mint(_user, _amount) {
emit MessageReceived(_spender, _user, _amount, MESSENGER);
} catch {
// If the mint fails, the user could be locked for multiple reasons such as blacklist or usdc being paused
lockedFundsDetails[_spender][_user] += _amount;
emit MessageFailed(_spender, _user, _amount, MESSENGER);
}
}
}
/**
* @notice Mints the locked funds from the contract in case they get unlocked
* @dev Returns the funds to the spender through a message to L1 if the contract is deprecated
* @param _spender The address that provided the tokens
* @param _user The user to withdraw the funds for
*/
function withdrawLockedFunds(address _spender, address _user) external override {
uint256 _amount = lockedFundsDetails[_spender][_user];
lockedFundsDetails[_spender][_user] = 0;
if (messengerStatus != Status.Deprecated) {
// The check for if the user is blacklisted happens in USDC's contract
IUSDC(USDC).mint(_user, _amount);
emit LockedFundsWithdrawn(_user, _amount);
} else {
uint32 _minGasLimit = 150_000;
// Send the message to the linked adapter
ICrossDomainMessenger(MESSENGER).sendMessage(
LINKED_ADAPTER,
abi.encodeCall(IL1OpUSDCBridgeAdapter.receiveWithdrawLockedFundsPostMigration, (_spender, _amount)),
_minGasLimit
);
emit LockedFundsSentBackToL1(_spender, _amount);
}
}
/*///////////////////////////////////////////////////////////////
BRIDGED USDC FUNCTIONS
///////////////////////////////////////////////////////////////*/
/**
* @notice Call with abitrary calldata on USDC contract.
* @dev can't execute the following list of transactions:
* • transferOwnership (0xf2fde38b)
* • changeAdmin (0x8f283970)
* @dev UpgradeTo and UpgradeToAndCall go through the fallback admin
* @param _data The calldata to execute on the USDC contract
*/
function callUsdcTransaction(bytes calldata _data) external onlyOwner {
bytes4 _selector = bytes4(_data);
bool _success;
if (
_selector == _TRANSFER_OWNERSHIP_SELECTOR || _selector == _CHANGE_ADMIN_SELECTOR
|| _selector == _UPDATE_MASTER_MINTER_SELECTOR
) {
revert IOpUSDCBridgeAdapter_ForbiddenTransaction();
} else if (_selector == _UPGRADE_TO_SELECTOR || _selector == _UPGRADE_TO_AND_CALL_SELECTOR) {
(_success,) = address(FALLBACK_PROXY_ADMIN).call(_data);
} else {
(_success,) = USDC.call(_data);
}
if (!_success) {
revert IOpUSDCBridgeAdapter_InvalidTransaction();
}
emit USDCFunctionSent(_selector);
}
/*///////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
///////////////////////////////////////////////////////////////*/
/**
* @notice Send the message to the linked adapter
* @param _from address that originated the message
* @param _to target address on the destination chain
* @param _amount amount of tokens to be bridged
* @param _minGasLimit minimum gas limit for the other chain to execute the message
*/
function _sendMessage(address _from, address _to, uint256 _amount, uint32 _minGasLimit) internal {
IUSDC(USDC).safeTransferFrom(_from, address(this), _amount);
// Burn the tokens
IUSDC(USDC).burn(_amount);
// Send the message to the linked adapter
ICrossDomainMessenger(MESSENGER).sendMessage(
LINKED_ADAPTER, abi.encodeCall(IOpUSDCBridgeAdapter.receiveMessage, (_to, _from, _amount)), _minGasLimit
);
emit MessageSent(_from, _to, _amount, MESSENGER, _minGasLimit);
}
}
L2OpUSDCDeploy.sol 122 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import {ERC1967Proxy} from '@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol';
import {L2OpUSDCBridgeAdapter} from 'contracts/L2OpUSDCBridgeAdapter.sol';
import {USDC_PROXY_CREATION_CODE} from 'contracts/utils/USDCProxyCreationCode.sol';
import {IL2OpUSDCDeploy} from 'interfaces/IL2OpUSDCDeploy.sol';
import {IUSDC} from 'interfaces/external/IUSDC.sol';
import {OpUSDCBridgeAdapter} from 'src/contracts/universal/OpUSDCBridgeAdapter.sol';
/**
* @title L2OpUSDCDeploy
* @notice Deployer contract for deploying the L2 USDC implementation, proxy, and `L2OpUSDCBridgeAdapter` contract,
* all at once on the `deploy` function.
* @dev The salt is always different for each deployed instance of this contract on the L1 Factory, and the L2 contracts
* are deployed with `CREATE` to guarantee that the addresses are unique among all the L2s, so we avoid a scenario where
* L2 contracts have the same address on different L2s when triggered by different owners.
*/
contract L2OpUSDCDeploy is IL2OpUSDCDeploy {
address internal constant _L2_MESSENGER = 0x4200000000000000000000000000000000000007;
/**
* @notice Deploys the USDC implementation, proxy, and L2 adapter contracts all at once, and then initializes the USDC
* @param _l1Adapter The address of the L1 adapter contract
* @param _l2AdapterOwner The address of the L2 adapter owner
* @param _usdcImplAddr The address of the USDC implementation on L2 to connect the proxy to
* @param _usdcInitializeData The USDC name, symbol, currency, and decimals used on the first `initialize()` call
* @param _usdcInitTxs The initialization transactions for the USDC proxy and implementation contracts
* @dev The USDC proxy owner needs to be set on the first init tx, and will be set to the L2 adapter address
* @dev Using `CREATE` to guarantee that the addresses are unique among all the L2s
*/
constructor(
address _l1Adapter,
address _l2AdapterOwner,
address _usdcImplAddr,
USDCInitializeData memory _usdcInitializeData,
bytes[] memory _usdcInitTxs
) {
// Deploy USDC proxy
bytes memory _usdcProxyCArgs = abi.encode(_usdcImplAddr);
bytes memory _usdcProxyInitCode = bytes.concat(USDC_PROXY_CREATION_CODE, _usdcProxyCArgs);
// 1st nonce
address _usdcProxy = _deployCreate(_usdcProxyInitCode);
emit USDCProxyDeployed(_usdcProxy);
// Deploy L2 Adapter implementation and proxy, initializing it with the owner
// 2nd nonce
address _l2AdapterImpl = address(new L2OpUSDCBridgeAdapter(_usdcProxy, _L2_MESSENGER, _l1Adapter));
// 3rd nonce
address _l2Adapter =
address(new ERC1967Proxy(_l2AdapterImpl, abi.encodeCall(OpUSDCBridgeAdapter.initialize, _l2AdapterOwner)));
emit L2AdapterDeployed(_l2Adapter);
// Deploy the FallbackProxyAdmin internally in the L2 Adapter to keep it unique
address _fallbackProxyAdmin = address(L2OpUSDCBridgeAdapter(_l2Adapter).FALLBACK_PROXY_ADMIN());
// Change the USDC admin so the init txs can be executed over the proxy from this contract
IUSDC(_usdcProxy).changeAdmin(_fallbackProxyAdmin);
// Execute the USDC initialization transactions over the USDC proxy
_executeInitTxs(_usdcProxy, _usdcInitializeData, _l2Adapter, _usdcInitTxs);
}
/**
* @notice Executes the initialization transactions for a target contract
* @param _usdc The address of the contract to execute the transactions on
* @param _usdcInitializeData The USDC name, symbol, currency, and decimals used on the first `initialize()` call
* @param _l2Adapter The address of the L2 adapter
* @param _initTxs The initialization transactions to execute
* @dev The first `initialize()` call is defined here to ensure it is properly done, granting the right permissions
* to the L2 adapter contract. The L2 factory is set as master minter first so it can configure the l2 adapter as
* unlimited minter and then the master minter is updated again to the l2 adapter
*/
function _executeInitTxs(
address _usdc,
USDCInitializeData memory _usdcInitializeData,
address _l2Adapter,
bytes[] memory _initTxs
) internal {
// Initialize the USDC contract
IUSDC(_usdc).initialize(
_usdcInitializeData.tokenName,
_usdcInitializeData.tokenSymbol,
_usdcInitializeData.tokenCurrency,
_usdcInitializeData.tokenDecimals,
address(this),
_l2Adapter,
_l2Adapter,
address(this)
);
// Add l2 adapter as unlimited minter
IUSDC(_usdc).configureMinter(_l2Adapter, type(uint256).max);
// Set l2 adapter as new master minter
IUSDC(_usdc).updateMasterMinter(_l2Adapter);
// Transfer USDC ownership to the L2 adapter
IUSDC(_usdc).transferOwnership(_l2Adapter);
// Execute the input init txs, use `_i+1` as revert argument since the first tx is already executed on the contract
for (uint256 _i; _i < _initTxs.length; _i++) {
(bool _success,) = _usdc.call(_initTxs[_i]);
if (!_success) {
revert IL2OpUSDCDeploy_InitializationFailed(_i + 1);
}
}
}
/**
* @notice Deploys a new contract via calling the `CREATE` opcode
* @param _initCode The creation bytecode.
* @return _newContract The 20-byte address where the contract was deployed.
*/
function _deployCreate(bytes memory _initCode) internal returns (address _newContract) {
assembly ("memory-safe") {
_newContract := create(0x0, add(_initCode, 0x20), mload(_initCode))
}
if (_newContract == address(0) || _newContract.code.length == 0) {
revert IL2OpUSDCDeploy_DeploymentFailed();
}
}
}
OpUSDCBridgeAdapter.sol 159 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import {UUPSUpgradeable} from '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';
import {EIP712Upgradeable} from '@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol';
import {MessageHashUtils} from '@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol';
import {SignatureChecker} from '@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol';
import {IOpUSDCBridgeAdapter} from 'interfaces/IOpUSDCBridgeAdapter.sol';
import {ICrossDomainMessenger} from 'interfaces/external/ICrossDomainMessenger.sol';
abstract contract OpUSDCBridgeAdapter is UUPSUpgradeable, OwnableUpgradeable, EIP712Upgradeable, IOpUSDCBridgeAdapter {
using MessageHashUtils for bytes32;
using SignatureChecker for address;
/// @notice The typehash for the bridge message
bytes32 public constant BRIDGE_MESSAGE_TYPEHASH =
keccak256('BridgeMessage(address to,uint256 amount,uint256 deadline,uint256 nonce,uint32 minGasLimit)');
/// @inheritdoc IOpUSDCBridgeAdapter
address public immutable USDC;
/// @inheritdoc IOpUSDCBridgeAdapter
address public immutable LINKED_ADAPTER;
/// @inheritdoc IOpUSDCBridgeAdapter
address public immutable MESSENGER;
/// @inheritdoc IOpUSDCBridgeAdapter
Status public messengerStatus;
/// @inheritdoc IOpUSDCBridgeAdapter
mapping(address _user => mapping(uint256 _nonce => bool _used)) public userNonces;
/// @inheritdoc IOpUSDCBridgeAdapter
mapping(address _spender => mapping(address _user => uint256 _lockedAmount)) public lockedFundsDetails;
/// @notice Reserve 50 storage slots to be safe on future upgrades
uint256[50] private __gap;
/**
* @notice Modifier to check if the sender is the linked adapter through the messenger
*/
modifier onlyLinkedAdapter() {
if (msg.sender != MESSENGER || ICrossDomainMessenger(MESSENGER).xDomainMessageSender() != LINKED_ADAPTER) {
revert IOpUSDCBridgeAdapter_InvalidSender();
}
_;
}
/**
* @notice Construct the OpUSDCBridgeAdapter contract
* @param _usdc The address of the USDC Contract to be used by the adapter
* @param _messenger The address of the messenger contract
* @param _linkedAdapter The address of the linked adapter
*/
// solhint-disable-next-line no-unused-vars
constructor(address _usdc, address _messenger, address _linkedAdapter) {
USDC = _usdc;
MESSENGER = _messenger;
LINKED_ADAPTER = _linkedAdapter;
_disableInitializers();
}
/**
* @notice Initialize the contract
* @param _owner The owner of the contract
*/
function initialize(address _owner) external virtual initializer {}
/*///////////////////////////////////////////////////////////////
MESSAGING
///////////////////////////////////////////////////////////////*/
/**
* @notice Send tokens to another chain through the linked adapter
* @param _to The target address on the destination chain
* @param _amount The amount of tokens to send
* @param _minGasLimit Minimum gas limit that the message can be executed with
*/
function sendMessage(address _to, uint256 _amount, uint32 _minGasLimit) external virtual;
/**
* @notice Send signer tokens to another chain through the linked adapter
* @param _signer The address of the user sending the message
* @param _to The target address on the destination chain
* @param _amount The amount of tokens to send
* @param _signature The signature of the user
* @param _nonce The nonce of the user
* @param _deadline The deadline for the message to be executed
* @param _minGasLimit Minimum gas limit that the message can be executed with
*/
function sendMessage(
address _signer,
address _to,
uint256 _amount,
bytes calldata _signature,
uint256 _nonce,
uint256 _deadline,
uint32 _minGasLimit
) external virtual;
/**
* @notice Receive the message from the other chain and mint or transfer tokens to the user
* @dev This function should only be called when receiving a message to mint or transfer tokens
* @param _user The user to mint or transfer the tokens for
* @param _spender The address that provided the tokens
* @param _amount The amount of tokens to transfer or mint
*/
function receiveMessage(address _user, address _spender, uint256 _amount) external virtual;
/**
* @notice Withdraws the locked funds from the contract if they get unlocked
* @param _spender The address that provided the tokens
* @param _user The user to withdraw the funds for
*/
function withdrawLockedFunds(address _spender, address _user) external virtual;
/**
* @notice Cancels a signature by setting the nonce as used
* @param _nonce The nonce of the signature to cancel
*/
function cancelSignature(uint256 _nonce) external {
userNonces[msg.sender][_nonce] = true;
emit NonceCanceled(msg.sender, _nonce);
}
/**
* @notice Checks the caller is the owner to authorize the upgrade
*/
function _authorizeUpgrade(address) internal virtual override onlyOwner {}
/**
* @notice Check the signature of a message
* @param _signer the address that signed the message
* @param _messageHash the hash of the message that was signed
* @param _signature the signature of the message
*/
function _checkSignature(address _signer, bytes32 _messageHash, bytes memory _signature) internal view {
// Uses the EIP712Upgradeable typed data hash
_messageHash = _hashTypedDataV4(_messageHash);
if (!_signer.isValidSignatureNow(_messageHash, _signature)) revert IOpUSDCBridgeAdapter_InvalidSignature();
}
/**
* @notice Hashes the bridge message struct
* @param _message The bridge message struct to hash
* @return _hash The hash of the bridge message struct
*/
function _hashMessageStruct(BridgeMessage memory _message) internal pure returns (bytes32 _hash) {
_hash = keccak256(
abi.encode(
BRIDGE_MESSAGE_TYPEHASH, _message.to, _message.amount, _message.deadline, _message.nonce, _message.minGasLimit
)
);
}
}
FallbackProxyAdmin.sol 53 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {IUSDC} from 'interfaces/external/IUSDC.sol';
/**
* @title FallbackProxyAdmin
* @notice Middleware contract for the L2 Adapter to interact with the USDC proxy.
* @dev The admin can't call the fallback function of the USDC proxy, meaning it can't interact with the functions
* such as mint and burn between others. Because of this, the FallbackProxyAdmin contract is used as a middleware,
* being controlled by the L2OpUSDCBridgeAdapter contract and allowing to call the admin functions through it while
* also being able to call the fallback function of the USDC proxy.
*/
contract FallbackProxyAdmin is Ownable {
/// @notice USDC address
address public immutable USDC;
/**
* @notice Construct the FallbackProxyAdmin contract
* @param _usdc USDC address
*/
constructor(address _usdc) Ownable(msg.sender) {
USDC = _usdc;
}
/**
* @notice Changes the admin of the USDC proxy
* @param _newAdmin Address to transfer proxy administration to
* @dev Owner should always be the L2 Adapter
* @dev USDC admin cant interact proxy with implementation so we use this contract as the middleman
*/
function changeAdmin(address _newAdmin) external onlyOwner {
IUSDC(USDC).changeAdmin(_newAdmin);
}
/**
* @notice Function to upgrade the usdc proxy to a new implementation
* @param _newImplementation Address of the new implementation
*/
function upgradeTo(address _newImplementation) external onlyOwner {
IUSDC(USDC).upgradeTo(_newImplementation);
}
/**
* @notice Upgrades the USDC proxy to a new implementation and calls a function on the new implementation
* @param _newImplementation Address of the new implementation
* @param _data Data to call on the new implementation
*/
function upgradeToAndCall(address _newImplementation, bytes calldata _data) external onlyOwner {
IUSDC(USDC).upgradeToAndCall(_newImplementation, _data);
}
}
USDCProxyCreationCode.sol 8 lines
// SPDX-License-Identifier: MIT pragma solidity 0.8.25; // Native USDC proxy contract bytecode on mainnet: // https://optimistic.etherscan.io/token/0x0b2c639c533813f4aa9d7837caf62653d097ff85#code bytes constant USDC_PROXY_CREATION_CODE = // solhint-disable-next-line max-line-length hex'608060405234801561001057600080fd5b506040516108a93803806108a98339818101604052602081101561003357600080fd5b5051808061004081610051565b5061004a336100c3565b5050610123565b610064816100e760201b61042a1760201c565b61009f5760405162461bcd60e51b815260040180806020018281038252603b81526020018061086e603b913960400191505060405180910390fd5b7f7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c355565b7f10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b55565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47081811480159061011b57508115155b949350505050565b61073c806101326000396000f3fe60806040526004361061005a5760003560e01c80635c60da1b116100435780635c60da1b146101315780638f2839701461016f578063f851a440146101af5761005a565b80633659cfe6146100645780634f1ef286146100a4575b6100626101c4565b005b34801561007057600080fd5b506100626004803603602081101561008757600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166101de565b610062600480360360408110156100ba57600080fd5b73ffffffffffffffffffffffffffffffffffffffff82351691908101906040810160208201356401000000008111156100f257600080fd5b82018360208201111561010457600080fd5b8035906020019184600183028401116401000000008311171561012657600080fd5b509092509050610232565b34801561013d57600080fd5b50610146610309565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b34801561017b57600080fd5b506100626004803603602081101561019257600080fd5b503573ffffffffffffffffffffffffffffffffffffffff16610318565b3480156101bb57600080fd5b50610146610420565b6101cc610466565b6101dc6101d76104fa565b61051f565b565b6101e6610543565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614156102275761022281610568565b61022f565b61022f6101c4565b50565b61023a610543565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614156102fc5761027683610568565b60003073ffffffffffffffffffffffffffffffffffffffff16348484604051808383808284376040519201945060009350909150508083038185875af1925050503d80600081146102e3576040519150601f19603f3d011682016040523d82523d6000602084013e6102e8565b606091505b50509050806102f657600080fd5b50610304565b6103046101c4565b505050565b60006103136104fa565b905090565b610320610543565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614156102275773ffffffffffffffffffffffffffffffffffffffff81166103bf576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260368152602001806106966036913960400191505060405180910390fd5b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6103e8610543565b6040805173ffffffffffffffffffffffffffffffffffffffff928316815291841660208301528051918290030190a1610222816105bd565b6000610313610543565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47081811480159061045e57508115155b949350505050565b61046e610543565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614156104f2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260328152602001806106646032913960400191505060405180910390fd5b6101dc6101dc565b7f7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c35490565b3660008037600080366000845af43d6000803e80801561053e573d6000f35b3d6000fd5b7f10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b5490565b610571816105e1565b6040805173ffffffffffffffffffffffffffffffffffffffff8316815290517fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b9181900360200190a150565b7f10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b55565b6105ea8161042a565b61063f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252603b8152602001806106cc603b913960400191505060405180910390fd5b7f7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c35556fe43616e6e6f742063616c6c2066616c6c6261636b2066756e6374696f6e2066726f6d207468652070726f78792061646d696e43616e6e6f74206368616e6765207468652061646d696e206f6620612070726f787920746f20746865207a65726f206164647265737343616e6e6f742073657420612070726f787920696d706c656d656e746174696f6e20746f2061206e6f6e2d636f6e74726163742061646472657373a2646970667358221220046bec85a39556fa01d3014f9bbd881bf3dfd8a920836836698508b80c55e88964736f6c634300060c003343616e6e6f742073657420612070726f787920696d706c656d656e746174696f6e20746f2061206e6f6e2d636f6e74726163742061646472657373';
IL1OpUSDCBridgeAdapter.sol 91 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
interface IL1OpUSDCBridgeAdapter {
/*///////////////////////////////////////////////////////////////
EVENTS
///////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when the burn amount is set
* @param _burnAmount The amount to be burned
*/
event BurnAmountSet(uint256 _burnAmount);
/**
* @notice Emitted when the migration process is complete
* @param _burnedAmount The amount of USDC tokens that were burned
*/
event MigrationComplete(uint256 _burnedAmount);
/*///////////////////////////////////////////////////////////////
LOGIC
///////////////////////////////////////////////////////////////*/
/**
* @notice Initiates the process to migrate the bridged USDC to native USDC
* @param _roleCaller The address that will be allowed to transfer the usdc roles
* @param _burnCaller The address that will be allowed to call this contract to burn the USDC tokens
* @param _minGasLimitReceiveOnL2 Minimum gas limit that the message can be executed with on L2
* @param _minGasLimitSetBurnAmount Minimum gas limit that the message can be executed with to set the burn amount
*/
function migrateToNative(
address _roleCaller,
address _burnCaller,
uint32 _minGasLimitReceiveOnL2,
uint32 _minGasLimitSetBurnAmount
) external;
/**
* @notice Sets the amount of USDC tokens that will be burned when the burnLockedUSDC function is called
* @param _amount The amount of USDC tokens that will be burned
* @dev Only callable by a whitelisted messenger during its migration process
*/
function setBurnAmount(uint256 _amount) external;
/**
* @notice Burns the USDC tokens locked in the contract
* @dev The amount is determined by the burnAmount variable, which is set in the setBurnAmount function
*/
function burnLockedUSDC() external;
/**
* @notice Send a message to the linked adapter to call receiveStopMessaging() and stop outgoing messages.
* @dev Only callable by the owner of the adapter
* @dev Setting isMessagingDisabled to true is an irreversible operation
* @param _minGasLimit Minimum gas limit that the message can be executed with
*/
function stopMessaging(uint32 _minGasLimit) external;
/**
* @notice Resume messaging on the messenger
* @dev Only callable by the owner
* @dev Can't resume deprecated messengers
* @param _minGasLimit Minimum gas limit that the message can be executed with
*/
function resumeMessaging(uint32 _minGasLimit) external;
/**
* @notice Receives a message from L2 if the adapter is deprecated and a user is withdrawing locked funds
* @dev If the _spender is still locked, the user will be forced to replay this message
* @param _spender The user that initially provided the tokens
* @param _amount The amount of tokens to withdraw
*/
function receiveWithdrawLockedFundsPostMigration(address _spender, uint256 _amount) external;
/*///////////////////////////////////////////////////////////////
VARIABLES
///////////////////////////////////////////////////////////////*/
/**
* @notice Fetches the amount of USDC tokens that will be burned when the burnLockedUSDC function is called
* @return _burnAmount The amount of USDC tokens that will be burned
*/
function burnAmount() external view returns (uint256 _burnAmount);
/**
* @notice Fetches the address of the burn caller
* @return _burnCaller The address of the burn caller
*/
function burnCaller() external view returns (address _burnCaller);
}
IL1OpUSDCFactory.sol 111 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import {IUSDC} from './external/IUSDC.sol';
// solhint-disable func-name-mixedcase
interface IL1OpUSDCFactory {
/**
* @notice The struct to hold the deployments data to deploy the L2 Factory, L2 adapter, and the L2 USDC contracts
* @param l2AdapterOwner The address of the owner of the L2 adapter
* @param usdcImplAddr The address of the USDC implementation on L2 to connect the proxy to
* @param minGasLimitDeploy The minimum gas limit for deploying the L2 Deploy, L2 adapter, and L2 USDC proxy
* @param usdcInitTxs The initialization transactions to be executed on the USDC contract. The `initialize()` first
* init tx must not be included since it is defined in the L2 factory contract
*/
struct L2Deployments {
address l2AdapterOwner;
address usdcImplAddr;
uint32 minGasLimitDeploy;
bytes[] usdcInitTxs;
}
/*///////////////////////////////////////////////////////////////
EVENTS
///////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when the `L1OpUSDCBridgeAdapter` is deployed
* @param _l1Adapter The address of the L1 adapter
* @param _l2Deploy The address of the L2 deployer contract
* @param _l2Adapter The address of the L2 adapter
*/
event ProtocolDeployed(address _l1Adapter, address _l2Deploy, address _l2Adapter);
/*///////////////////////////////////////////////////////////////
ERRORS
///////////////////////////////////////////////////////////////*/
/**
* @notice Thrown when the `initialize()` tx is provided as the first init tx for the USDC contract
*/
error IL1OpUSDCFactory_NoInitializeTx();
/*///////////////////////////////////////////////////////////////
LOGIC
///////////////////////////////////////////////////////////////*/
/**
* @notice Deploys the L1 Adapter, and sends the deployment txs for the L2 factory, L2 adapter and the L2 USDC through
* the L1 messenger
* @param _l1Messenger The address of the L1 messenger for the L2 Op chain
* @param _l1AdapterOwner The address of the owner of the L1 adapter
* @param _chainName The name of the L2 Op chain
* @param _l2Deployments The deployments data for the L2 adapter, and the L2 USDC contracts
* @return _l1Adapter The address of the L1 adapter
* @return _l2Deploy The address of the L2 deployer contract
* @return _l2Adapter The address of the L2 adapter
* @dev It can fail on L2 due to a gas miscalculation, but in that case the tx can be replayed. It only deploys 1 L2
* factory per L2 deployments, to make sure the nonce is being tracked correctly while precalculating addresses
* @dev The implementation of the USDC contract needs to be deployed on L2 before this is called
* Then set the `usdcImplAddr` in the L2Deployments struct to the address of the deployed USDC implementation contract
*
* @dev IMPORTANT!!!!
* The _l2Deployments.usdcInitTxs must be manually entered to correctly initialize the USDC contract on L2.
* If a function is not included in the init txs, it could lead to potential attack vectors.
* We currently hardcode the `initialize()` function in the L2 factory contract, to correctly configure the setup
* You must provide the following init txs:
* - initalizeV2
* - initilizeV2_1
* - initializeV2_2
*
* It is also important to note that circle may add more init functions in future implementations
* This is up to the deployer to check and be sure all init transactions are included
*/
function deploy(
address _l1Messenger,
address _l1AdapterOwner,
string calldata _chainName,
L2Deployments calldata _l2Deployments
) external returns (address _l1Adapter, address _l2Deploy, address _l2Adapter);
/*///////////////////////////////////////////////////////////////
VARIABLES
///////////////////////////////////////////////////////////////*/
/**
* @return _l2Create2Deployer The address of the `create2Deployer` contract on L2
*/
function L2_CREATE2_DEPLOYER() external view returns (address _l2Create2Deployer);
/**
* @return _usdc The address of USDC on L1
*/
function USDC() external view returns (IUSDC _usdc);
/**
* @return _name The name of the USDC token
* @dev If the 3rd party team wants to update the name, it can be done on the `initialize2()` 2nd init tx
*/
function USDC_NAME() external view returns (string memory _name);
/**
* @return _symbol The symbol of the USDC token
*/
function USDC_SYMBOL() external view returns (string memory _symbol);
/**
* @return _deploymentsSaltCounter The counter for the deployments salt to be used on the L2 factory deployment
*/
function deploymentsSaltCounter() external view returns (uint256 _deploymentsSaltCounter);
}
IL2OpUSDCBridgeAdapter.sol 91 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import {FallbackProxyAdmin} from 'contracts/utils/FallbackProxyAdmin.sol';
interface IL2OpUSDCBridgeAdapter {
/*///////////////////////////////////////////////////////////////
EVENTS
///////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when the owner message is sent
* @param _functionSignature The signature of the function sent
*/
event USDCFunctionSent(bytes4 _functionSignature);
/**
* @notice Emitted when a `receiveMessage` call message is replayed after the adapter was deprecated
* @param _spender The address that provided the tokens
* @param _amount The amount of USDC sent back to L1
*/
event ReplayedFundsSentBackToL1(address _spender, uint256 _amount);
/**
* @notice Emitted when the locked funds are sent back to L1
* @param _spender The address that provided the tokens
* @param _amountSent The amount of tokens that were withdrawn
*/
event LockedFundsSentBackToL1(address indexed _spender, uint256 _amountSent);
/*///////////////////////////////////////////////////////////////
LOGIC
///////////////////////////////////////////////////////////////*/
/**
* @notice Initiates the process to migrate the bridged USDC to native USDC
* @dev Full migration can't finish until L1 receives the message for setting the burn amount
* @param _roleCaller The address that will be allowed to transfer the USDC roles
* @param _setBurnAmountMinGasLimit Minimum gas limit that the setBurnAmount message can be executed on L1
*/
function receiveMigrateToNative(address _roleCaller, uint32 _setBurnAmountMinGasLimit) external;
/**
* @notice Transfer the USDC roles to the new owner
* @param _owner The address to transfer ownership to
* @dev Can only be called by the role caller set in the migration process
*/
function transferUSDCRoles(address _owner) external;
/**
* @notice Receive the stop messaging message from the linked adapter and stop outgoing messages
*/
function receiveStopMessaging() external;
/**
* @notice Resume messaging after it was stopped
*/
function receiveResumeMessaging() external;
/**
* @notice Call with arbitrary calldata on USDC contract.
* @dev can't execute the following list of transactions:
* • transferOwnership (0xf2fde38b)
* • changeAdmin (0x8f283970)
* @dev UpgradeTo and UpgradeToAndCall go through the fallback admin
* @param _data The calldata to execute on the USDC contract
*/
function callUsdcTransaction(bytes calldata _data) external;
/*///////////////////////////////////////////////////////////////
VARIABLES
///////////////////////////////////////////////////////////////*/
/**
* @notice Fetches the address of the role caller
* @return _roleCaller The address of the role caller
*/
function roleCaller() external view returns (address _roleCaller);
/**
* @return _fallbackProxyAdmin The address of the fallback proxy admin
* @dev The admin can't call the fallback function of the USDC proxy, meaning it can't interact with the functions
* such as mint and burn between others. Because of this, the FallbackProxyAdmin contract is used as a middleware,
* being controlled by the L2OpUSDCBridgeAdapter contract and allowing to call the admin functions through it while
* also being able to call the fallback function of the USDC proxy.
* @dev Declared with immutable notation even though it is not defined on the constructor because it is set on the
* `initialize` function which replicates the behavior of the constructor.
*/
// solhint-disable-next-line func-name-mixedcase
function FALLBACK_PROXY_ADMIN() external view returns (FallbackProxyAdmin _fallbackProxyAdmin);
}
IL2OpUSDCDeploy.sol 59 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
interface IL2OpUSDCDeploy {
/*///////////////////////////////////////////////////////////////
STRUCTS
///////////////////////////////////////////////////////////////*/
/**
* @notice The struct to hold the USDC data for the name, symbol, currency, and decimals when initializing
* @param tokenName The name of the USDC token
* @param tokenSymbol The symbol of the USDC token
* @param tokenCurrency The currency that the USDC token represents
* @param tokenDecimals The number of decimals that the USDC token uses
*/
struct USDCInitializeData {
string tokenName;
string tokenSymbol;
string tokenCurrency;
uint8 tokenDecimals;
}
/*///////////////////////////////////////////////////////////////
EVENTS
///////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when the USDC implementation is deployed
* @param _l2UsdcImplementation The address of the L2 USDC implementation
*/
event USDCImplementationDeployed(address _l2UsdcImplementation);
/**
* @notice Emitted when the USDC proxy is deployed
* @param _l2UsdcProxy The address of the L2 USDC proxy
*/
event USDCProxyDeployed(address _l2UsdcProxy);
/**
* @notice Emitted when the L2 adapter is deployed
* @param _l2Adapter The address of the L2 adapter
*/
event L2AdapterDeployed(address _l2Adapter);
/*///////////////////////////////////////////////////////////////
ERRORS
///////////////////////////////////////////////////////////////*/
/**
* @notice Thrown when a contract deployment fails
*/
error IL2OpUSDCDeploy_DeploymentFailed();
/**
* @notice Thrown when an USDC initialization tx failed
* @param _txIndex The index of the failed initialization tx
*/
error IL2OpUSDCDeploy_InitializationFailed(uint256 _txIndex);
}
IOpUSDCBridgeAdapter.sol 294 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
interface IOpUSDCBridgeAdapter {
/*///////////////////////////////////////////////////////////////
ENUMS
///////////////////////////////////////////////////////////////*/
/**
* @notice The status of an L1 Messenger
* @param Active The messenger is active
* @param Paused The messenger is paused
* @param Upgrading The messenger is upgrading
* @param Deprecated The messenger is deprecated
*/
enum Status {
Active,
Paused,
Upgrading,
Deprecated
}
/*///////////////////////////////////////////////////////////////
STRUCTS
///////////////////////////////////////////////////////////////*/
/**
* @notice The struct to hold the data for a bridge message with signature
* @param to The target address on the destination chain
* @param amount The amount of tokens to send
* @param deadline The deadline for the message to be executed
* @param nonce The nonce of the user
* @param minGasLimit The minimum gas limit for the message to be executed
*/
struct BridgeMessage {
address to;
uint256 amount;
uint256 deadline;
uint256 nonce;
uint32 minGasLimit;
}
/*///////////////////////////////////////////////////////////////
EVENTS
///////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when messaging is stopped
* @param _messenger The address of the messenger contract that was stopped
*/
event MessagingStopped(address _messenger);
/**
* @notice Emitted when a message is sent to the linked adapter
* @param _user The user that sent the message
* @param _to The target address on the destination chain
* @param _amount The amount of tokens to send
* @param _messenger The address of the messenger contract that was sent through
* @param _minGasLimit Minimum gas limit that the message can be executed with
*/
event MessageSent(
address indexed _user, address indexed _to, uint256 _amount, address indexed _messenger, uint32 _minGasLimit
);
/**
* @notice Emitted when a message as received
* @param _spender The address that provided the tokens
* @param _user The user that received the message
* @param _amount The amount of tokens received
* @param _messenger The address of the messenger contract that was received through
*/
event MessageReceived(address indexed _spender, address indexed _user, uint256 _amount, address indexed _messenger);
/**
* @notice Emitted when messaging is resumed
* @param _messenger The address of the messenger that was resumed
*/
event MessagingResumed(address _messenger);
/**
* @notice Emitted when the adapter is migrating usdc to native
* @param _messenger The address of the messenger contract that is doing the migration
* @param _caller The address that will be allowed to call the permissioned function on the given chain
* @dev On L1 _caller can call burnLockedUSDC
* @dev On L2 _caller can call transferUSDCRoles
*/
event MigratingToNative(address _messenger, address _caller);
/**
* @notice Emitted when a message fails
* @param _spender The address that provided the tokens
* @param _user The user that the message failed for
* @param _amount The amount of tokens that were added to the blacklisted funds
* @param _messenger The address of the messenger that the message failed for
*/
event MessageFailed(address indexed _spender, address indexed _user, uint256 _amount, address indexed _messenger);
/**
* @notice Emitted when the any previously locked funds are withdrawn outside of the traditional bridging flows
* @param _user The user that the funds were withdrawn for
* @param _amountWithdrawn The amount of tokens that were withdrawn
*/
event LockedFundsWithdrawn(address indexed _user, uint256 _amountWithdrawn);
/**
* @notice Emitted when a nonce is canceled
* @param _caller The caller
* @param _nonce The nonce that was canceled
*/
event NonceCanceled(address _caller, uint256 _nonce);
/*///////////////////////////////////////////////////////////////
ERRORS
///////////////////////////////////////////////////////////////*/
/**
* @notice Error when burnLockedUSDC is called before a burn amount is set
*/
error IOpUSDCBridgeAdapter_BurnAmountNotSet();
/**
* @notice Error when the caller is not the roleCaller
*/
error IOpUSDCBridgeAdapter_InvalidCaller();
/**
* @notice Error when address is not valid
*/
error IOpUSDCBridgeAdapter_InvalidAddress();
/**
* @notice Error when the owner transaction is invalid
*/
error IOpUSDCBridgeAdapter_InvalidTransaction();
/**
* @notice Error when signature is not valid
*/
error IOpUSDCBridgeAdapter_ForbiddenTransaction();
/**
* @notice Error when messaging is disabled
*/
error IOpUSDCBridgeAdapter_MessagingDisabled();
/**
* @notice Error when messaging is enabled
*/
error IOpUSDCBridgeAdapter_MessagingEnabled();
/**
* @notice Error when the caller is not the linked adapter
*/
error IOpUSDCBridgeAdapter_InvalidSender();
/**
* @notice Error when the nonce is already used for the given signature
*/
error IOpUSDCBridgeAdapter_InvalidNonce();
/**
* @notice Error when the signature is invalid
*/
error IOpUSDCBridgeAdapter_InvalidSignature();
/**
* @notice Error when the deadline has passed
*/
error IOpUSDCBridgeAdapter_MessageExpired();
/**
* @notice Error when the contract is not in the upgrading state
*/
error IOpUSDCBridgeAdapter_NotUpgrading();
/**
* @notice Error when the address is blacklisted
*/
error IOpUSDCBridgeAdapter_BlacklistedAddress();
/**
* @notice Error when bridgedUSDC has not been migrated yet to native USDC
*/
error IOpUSDCBridgeAdapter_NotMigrated();
/*///////////////////////////////////////////////////////////////
LOGIC
///////////////////////////////////////////////////////////////*/
/**
* @notice Initialize the contract
* @param _owner The owner of the contract
* @dev This function needs only used during the deployment of the proxy contract, and it is disabled for the
* implementation contract
*/
function initialize(address _owner) external;
/**
* @notice Send tokens to another chain through the linked adapter
* @param _to The target address on the destination chain
* @param _amount The amount of tokens to send
* @param _minGasLimit Minimum gas limit that the message can be executed with
*/
function sendMessage(address _to, uint256 _amount, uint32 _minGasLimit) external;
/**
* @notice Send signer tokens to another chain through the linked adapter
* @param _signer The address of the user sending the message
* @param _to The target address on the destination chain
* @param _amount The amount of tokens to send
* @param _signature The signature of the user
* @param _nonce The nonce of the user
* @param _deadline The deadline for the message to be executed
* @param _minGasLimit Minimum gas limit that the message can be executed with
*/
function sendMessage(
address _signer,
address _to,
uint256 _amount,
bytes calldata _signature,
uint256 _nonce,
uint256 _deadline,
uint32 _minGasLimit
) external;
/**
* @notice Receive the message from the other chain and mint or transfer tokens to the user
* @dev This function should only be called when receiving a message to mint or transfer tokens
* @param _user The user to mint or transfer the tokens for
* @param _spender The address that provided the tokens
* @param _amount The amount of tokens to transfer or mint
*/
function receiveMessage(address _user, address _spender, uint256 _amount) external;
/**
* @notice Withdraws the locked funds from the contract if they get unlocked
* @param _spender The address that provided the tokens
* @param _user The user to withdraw the funds for
*/
function withdrawLockedFunds(address _spender, address _user) external;
/**
* @notice Cancels a signature by setting the nonce as used
* @param _nonce The nonce of the signature to cancel
*/
function cancelSignature(uint256 _nonce) external;
/*///////////////////////////////////////////////////////////////
VARIABLES
///////////////////////////////////////////////////////////////*/
/**
* @notice Fetches address of the USDC token
* @return _usdc Address of the USDC token
*/
// solhint-disable-next-line func-name-mixedcase
function USDC() external view returns (address _usdc);
/**
* @notice Fetches address of the linked adapter on L2 to send messages to and receive from
* @return _linkedAdapter Address of the linked adapter
*/
// solhint-disable-next-line func-name-mixedcase
function LINKED_ADAPTER() external view returns (address _linkedAdapter);
/**
* @notice Fetches address of the CrossDomainMessenger to send messages to L1 <-> L2
* @return _messenger Address of the messenger
*/
// solhint-disable-next-line func-name-mixedcase
function MESSENGER() external view returns (address _messenger);
/**
* @notice Fetches the status of the messenger
* @return _status The status of the messenger
*/
function messengerStatus() external view returns (Status _status);
/**
* @notice Returns the nonce of a given user to avoid replay attacks
* @param _user The user to check for
* @param _nonce The nonce to check for
* @return _used If the nonce has been used
*/
function userNonces(address _user, uint256 _nonce) external view returns (bool _used);
/**
* @notice Returns the amount of funds locked that got locked for a specific user
* @param _spender The address that provided the tokens
* @param _user The user to check for
* @return _lockedAmount The amount of funds locked from locked messages
*/
function lockedFundsDetails(address _spender, address _user) external view returns (uint256 _lockedAmount);
}
ICreate2Deployer.sol 12 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
interface ICreate2Deployer {
/**
* @notice Deploys a contract using the CREATE2 opcode
* @param _value The value to send with the deployment
* @param _salt The salt value to use for the deployment
* @param _code The init code to deploy
*/
function deploy(uint256 _value, bytes32 _salt, bytes memory _code) external;
}
ICrossDomainMessenger.sol 36 lines
pragma solidity 0.8.25;
interface ICrossDomainMessenger {
/**
* @notice Sends a message to some target address on the other chain. Note that if the call
* always reverts, then the message will be unrelayable, and any ETH sent will be
* permanently locked. The same will occur if the target on the other chain is
* considered unsafe (see the _isUnsafeTarget() function).
* @param _target Target contract or wallet address.
* @param _message Message to trigger the target address with.
* @param _minGasLimit Minimum gas limit that the message can be executed with.
*/
function sendMessage(address _target, bytes calldata _message, uint32 _minGasLimit) external;
/**
* @notice Retrieves the address of the contract or wallet that initiated the currently
* executing message on the other chain. Will throw an error if there is no message
* currently being executed. Allows the recipient of a call to see who triggered it.
* @return _sender Address of the sender of the currently executing message on the other chain.
*/
function xDomainMessageSender() external view returns (address _sender);
/**
* @notice Returns the address of the portal.
* @return _portal Address of the portal.
*/
function portal() external view returns (address _portal);
/**
* @notice Returns the address of the portal.
* @dev This is a legacy function that is used for any legacy messengers.
* @return _portal Address of the portal.
*/
// solhint-disable-next-line func-name-mixedcase
function PORTAL() external view returns (address _portal);
}
IOptimismPortal.sol 22 lines
pragma solidity 0.8.25;
interface IOptimismPortal {
/**
* @notice Accepts deposits of ETH and data, and emits a TransactionDeposited event for use in
* deriving deposit transactions. Note that if a deposit is made by a contract, its
* address will be aliased when retrieved using `tx.origin` or `msg.sender`. Consider
* using the CrossDomainMessenger contracts for a simpler developer experience.
* @param _to Target address on L2.
* @param _value ETH value to send to the recipient.
* @param _gasLimit Amount of L2 gas to purchase by burning gas on L1.
* @param _isCreation Whether or not the transaction is a contract creation.
* @param _data Data to trigger the recipient with.
*/
function depositTransaction(
address _to,
uint256 _value,
uint64 _gasLimit,
bool _isCreation,
bytes memory _data
) external payable;
}
IUSDC.sol 202 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IUSDC is IERC20 {
/**
* @notice Mints USDC tokens
* @param _to Address to mint tokens to
* @param _amount Amount of tokens to mint
*/
function mint(address _to, uint256 _amount) external;
/**
* @notice allows a minter to burn some of its own tokens
* Validates that caller is a minter and that sender is not blacklisted
* amount is less than or equal to the minter's account balance
* @param _amount uint256 the amount of tokens to be burned
*/
function burn(uint256 _amount) external;
/**
* @notice Transfers USDC ownership to another address
* @param _newOwner Address to transfer ownership to
*/
function transferOwnership(address _newOwner) external;
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external;
/**
* @notice Initializes the fiat token contract.
* @param _tokenName The name of the fiat token.
* @param _tokenSymbol The symbol of the fiat token.
* @param _tokenCurrency The fiat currency that the token represents.
* @param _tokenDecimals The number of decimals that the token uses.
* @param _newMasterMinter The masterMinter address for the fiat token.
* @param _newPauser The pauser address for the fiat token.
* @param _newBlacklister The blacklister address for the fiat token.
* @param _newOwner The owner of the fiat token.
*/
function initialize(
string memory _tokenName,
string memory _tokenSymbol,
string memory _tokenCurrency,
uint8 _tokenDecimals,
address _newMasterMinter,
address _newPauser,
address _newBlacklister,
address _newOwner
) external;
/**
* @notice Initialize v2
* @param _newName New token name
*/
// solhint-disable-next-line func-name-mixedcase
function initializeV2(string calldata _newName) external;
/**
* @notice Initialize v2.1
* @param _lostAndFound The address to which the locked funds are sent
*/
// solhint-disable-next-line func-name-mixedcase
function initializeV2_1(address _lostAndFound) external;
/**
* @notice Initialize v2.2
* @param _accountsToBlacklist A list of accounts to migrate from the old blacklist
* @param _newSymbol New token symbol
* data structure to the new blacklist data structure.
*/
// solhint-disable-next-line func-name-mixedcase
function initializeV2_2(address[] calldata _accountsToBlacklist, string calldata _newSymbol) external;
/**
* @dev Function to add/update a new minter
* @param _minter The address of the minter
* @param _minterAllowedAmount The minting amount allowed for the minter
* @return _result True if the operation was successful.
*/
function configureMinter(address _minter, uint256 _minterAllowedAmount) external returns (bool _result);
/**
* @notice Removes a minter.
* @param _minter The address of the minter to remove.
* @return _result True if the operation was successful.
*/
function removeMinter(address _minter) external returns (bool _result);
/**
* @notice Updates the master minter address.
* @param _newMasterMinter The address of the new master minter.
*/
function updateMasterMinter(address _newMasterMinter) external;
/**
* @notice Adds account to blacklist
* @param _account The address to blacklist
*/
function blacklist(address _account) external;
/**
* @notice Removes account from blacklist.
* @param _account The address to remove from the blacklist.
*/
function unBlacklist(address _account) external;
/**
* @notice Function to upgrade the usdc proxy to a new implementation
* @param _newImplementation Address of the new implementation
*/
function upgradeTo(address _newImplementation) external;
/**
* @notice Upgrades the USDC proxy to a new implementation and calls a function on the new implementation
* @param _newImplementation Address of the new implementation
* @param _data Data to call on the new implementation
*/
function upgradeToAndCall(address _newImplementation, bytes calldata _data) external;
/**
* @notice Returns the current implementation address
* @return _implementation Address of the current implementation
*/
function implementation() external view returns (address _implementation);
/**
* @notice Returns the current master minter address
* @return _masterMinter Address of the current master minter
*/
function masterMinter() external view returns (address _masterMinter);
/**
* @notice Returns the current owner address
* @return _owner Address of the current owner
*/
function owner() external view returns (address _owner);
/**
* @return _currency The currency of the token
*/
function currency() external view returns (string memory _currency);
/**
* @return _decimals The decimals of the token
*/
function decimals() external view returns (uint8 _decimals);
/**
* @return _name The name of the token
*/
function name() external view returns (string memory _name);
/**
* @return _symbol The symbol of the token
*/
function symbol() external view returns (string memory _symbol);
/**
* @notice Checks if an account is a minter.
* @param _account The address to check.
* @return _isMinter True if the account is a minter, false if the account is not a minter.
*/
function isMinter(address _account) external view returns (bool _isMinter);
/**
* @notice Returns the allowance of a minter
* @param _minter The address of the minter
* @return _allowance The minting amount allowed for the minter
*/
function minterAllowance(address _minter) external view returns (uint256 _allowance);
/**
* @notice Returns the address of the current pauser
* @return _pauser Address of the current pauser
*/
function pauser() external view returns (address _pauser);
/**
* @notice Returns the address of the current blacklister
* @return _blacklister Address of the current blacklister
*/
function blacklister() external view returns (address _blacklister);
/**
* @notice Checks if account is blacklisted
* @param _account The address to check
* @return _result True if the account is blacklisted, false if not
*/
function isBlacklisted(address _account) external view returns (bool _result);
/**
* @notice Returns the address of the current admin
* @return _admin Address of the current admin
*/
function admin() external view returns (address _admin);
}
CrossChainDeployments.sol 125 lines
pragma solidity 0.8.25;
import {L2OpUSDCDeploy} from 'contracts/L2OpUSDCDeploy.sol';
import {ICreate2Deployer} from 'interfaces/external/ICreate2Deployer.sol';
import {ICrossDomainMessenger} from 'interfaces/external/ICrossDomainMessenger.sol';
import {IOptimismPortal} from 'interfaces/external/IOptimismPortal.sol';
/**
* @title CrossChainDeployments
* @notice Library containing logic needed on the L1 Factory to properly deploy contracts on the L2.
* @dev Logic splitted here to reduce code size on the L1 Factory contract.
*/
library CrossChainDeployments {
/// @notice RLP encoding deployer length prefix for calculating the address of a contract deployed through `CREATE`
bytes1 internal constant _LEN = bytes1(0x94);
/// @notice The status of if the transaction is a contract creation
bool internal constant _IS_CONTRACT_CREATION = false;
/// @notice The msg.value sent with the transaction
uint256 internal constant _VALUE = 0;
/**
* @notice Deploys the L2 factory contract through the L1 messenger
* @param _args The initialization arguments for the L2 factory
* @param _salt The salt to be used to deploy the L2 factory
* @param _messenger The address of the L1 messenger
* @param _create2Deployer The address of the L2 create2 deployer
* @param _minGasLimit The minimum gas limit that the message can be executed with
* @return _l2Deploy The address of the L2 factory
*/
function deployL2Factory(
bytes memory _args,
bytes32 _salt,
address _messenger,
address _create2Deployer,
uint32 _minGasLimit
) external returns (address _l2Deploy) {
bytes memory _l2DeployInitCode = bytes.concat(type(L2OpUSDCDeploy).creationCode, _args);
_l2Deploy = precalculateCreate2Address(_salt, keccak256(_l2DeployInitCode), _create2Deployer);
bytes memory _l2DeploymentsTx = abi.encodeCall(ICreate2Deployer.deploy, (_VALUE, _salt, _l2DeployInitCode));
address _portal;
// Some messengers are still using the legacy `portal` function so we need to handle this case
try ICrossDomainMessenger(_messenger).portal() returns (address _p) {
_portal = _p;
} catch {
_portal = ICrossDomainMessenger(_messenger).PORTAL();
}
IOptimismPortal(_portal).depositTransaction(
_create2Deployer, _VALUE, _minGasLimit, _IS_CONTRACT_CREATION, _l2DeploymentsTx
);
}
/**
* @notice Precalculate and address to be deployed using the `CREATE2` opcode
* @param _salt The 32-byte random value used to create the contract address.
* @param _initCodeHash The 32-byte bytecode digest of the contract creation bytecode.
* @param _deployer The 20-byte _deployer address.
* @return _precalculatedAddress The 20-byte address where a contract will be stored.
*/
function precalculateCreate2Address(
bytes32 _salt,
bytes32 _initCodeHash,
address _deployer
) internal pure returns (address _precalculatedAddress) {
assembly ("memory-safe") {
let _ptr := mload(0x40)
mstore(add(_ptr, 0x40), _initCodeHash)
mstore(add(_ptr, 0x20), _salt)
mstore(_ptr, _deployer)
let _start := add(_ptr, 0x0b)
mstore8(_start, 0xff)
_precalculatedAddress := and(keccak256(_start, 85), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
}
/**
* @notice Precalculates the address of a contract that will be deployed thorugh `CREATE` opcode
* @param _deployer The deployer address
* @param _nonce The next nonce of the deployer address
* @return _precalculatedAddress The address where the contract will be stored
* @dev Only works for nonces between 1 and (2 ** 64 - 2), which is enough for this use case
*/
function precalculateCreateAddress(
address _deployer,
uint256 _nonce
) internal pure returns (address _precalculatedAddress) {
bytes memory _data;
// A one-byte integer in the [0x00, 0x7f] range uses its own value as a length prefix, there is no
// additional "0x80 + length" prefix that precedes it.
if (_nonce <= 0x7f) {
_data = abi.encodePacked(bytes1(0xd6), _LEN, _deployer, uint8(_nonce));
}
// In the case of `_nonce > 0x7f` and `_nonce <= type(uint8).max`, we have the following encoding scheme
// (the same calculation can be carried over for higher _nonce bytes):
// 0xda = 0xc0 (short RLP prefix) + 0x1a (= the bytes length of: 0x94 + address + 0x84 + _nonce, in hex),
// 0x94 = 0x80 + 0x14 (= the bytes length of an address, 20 bytes, in hex),
// 0x84 = 0x80 + 0x04 (= the bytes length of the _nonce, 4 bytes, in hex).
else if (_nonce <= type(uint8).max) {
_data = abi.encodePacked(bytes1(0xd7), _LEN, _deployer, bytes1(0x81), uint8(_nonce));
} else if (_nonce <= type(uint16).max) {
_data = abi.encodePacked(bytes1(0xd8), _LEN, _deployer, bytes1(0x82), uint16(_nonce));
} else if (_nonce <= type(uint24).max) {
_data = abi.encodePacked(bytes1(0xd9), _LEN, _deployer, bytes1(0x83), uint24(_nonce));
} else if (_nonce <= type(uint32).max) {
_data = abi.encodePacked(bytes1(0xda), _LEN, _deployer, bytes1(0x84), uint32(_nonce));
} else if (_nonce <= type(uint40).max) {
_data = abi.encodePacked(bytes1(0xdb), _LEN, _deployer, bytes1(0x85), uint40(_nonce));
} else if (_nonce <= type(uint48).max) {
_data = abi.encodePacked(bytes1(0xdc), _LEN, _deployer, bytes1(0x86), uint48(_nonce));
} else if (_nonce <= type(uint56).max) {
_data = abi.encodePacked(bytes1(0xdd), _LEN, _deployer, bytes1(0x87), uint56(_nonce));
} else {
_data = abi.encodePacked(bytes1(0xde), _LEN, _deployer, bytes1(0x88), uint64(_nonce));
}
_precalculatedAddress = address(uint160(uint256(keccak256(_data))));
}
}
Read Contract
L2_CREATE2_DEPLOYER 0x8b0f9bf8 → address
USDC 0x89a30271 → address
USDC_NAME 0xec30286b → string
USDC_SYMBOL 0xc25c3e18 → string
deploymentsSaltCounter 0xeae1a64e → uint256
Write Contract 1 functions
These functions modify contract state and require a wallet transaction to execute.
deploy 0xec1cd11d
address _l1Messenger
address _l1AdapterOwner
string _chainName
tuple _l2Deployments
returns: address, address, address
Recent Transactions
No transactions found for this address