Address Contract Verified
Address
0x4Fb4c4aDE2a7fFE765d8193610779FF01DD923a0
Balance
0 ETH
Nonce
1
Code Size
10758 bytes
Creator
0xC4a59122...451b at tx 0x6d8952ae...1a07e5
Indexed Transactions
0
Contract Bytecode
10758 bytes
0x608060405234801561001057600080fd5b50600436106101425760003560e01c8063778c5c64116100b8578063a20baee61161007c578063a20baee6146102d4578063c3c854b6146102e3578063c45a0155146102f6578063e19c80c21461031d578063e75dd59214610330578063f8d898981461035957600080fd5b8063778c5c641461028a5780637ec940a81461029d5780638cd2e0c7146102b05780638da5cb5b146102c3578063969c2452146102cb57600080fd5b80634ba4a28b1161010a5780634ba4a28b146102045780634ff814431461022b5780636229dcc51461023e578063658e79041461025157806374ef871a146102645780637617cd081461027757600080fd5b806308b6ab95146101475780631930e8251461018b5780633d4411a0146101c657806341e5e1f5146101e7578063452a9320146101fc575b600080fd5b61016e7f000000000000000000000000d5eeaf2eeb9e1c7b88acfad3f41401925fc20c8b81565b6040516001600160a01b0390911681526020015b60405180910390f35b6101b66101993660046125d6565b600060208181529281526040808220909352908152205460ff1681565b6040519015158152602001610182565b6101d96101d436600461260f565b610380565b604051908152602001610182565b6101fa6101f536600461262c565b6103ec565b005b61016e610401565b6101d97f00000000000000000000000000000000000000000000000ad78ebc5ac620000081565b6101d9610239366004612661565b61048a565b6101fa61024c36600461267a565b610495565b6101fa61025f36600461262c565b610ab3565b6101fa6102723660046126ca565b610ac3565b6101fa61028536600461262c565b610ad9565b6101fa6102983660046125d6565b610ae9565b6101d96102ab366004612728565b610c39565b6101fa6102be36600461262c565b6111e3565b61016e6111f3565b6101d960015481565b6101d9670de0b6b3a764000081565b6101fa6102f136600461276e565b611253565b61016e7f000000000000000000000000ca61a7be20d361b21c0ad7fa61e241c56202e66c81565b6101fa61032b36600461260f565b6112bd565b61016e61033e36600461260f565b6002602052600090815260409020546001600160a01b031681565b61016e7f000000000000000000000000e868084cf08f3c3db11f4b73a95473762d9463f781565b6000816001600160a01b031663b620115d6040518163ffffffff1660e01b81526004016020604051808303816000875af11580156103c2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103e6919061279c565b92915050565b6103fc838360008085600161145a565b505050565b60007f000000000000000000000000d5eeaf2eeb9e1c7b88acfad3f41401925fc20c8b6001600160a01b031663452a93206040518163ffffffff1660e01b8152600401602060405180830381865afa158015610461573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061048591906127b5565b905090565b60006103e682611ce0565b82826000826001600160a01b0316636352211e836040518263ffffffff1660e01b81526004016104c791815260200190565b602060405180830381865afa1580156104e4573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061050891906127b5565b9050336001600160a01b0382161480610592575060405163020604bf60e21b81526004810183905233906001600160a01b0385169063081812fc90602401602060405180830381865afa158015610563573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061058791906127b5565b6001600160a01b0316145b80610607575060405163e985e9c560e01b81526001600160a01b0384169063e985e9c5906105c690849033906004016127d2565b602060405180830381865afa1580156105e3573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061060791906127ec565b61062c5760405162461bcd60e51b815260040161062390612809565b60405180910390fd5b61069660405180610120016040528060006001600160a01b0316815260200160006001600160a01b0316815260200160006001600160a01b031681526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b86876001600160a01b0316635733d58f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106d5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106f9919061279c565b6040516331a9108f60e11b8152600481018990526001600160a01b038a1690636352211e90602401602060405180830381865afa15801561073e573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061076291906127b5565b6001600160a01b0390811660408581019190915261010085019290925291909116808352905163ae94a40360e01b815260048101889052600091829182919063ae94a403906024016060604051808303816000875af11580156107c9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107ed9190612840565b9250925092506107fc8a611d0c565b60e089015260a0880152608087015260608601526001600160a01b031660208501526108288183612884565b8460c0018181525050896001600160a01b031663c82825696040518163ffffffff1660e01b8152600401602060405180830381865afa15801561086f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061089391906127ec565b6108f45760006108e18560e0015186606001516108b09190612897565b8660a0015187608001516108c49190612884565b60e08801516108d39088612897565b60008960c001516000611dfb565b90506108f281866101000151611e55565b505b6040516301ee819f60e01b8152600481018a90526001600160a01b0389811660248301526044820185905260648201849052608482018390528b16906301ee819f9060a401600060405180830381600087803b15801561095357600080fd5b505af1158015610967573d6000803e3d6000fd5b505050507f000000000000000000000000e868084cf08f3c3db11f4b73a95473762d9463f76001600160a01b03166385177509337f00000000000000000000000000000000000000000000000ad78ebc5ac62000008760c001516109cb91906128ae565b6040516001600160e01b031960e085901b1681526001600160a01b03909216600483015260248201526044016020604051808303816000875af1158015610a16573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a3a91906127ec565b5060408085015181516001600160a01b039182168152818d1660208201529182018b9052891660608201526080810184905260a0810183905260c081018290527f3114c48eed8454c0da6786e8da28d91bd6f6396f5005f9dffc80e439985de8a29060e00160405180910390a150505050505050505050565b6103fc838360008460008061145a565b610ad186868686868661145a565b505050505050565b6103fc838383600080600061145a565b336001600160a01b037f000000000000000000000000ca61a7be20d361b21c0ad7fa61e241c56202e66c1614610b595760405162461bcd60e51b8152602060048201526015602482015274426f72726f7765724f70733a2021466163746f727960581b6044820152606401610623565b6001600160a01b038281166000908152600260205260409020541615610bcc5760405162461bcd60e51b815260206004820152602260248201527f426f72726f7765724f70733a20436f6c6c61746572616c20636f6e6669677572604482015261195960f21b6064820152608401610623565b6001600160a01b038281166000908152600260205260409081902080546001600160a01b03191692841692909217909155517ff6e0528dc0c0ef50525339faff44940d57e7897bee18b67dd0aa23bba1749ad290610c2d90849084906127d2565b60405180910390a15050565b600083336001600160a01b0382161480610c7457506001600160a01b03811660009081526020818152604080832033845290915290205460ff165b610cb85760405162461bcd60e51b815260206004820152601560248201527411195b1959d85d19481b9bdd08185c1c1c9bdd9959605a1b6044820152606401610623565b7f000000000000000000000000d5eeaf2eeb9e1c7b88acfad3f41401925fc20c8b6001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610d16573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d3a91906127ec565b15610d875760405162461bcd60e51b815260206004820181905260248201527f426f72726f7765724f70733a204465706f7369747320617265207061757365646044820152606401610623565b610de660405180610140016040528060006001600160a01b031681526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b60a08101849052610df684611ce0565b60c08201819052610e0690611ecf565b866001600160a01b031663bf5cb4b06040518163ffffffff1660e01b815260040160408051808303816000875af1158015610e45573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e6991906128c1565b5050610e7487611d0c565b602080870191909152608086019190915260608501919091526040808501929092526001600160a01b0392831684528151631e5395c960e21b81529151928a169263794e57249260048082019392918290030181865afa158015610edc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f00919061279c565b876001600160a01b0316635733d58f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f3e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f62919061279c565b61010083015260e082015260c08101516020820151610f82918791611f4a565b610120820181905260e0820151610f999190611f7e565b6000610fc1826040015183608001518460600151610fb79190612884565b8460200151611f4a565b9050816101000151811061103057600061101983602001518460400151610fe89190612897565b84608001518560600151610ffc9190612884565b602086015161100b908b612897565b60018760c001516001611dfb565b905061102a81846101000151611e55565b50611044565b611044826101200151836101000151611ff4565b60c08201516040516301f592d760e61b81526001600160a01b03898116600483015260248201899052604482019290925290891690637d64b5c0906064016020604051808303816000875af11580156110a1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110c5919061279c565b82519094506110df906001600160a01b0316338a8961206a565b60a082015160405163467fafdf60e11b81526001600160a01b03898116600483015260248201929092527f000000000000000000000000e868084cf08f3c3db11f4b73a95473762d9463f790911690638cff5fbe906044016020604051808303816000875af1158015611156573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061117a91906127ec565b5060c0820151604080516001600160a01b038a811682528b166020820152808201879052606081018990526080810192909252517f198ed09e9418f894a72029bb718e054f99dcbd451320232f527a4a1bf3db13f69181900360a00190a1505050949350505050565b6103fc838360008085600061145a565b60007f000000000000000000000000d5eeaf2eeb9e1c7b88acfad3f41401925fc20c8b6001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610461573d6000803e3d6000fd5b336000818152602081815260408083206001600160a01b03871680855290835292819020805460ff191686151590811790915590519081529192917f92d241afb0a1a9b3441bf1bd6bea0f9164cf5a2562cbe4bcc34ab943b2465608910160405180910390a35050565b6001600160a01b0381811660009081526002602052604090205416158015906113465750806001600160a01b0316635758e7056040518163ffffffff1660e01b8152600401602060405180830381865afa15801561131f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611343919061279c565b15155b80156113b15750806001600160a01b031663795d26c36040518163ffffffff1660e01b8152600401602060405180830381865afa15801561138b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113af919061279c565b155b6113fd5760405162461bcd60e51b815260206004820152601f60248201527f54726f7665204d616e616765722063616e6e6f742062652072656d6f766564006044820152606401610623565b6001600160a01b03811660008181526002602090815260409182902080546001600160a01b031916905590519182527fe44bbef3bc872937d7daf489db0badffc044d1813a027aea391838c546514303910160405180910390a150565b83158015611466575080155b806114f057507f000000000000000000000000d5eeaf2eeb9e1c7b88acfad3f41401925fc20c8b6001600160a01b0316635c975abb6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156114ca573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114ee91906127ec565b155b61154e5760405162461bcd60e51b815260206004820152602960248201527f426f72726f7765724f70733a2054726f76652061646a7573746d656e747320616044820152681c99481c185d5cd95960ba1b6064820152608401610623565b831580611559575082155b6115b75760405162461bcd60e51b815260206004820152602960248201527f426f72726f7765724f70733a2043616e6e6f7420776974686472617720616e64604482015268081859190818dbdb1b60ba1b6064820152608401610623565b831515806115c457508215155b806115ce57508115155b61164f5760405162461bcd60e51b815260206004820152604660248201527f426f72726f7765724f70733a205468657265206d75737420626520656974686560448201527f72206120636f6c6c61746572616c206368616e6765206f7220612064656274206064820152656368616e676560d01b608482015260a401610623565b6116fa60405180610260016040528060006001600160a01b031681526020016000815260200160008152602001600081526020016000815260200160008152602001600015158152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160006001600160a01b0316815260200160008152602001600081526020016000151581525090565b6040516331a9108f60e11b8152600481018790526001600160a01b03881690636352211e90602401602060405180830381865afa15801561173f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061176391906127b5565b6001600160a01b03166101e08201528415158061177f57508315155b806117875750815b156118b857806101e001516001600160a01b0316336001600160a01b03161480611822575060405163020604bf60e21b81526004810187905233906001600160a01b0389169063081812fc90602401602060405180830381865afa1580156117f3573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061181791906127b5565b6001600160a01b0316145b8061189c57506101e081015160405163e985e9c560e01b81526001600160a01b0389169163e985e9c59161185b919033906004016127d2565b602060405180830381865afa158015611878573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061189c91906127ec565b6118b85760405162461bcd60e51b815260040161062390612809565b811561192e576000831161192e5760405162461bcd60e51b815260206004820152603760248201527f426f72726f7765724f70733a204465627420696e637265617365207265717569604482015276726573206e6f6e2d7a65726f20646562744368616e676560481b6064820152608401610623565b60405163ae94a40360e01b8152600481018790526001600160a01b0388169063ae94a403906024016060604051808303816000875af1158015611975573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119999190612840565b61012084015260e08301526101008201526119b387611d0c565b602080870191909152608086019190915260608501919091526040808501929092526001600160a01b0392831684528151631e5395c960e21b8152915186938b169263794e57249260048083019391928290030181865afa158015611a1c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a40919061279c565b886001600160a01b0316635733d58f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a7e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611aa2919061279c565b6102208401526102008301526101a0820152604081015160808201516060830151600092611ad6929091610fb79190612884565b61022083015181106102408401529050611af086866120ca565b151560c084015260a083015282158015611b0a5750600084115b15611b71576001548260e00151611b2191906128ae565b841115611b68576001548260e00151611b3a91906128ae565b6101a08301819052611b4c90856128ae565b9350611b5d848361012001516120e9565b6101c0830152611b71565b6101a082018490525b611b7b83836120ff565b8160c0015115611ba55760a08201518251611ba5916001600160a01b039091169033908b9061206a565b6101a082015160c083015160a08401516101c0850151604051634c29aa9360e11b8152600481018c9052871515602482015260448101949094529115156064840152608483015260a48201523360c48201526001600160a01b0389169063985355269060e4016080604051808303816000875af1158015611c2a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c4e91906128e5565b505050507fdf639d9850e54de08290fbdfd42bfb97b8511673462c414785283e8e5bde37ff826101e0015189898989876101c00151886101a00151611c939190612884565b604080516001600160a01b039788168152969095166020870152938501929092526060840152608083015260a082015284151560c082015260e00160405180910390a15050505050505050565b60006103e67f00000000000000000000000000000000000000000000000ad78ebc5ac620000083612884565b6001600160a01b038082166000908152600260205260408120549091169080808084611d865760405162461bcd60e51b815260206004820152602360248201527f426f72726f7765724f70733a206e6f6e6578697374656e7420636f6c6c6174656044820152621c985b60ea1b6064820152608401610623565b856001600160a01b03166301c799fc6040518163ffffffff1660e01b81526004016080604051808303816000875af1158015611dc6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dea91906128e5565b979992985090969095509350915050565b600081611e1157611e0c83876128ae565b611e1b565b611e1b8387612884565b955083611e3157611e2c85886128ae565b611e3b565b611e3b8588612884565b96506000611e4988886122af565b98975050505050505050565b80821015611ecb5760405162461bcd60e51b815260206004820152604960248201526000805160206129b183398151915260448201527f6f756c6420726573756c7420696e20544352203c20434352206973206e6f74206064820152681c195c9b5a5d1d195960ba1b608482015260a401610623565b5050565b600154811015611f475760405162461bcd60e51b815260206004820152603a60248201527f426f72726f7765724f70733a2054726f76652773206e65742064656274206d7560448201527f73742062652067726561746572207468616e206d696e696d756d0000000000006064820152608401610623565b50565b60008215611f7257600083611f5f8487612897565b611f69919061291b565b9150611f779050565b506000195b9392505050565b80821015611ecb5760405162461bcd60e51b815260206004820152604960248201526000805160206129b183398151915260448201527f6f756c6420726573756c7420696e20494352203c204d4352206973206e6f74206064820152681c195c9b5a5d1d195960ba1b608482015260a401610623565b80821015611ecb5760405162461bcd60e51b815260206004820152604960248201526000805160206129b183398151915260448201527f6f756c6420726573756c7420696e20494352203c20434352206973206e6f74206064820152681c195c9b5a5d1d195960ba1b608482015260a401610623565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b1790526120c49085906122d5565b50505050565b60008083156120de575082905060016120e2565b8291505b9250929050565b60008183106120f85781611f77565b5090919050565b600061214a8261010001518361012001518460e0015161211f9190612884565b8460a001518560c00151866101c00151876101a0015161213f9190612884565b8888602001516123aa565b905061215b81836102000151611f7e565b60006121bd836020015184604001516121749190612897565b846080015185606001516121889190612884565b85602001518660a0015161219c9190612897565b8660c00151876101c00151886101a001516121b79190612884565b89611dfb565b9050826102400151156122a05783156121e4576121df81846102200151611e55565b6120c4565b8260c001516121df5782602001518360a001516122019190612897565b670de0b6b3a7640000846101c00151856101a001516122209190612884565b61222a9190612897565b10156121df576040805162461bcd60e51b81526020600482015260248101919091527f426f72726f7765724f70733a2043616e6e6f7420776974686472617720636f6c60448201527f6c61746572616c20776974686f757420706179696e67206261636b20646562746064820152608401610623565b6120c481846102200151611e55565b600081156122cc5760006122c3838561291b565b91506103e69050565b506000196103e6565b600061232a826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166123dd9092919063ffffffff16565b905080516000148061234b57508080602001905181019061234b91906127ec565b6103fc5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610623565b60008060006123bd8a8a8a8a8a8a6123f4565b9150915060006123ce838387611f4a565b9b9a5050505050505050505050565b60606123ec8484600085612448565b949350505050565b60008087878661240d57612408888b6128ae565b612417565b612417888b612884565b91508461242d57612428868a6128ae565b612437565b612437868a612884565b919a91995090975050505050505050565b6060824710156124a95760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610623565b600080866001600160a01b031685876040516124c59190612961565b60006040518083038185875af1925050503d8060008114612502576040519150601f19603f3d011682016040523d82523d6000602084013e612507565b606091505b509150915061251887838387612523565b979650505050505050565b6060831561259257825160000361258b576001600160a01b0385163b61258b5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610623565b50816123ec565b6123ec83838151156125a75781518083602001fd5b8060405162461bcd60e51b8152600401610623919061297d565b6001600160a01b0381168114611f4757600080fd5b600080604083850312156125e957600080fd5b82356125f4816125c1565b91506020830135612604816125c1565b809150509250929050565b60006020828403121561262157600080fd5b8135611f77816125c1565b60008060006060848603121561264157600080fd5b833561264c816125c1565b95602085013595506040909401359392505050565b60006020828403121561267357600080fd5b5035919050565b60008060006060848603121561268f57600080fd5b833561269a816125c1565b92506020840135915060408401356126b1816125c1565b809150509250925092565b8015158114611f4757600080fd5b60008060008060008060c087890312156126e357600080fd5b86356126ee816125c1565b95506020870135945060408701359350606087013592506080870135915060a087013561271a816126bc565b809150509295509295509295565b6000806000806080858703121561273e57600080fd5b8435612749816125c1565b93506020850135612759816125c1565b93969395505050506040820135916060013590565b6000806040838503121561278157600080fd5b823561278c816125c1565b91506020830135612604816126bc565b6000602082840312156127ae57600080fd5b5051919050565b6000602082840312156127c757600080fd5b8151611f77816125c1565b6001600160a01b0392831681529116602082015260400190565b6000602082840312156127fe57600080fd5b8151611f77816126bc565b6020808252601b908201527f426f72726f7765724f70733a204e6f7420617574686f72697a65640000000000604082015260600190565b60008060006060848603121561285557600080fd5b5050815160208301516040909301519094929350919050565b634e487b7160e01b600052601160045260246000fd5b808201808211156103e6576103e661286e565b80820281158282048414176103e6576103e661286e565b818103818111156103e6576103e661286e565b600080604083850312156128d457600080fd5b505080516020909101519092909150565b600080600080608085870312156128fb57600080fd5b505082516020840151604085015160609095015191969095509092509050565b60008261293857634e487b7160e01b600052601260045260246000fd5b500490565b60005b83811015612958578181015183820152602001612940565b50506000910152565b6000825161297381846020870161293d565b9190910192915050565b602081526000825180602084015261299c81604085016020870161293d565b601f01601f1916919091016040019291505056fe426f72726f7765724f70733a20416e206f7065726174696f6e20746861742077a26469706673582212209200cdc88b5f3b46470d58d182cf19cf19b40d99121fa01e4749a239950f2b5b64736f6c634300081c0033
Verified Source Code Full Match
Compiler: v0.8.28+commit.7893614a
EVM: paris
Optimization: Yes (100 runs)
IERC20Permit.sol 90 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @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);
}
IERC20.sol 78 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
}
SafeERC20.sol 143 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../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 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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @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.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @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, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @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.isContract(address(token));
}
}
ERC721.sol 466 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: address zero is not a valid owner");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _ownerOf(tokenId);
require(owner != address(0), "ERC721: invalid token ID");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
_requireMinted(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not token owner or approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
_requireMinted(tokenId);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
_safeTransfer(from, to, tokenId, data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*/
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
return _owners[tokenId];
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _ownerOf(tokenId) != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId, 1);
// Check that tokenId was not minted by `_beforeTokenTransfer` hook
require(!_exists(tokenId), "ERC721: token already minted");
unchecked {
// Will not overflow unless all 2**256 token ids are minted to the same owner.
// Given that tokens are minted one by one, it is impossible in practice that
// this ever happens. Might change if we allow batch minting.
// The ERC fails to describe this case.
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId, 1);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId, 1);
// Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
owner = ERC721.ownerOf(tokenId);
// Clear approvals
delete _tokenApprovals[tokenId];
unchecked {
// Cannot overflow, as that would require more tokens to be burned/transferred
// out than the owner initially received through minting and transferring in.
_balances[owner] -= 1;
}
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId, 1);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId, 1);
// Check that tokenId was not transferred by `_beforeTokenTransfer` hook
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
// Clear approvals from the previous owner
delete _tokenApprovals[tokenId];
unchecked {
// `_balances[from]` cannot overflow for the same reason as described in `_burn`:
// `from`'s balance is the number of token held, which is at least one before the current
// transfer.
// `_balances[to]` could overflow in the conditions described in `_mint`. That would require
// all 2**256 token ids to be minted, which in practice is impossible.
_balances[from] -= 1;
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` has not been minted yet.
*/
function _requireMinted(uint256 tokenId) internal view virtual {
require(_exists(tokenId), "ERC721: invalid token ID");
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
/// @solidity memory-safe-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
* - When `from` is zero, the tokens will be minted for `to`.
* - When `to` is zero, ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}
/**
* @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
* - When `from` is zero, the tokens were minted for `to`.
* - When `to` is zero, ``from``'s tokens were burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}
/**
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
*
* WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
* being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
* that `ownerOf(tokenId)` is `a`.
*/
// solhint-disable-next-line func-name-mixedcase
function __unsafe_increaseBalance(address account, uint256 amount) internal {
_balances[account] += amount;
}
}
ERC721Enumerable.sol 159 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
) internal virtual override {
super._beforeTokenTransfer(from, to, firstTokenId, batchSize);
if (batchSize > 1) {
// Will only trigger during construction. Batch transferring (minting) is not available afterwards.
revert("ERC721Enumerable: consecutive transfers not supported");
}
uint256 tokenId = firstTokenId;
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
IERC721Enumerable.sol 29 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
IERC721Metadata.sol 27 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
IERC721.sol 132 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
IERC721Receiver.sol 27 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
Address.sol 244 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @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, it is bubbled up by this
* function (like regular Solidity function calls).
*
* 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.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @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`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) 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(errorMessage);
}
}
}
Context.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @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;
}
}
ERC165.sol 29 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Math.sol 339 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @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 up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (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; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
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.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 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.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
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 (rounding == Rounding.Up && 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 down.
*
* 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
SignedMath.sol 43 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @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);
}
}
}
Strings.sol 85 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @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), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(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) {
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] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
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 keccak256(bytes(a)) == keccak256(bytes(b));
}
}
BorrowerOperations.sol 239 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "../interfaces/IDebtToken.sol";
import "../interfaces/IBorrowerOperations.sol";
import "../dependencies/YalaBase.sol";
import "../dependencies/YalaMath.sol";
import "../dependencies/YalaOwnable.sol";
import "../dependencies/DelegatedOps.sol";
/**
@title Yala Borrower Operations
@notice Based on Liquity's `BorrowerOperations`
https://github.com/liquity/dev/blob/main/packages/contracts/contracts/BorrowerOperations.sol
*/
contract BorrowerOperations is IBorrowerOperations, YalaBase, YalaOwnable, DelegatedOps {
using SafeERC20 for IERC20;
IDebtToken public immutable debtToken;
address public immutable factory;
uint256 public minNetDebt;
mapping(ITroveManager => IERC20) public collateraTokens;
modifier auth(ITroveManager troveManager, uint256 id) {
address owner = troveManager.ownerOf(id);
require(msg.sender == owner || troveManager.getApproved(id) == msg.sender || troveManager.isApprovedForAll(owner, msg.sender), "BorrowerOps: Not authorized");
_;
}
constructor(address _yalaCore, address _debtTokenAddress, address _factory, uint256 _minNetDebt, uint256 _gasCompensation) YalaOwnable(_yalaCore) YalaBase(_gasCompensation) {
debtToken = IDebtToken(_debtTokenAddress);
factory = _factory;
_setMinNetDebt(_minNetDebt);
}
function _setMinNetDebt(uint256 _minNetDebt) internal {
require(_minNetDebt > 0, "BorrowerOps: Invalid min net debt");
minNetDebt = _minNetDebt;
emit MinNetDebtUpdated(_minNetDebt);
}
function configureCollateral(ITroveManager troveManager, IERC20 collateralToken) external {
require(msg.sender == factory, "BorrowerOps: !Factory");
require(address(collateraTokens[troveManager]) == address(0), "BorrowerOps: Collateral configured");
collateraTokens[troveManager] = collateralToken;
emit CollateralConfigured(troveManager, collateralToken);
}
function removeTroveManager(ITroveManager troveManager) external {
require(address(collateraTokens[troveManager]) != address(0) && troveManager.shutdownAt() != 0 && troveManager.getEntireSystemDebt() == 0, "Trove Manager cannot be removed");
delete collateraTokens[troveManager];
emit TroveManagerRemoved(troveManager);
}
function getCompositeDebt(uint256 _debt) public view returns (uint256) {
return _getCompositeDebt(_debt);
}
function openTrove(ITroveManager troveManager, address account, uint256 _collateralAmount, uint256 _debtAmount) external callerOrDelegated(account) returns (uint256 id) {
require(!YALA_CORE.paused(), "BorrowerOps: Deposits are paused");
LocalVariables_openTrove memory vars;
vars.netDebt = _debtAmount;
vars.compositeDebt = _getCompositeDebt(vars.netDebt);
_requireAtLeastMinNetDebt(vars.compositeDebt);
troveManager.accrueInterests();
(vars.collateralToken, vars.totalCollateral, vars.totalDebt, vars.totalInterest, vars.price) = _getCollateralAndTCRData(troveManager);
(vars.MCR, vars.CCR) = (troveManager.MCR(), troveManager.CCR());
vars.ICR = YalaMath._computeCR(_collateralAmount, vars.compositeDebt, vars.price);
_requireICRisAboveMCR(vars.ICR, vars.MCR);
uint256 TCR = YalaMath._computeCR(vars.totalCollateral, vars.totalDebt + vars.totalInterest, vars.price);
if (TCR >= vars.CCR) {
uint256 newTCR = _getNewTCRFromTroveChange(vars.totalCollateral * vars.price, vars.totalDebt + vars.totalInterest, _collateralAmount * vars.price, true, vars.compositeDebt, true);
_requireNewTCRisAboveCCR(newTCR, vars.CCR);
} else {
_requireICRisAboveCCR(vars.ICR, vars.CCR);
}
// Create the trove
id = troveManager.openTrove(account, _collateralAmount, vars.compositeDebt);
// Move the collateral to the Trove Manager
vars.collateralToken.safeTransferFrom(msg.sender, address(troveManager), _collateralAmount);
// and mint the DebtAmount to the caller and gas compensation for Gas Pool
debtToken.mintWithGasCompensation(account, vars.netDebt);
emit TroveCreated(account, troveManager, id, _collateralAmount, vars.compositeDebt);
}
// Send collateral to a trove
function addColl(ITroveManager troveManager, uint256 id, uint256 _collateralAmount) external {
_adjustTrove(troveManager, id, _collateralAmount, 0, 0, false);
}
// Withdraw collateral from a trove
function withdrawColl(ITroveManager troveManager, uint256 id, uint256 _collWithdrawal) external {
_adjustTrove(troveManager, id, 0, _collWithdrawal, 0, false);
}
// Withdraw Debt tokens from a trove: mint new Debt tokens to the owner, and increase the trove's debt accordingly
function withdrawDebt(ITroveManager troveManager, uint256 id, uint256 _debtAmount) external {
_adjustTrove(troveManager, id, 0, 0, _debtAmount, true);
}
// Repay Debt tokens to a Trove: Burn the repaid Debt tokens, and reduce the trove's debt accordingly
function repay(ITroveManager troveManager, uint256 id, uint256 _debtAmount) external {
_adjustTrove(troveManager, id, 0, 0, _debtAmount, false);
}
function adjustTrove(ITroveManager troveManager, uint256 id, uint256 _collDeposit, uint256 _collWithdrawal, uint256 _debtChange, bool _isDebtIncrease) external {
_adjustTrove(troveManager, id, _collDeposit, _collWithdrawal, _debtChange, _isDebtIncrease);
}
function _adjustTrove(ITroveManager troveManager, uint256 id, uint256 _collDeposit, uint256 _collWithdrawal, uint256 _debtChange, bool _isDebtIncrease) internal {
require((_collDeposit == 0 && !_isDebtIncrease) || !YALA_CORE.paused(), "BorrowerOps: Trove adjustments are paused");
require(_collDeposit == 0 || _collWithdrawal == 0, "BorrowerOps: Cannot withdraw and add coll");
require(_collDeposit != 0 || _collWithdrawal != 0 || _debtChange != 0, "BorrowerOps: There must be either a collateral change or a debt change");
LocalVariables_adjustTrove memory vars;
vars.account = troveManager.ownerOf(id);
if (_collDeposit != 0 || _collWithdrawal != 0 || _isDebtIncrease) {
require(msg.sender == vars.account || troveManager.getApproved(id) == msg.sender || troveManager.isApprovedForAll(vars.account, msg.sender), "BorrowerOps: Not authorized");
}
if (_isDebtIncrease) {
require(_debtChange > 0, "BorrowerOps: Debt increase requires non-zero debtChange");
}
(vars.coll, vars.debt, vars.interest) = troveManager.applyPendingRewards(id);
(vars.collateralToken, vars.totalCollateral, vars.totalDebt, vars.totalInterest, vars.price) = _getCollateralAndTCRData(troveManager);
(vars.debtChange, vars.MCR, vars.CCR) = (_debtChange, troveManager.MCR(), troveManager.CCR());
uint256 TCR = YalaMath._computeCR(vars.totalCollateral, vars.totalDebt + vars.totalInterest, vars.price);
vars.isBelowCriticalThreshold = TCR < vars.CCR;
// Get the collChange based on whether or not collateral was sent in the transaction
(vars.collChange, vars.isCollIncrease) = _getCollChange(_collDeposit, _collWithdrawal);
if (!_isDebtIncrease && _debtChange > 0) {
if (_debtChange > (vars.debt - minNetDebt)) {
vars.debtChange = vars.debt - minNetDebt;
_debtChange = _debtChange - vars.debtChange;
vars.interestRepayment = YalaMath._min(_debtChange, vars.interest);
} else {
vars.debtChange = _debtChange;
}
}
_requireValidAdjustment(_isDebtIncrease, vars);
// If we are incrasing collateral, send tokens to the trove manager prior to adjusting the trove
if (vars.isCollIncrease) vars.collateralToken.safeTransferFrom(msg.sender, address(troveManager), vars.collChange);
troveManager.updateTroveFromAdjustment(id, _isDebtIncrease, vars.debtChange, vars.isCollIncrease, vars.collChange, vars.interestRepayment, msg.sender);
emit AdjustTrove(vars.account, troveManager, id, _collDeposit, _collWithdrawal, vars.debtChange + vars.interestRepayment, _isDebtIncrease);
}
function closeTrove(ITroveManager troveManager, uint256 id, address receiver) external auth(troveManager, id) {
LocalVariables_closeTrove memory vars;
(vars.troveManager, vars.CCR, vars.account) = (troveManager, troveManager.CCR(), troveManager.ownerOf(id));
(uint256 coll, uint256 debt, uint256 interest) = vars.troveManager.applyPendingRewards(id);
(vars.collateralToken, vars.totalCollateral, vars.totalDebt, vars.totalInterest, vars.price) = _getCollateralAndTCRData(troveManager);
vars.compositeDebt = debt + interest;
if (!troveManager.hasShutdown()) {
uint256 newTCR = _getNewTCRFromTroveChange(vars.totalCollateral * vars.price, vars.totalDebt + vars.totalInterest, coll * vars.price, false, vars.compositeDebt, false);
_requireNewTCRisAboveCCR(newTCR, vars.CCR);
}
troveManager.closeTrove(id, receiver, coll, debt, interest);
// Burn the repaid Debt from the user's balance and the gas compensation from the Gas Pool
debtToken.burnWithGasCompensation(msg.sender, vars.compositeDebt - DEBT_GAS_COMPENSATION);
emit CloseTrove(vars.account, troveManager, id, receiver, coll, debt, interest);
}
function _getCollChange(uint256 _collReceived, uint256 _requestedCollWithdrawal) internal pure returns (uint256 collChange, bool isCollIncrease) {
if (_collReceived != 0) {
collChange = _collReceived;
isCollIncrease = true;
} else {
collChange = _requestedCollWithdrawal;
}
}
function _requireValidAdjustment(bool _isDebtIncrease, LocalVariables_adjustTrove memory _vars) internal pure {
uint256 newICR = _getNewICRFromTroveChange(_vars.coll, _vars.debt + _vars.interest, _vars.collChange, _vars.isCollIncrease, _vars.debtChange + _vars.interestRepayment, _isDebtIncrease, _vars.price);
_requireICRisAboveMCR(newICR, _vars.MCR);
uint256 newTCR = _getNewTCRFromTroveChange(_vars.totalCollateral * _vars.price, _vars.totalDebt + _vars.totalInterest, _vars.collChange * _vars.price, _vars.isCollIncrease, _vars.debtChange + _vars.interestRepayment, _isDebtIncrease);
if (_vars.isBelowCriticalThreshold) {
if (_isDebtIncrease) {
_requireNewTCRisAboveCCR(newTCR, _vars.CCR);
} else if (!_vars.isCollIncrease) {
require((_vars.debtChange + _vars.interestRepayment) * DECIMAL_PRECISION >= _vars.collChange * _vars.price, "BorrowerOps: Cannot withdraw collateral without paying back debt");
}
} else {
_requireNewTCRisAboveCCR(newTCR, _vars.CCR);
}
}
function _requireICRisAboveMCR(uint256 _newICR, uint256 MCR) internal pure {
require(_newICR >= MCR, "BorrowerOps: An operation that would result in ICR < MCR is not permitted");
}
function _requireICRisAboveCCR(uint256 _newICR, uint256 CCR) internal pure {
require(_newICR >= CCR, "BorrowerOps: An operation that would result in ICR < CCR is not permitted");
}
function _requireNewTCRisAboveCCR(uint256 _newTCR, uint256 CCR) internal pure {
require(_newTCR >= CCR, "BorrowerOps: An operation that would result in TCR < CCR is not permitted");
}
function _requireAtLeastMinNetDebt(uint256 _netDebt) internal view {
require(_netDebt >= minNetDebt, "BorrowerOps: Trove's net debt must be greater than minimum");
}
// Compute the new collateral ratio, considering the change in coll and debt. Assumes 0 pending rewards.
function _getNewICRFromTroveChange(uint256 _coll, uint256 _debt, uint256 _collChange, bool _isCollIncrease, uint256 _debtChange, bool _isDebtIncrease, uint256 _price) internal pure returns (uint256) {
(uint256 newColl, uint256 newDebt) = _getNewTroveAmounts(_coll, _debt, _collChange, _isCollIncrease, _debtChange, _isDebtIncrease);
uint256 newICR = YalaMath._computeCR(newColl, newDebt, _price);
return newICR;
}
function _getNewTroveAmounts(uint256 _coll, uint256 _debt, uint256 _collChange, bool _isCollIncrease, uint256 _debtChange, bool _isDebtIncrease) internal pure returns (uint256, uint256) {
uint256 newColl = _coll;
uint256 newDebt = _debt;
newColl = _isCollIncrease ? _coll + _collChange : _coll - _collChange;
newDebt = _isDebtIncrease ? _debt + _debtChange : _debt - _debtChange;
return (newColl, newDebt);
}
function _getNewTCRFromTroveChange(uint256 totalColl, uint256 totalDebt, uint256 _collChange, bool _isCollIncrease, uint256 _debtChange, bool _isDebtIncrease) internal pure returns (uint256) {
totalDebt = _isDebtIncrease ? totalDebt + _debtChange : totalDebt - _debtChange;
totalColl = _isCollIncrease ? totalColl + _collChange : totalColl - _collChange;
uint256 newTCR = YalaMath._computeCR(totalColl, totalDebt);
return newTCR;
}
function _getCollateralAndTCRData(ITroveManager troveManager) internal returns (IERC20 collateraToken, uint256 coll, uint256 debt, uint256 interest, uint256 price) {
collateraToken = collateraTokens[troveManager];
require(address(collateraToken) != address(0), "BorrowerOps: nonexistent collateral");
(coll, debt, interest, price) = troveManager.getEntireSystemBalances();
}
function getTCR(ITroveManager troveManager) public returns (uint256) {
return troveManager.getTCR();
}
}
DelegatedOps.sol 19 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
contract DelegatedOps {
event DelegateApprovalSet(address indexed caller, address indexed delegate, bool isApproved);
mapping(address owner => mapping(address caller => bool isApproved)) public isApprovedDelegate;
modifier callerOrDelegated(address _account) {
require(msg.sender == _account || isApprovedDelegate[_account][msg.sender], "Delegate not approved");
_;
}
function setDelegateApproval(address _delegate, bool _isApproved) external {
isApprovedDelegate[msg.sender][_delegate] = _isApproved;
emit DelegateApprovalSet(msg.sender, _delegate, _isApproved);
}
}
YalaBase.sol 29 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
/*
* Base contract for TroveManager, BorrowerOperations. Contains global system constants and
* common functions.
*/
contract YalaBase {
uint256 public constant DECIMAL_PRECISION = 1e18;
// Amount of debt to be locked in gas pool on opening troves
uint256 public immutable DEBT_GAS_COMPENSATION;
constructor(uint256 _gasCompensation) {
DEBT_GAS_COMPENSATION = _gasCompensation;
}
// --- Gas compensation functions ---
// Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation
function _getCompositeDebt(uint256 _debt) internal view returns (uint256) {
return _debt + DEBT_GAS_COMPENSATION;
}
function _getNetDebt(uint256 _debt) internal view returns (uint256) {
return _debt - DEBT_GAS_COMPENSATION;
}
}
YalaMath.sol 41 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
library YalaMath {
uint256 internal constant DECIMAL_PRECISION = 1e18;
function _min(uint256 _a, uint256 _b) internal pure returns (uint256) {
return (_a < _b) ? _a : _b;
}
function _max(uint256 _a, uint256 _b) internal pure returns (uint256) {
return (_a >= _b) ? _a : _b;
}
function _computeCR(uint256 _coll, uint256 _debt, uint256 _price) internal pure returns (uint256) {
if (_debt > 0) {
uint256 newCollRatio = (_coll * _price) / _debt;
return newCollRatio;
}
// Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR.
else {
// if (_debt == 0)
return 2 ** 256 - 1;
}
}
function _computeCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {
if (_debt > 0) {
uint256 newCollRatio = (_coll) / _debt;
return newCollRatio;
}
// Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR.
else {
// if (_debt == 0)
return 2 ** 256 - 1;
}
}
}
YalaOwnable.sol 31 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import "../interfaces/IYalaCore.sol";
/**
@title Yala Ownable
@notice Contracts inheriting `YalaOwnable` have the same owner as `YalaCore`.
The ownership cannot be independently modified or renounced.
*/
contract YalaOwnable {
IYalaCore public immutable YALA_CORE;
constructor(address _yalaCore) {
YALA_CORE = IYalaCore(_yalaCore);
}
modifier onlyOwner() {
require(msg.sender == YALA_CORE.owner(), "Only owner");
_;
}
function owner() public view returns (address) {
return YALA_CORE.owner();
}
function guardian() public view returns (address) {
return YALA_CORE.guardian();
}
}
IBorrowerOperations.sol 72 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import "./ITroveManager.sol";
interface IBorrowerOperations {
struct LocalVariables_openTrove {
IERC20 collateralToken;
uint256 price;
uint256 totalCollateral;
uint256 totalDebt;
uint256 totalInterest;
uint256 netDebt;
uint256 compositeDebt;
uint256 MCR;
uint256 CCR;
uint256 ICR;
}
struct LocalVariables_adjustTrove {
IERC20 collateralToken;
uint256 price;
uint256 totalCollateral;
uint256 totalDebt;
uint256 totalInterest;
uint256 collChange;
bool isCollIncrease;
uint256 debt;
uint256 coll;
uint256 interest;
uint256 newDebt;
uint256 newColl;
uint256 stake;
uint256 debtChange;
uint256 interestRepayment;
address account;
uint256 MCR;
uint256 CCR;
bool isBelowCriticalThreshold;
}
struct LocalVariables_closeTrove {
ITroveManager troveManager;
IERC20 collateralToken;
address account;
uint256 totalCollateral;
uint256 totalDebt;
uint256 totalInterest;
uint256 compositeDebt;
uint256 price;
uint256 CCR;
}
enum BorrowerOperation {
openTrove,
closeTrove,
adjustTrove
}
event MinNetDebtUpdated(uint256 minNetDebt);
event CollateralConfigured(ITroveManager troveManager, IERC20 collateralToken);
event TroveManagerRemoved(ITroveManager troveManager);
event TroveCreated(address borrower, ITroveManager troveManager, uint256 id, uint256 _collateralAmount, uint256 _debtAmount);
event AdjustTrove(address borrower, ITroveManager troveManager, uint256 id, uint256 _collDeposit, uint256 _collWithdrawal, uint256 _debtChange, bool _isDebtIncrease);
event CloseTrove(address borrower, ITroveManager troveManager, uint256 id, address receiver, uint256 coll, uint256 debt, uint256 interest);
function minNetDebt() external view returns (uint256);
function collateraTokens(ITroveManager troveManager) external view returns (IERC20);
function repay(ITroveManager troveManager, uint256 id, uint256 _debtAmount) external;
function configureCollateral(ITroveManager troveManager, IERC20 collateralToken) external;
}
IDebtToken.sol 33 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import "./ITroveManager.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IDebtToken is IERC20 {
function burn(address _account, uint256 _amount) external;
function burnWithGasCompensation(address _account, uint256 _amount) external returns (bool);
function enableTroveManager(address _troveManager) external;
function enablePSM(address _psm) external;
function mint(address _account, uint256 _amount) external;
function mintWithGasCompensation(address _account, uint256 _amount) external returns (bool);
function returnFromPool(address _poolAddress, address _receiver, uint256 _amount) external;
function sendToSP(address _sender, uint256 _amount) external;
function DEBT_GAS_COMPENSATION() external view returns (uint256);
function borrowerOperationsAddress() external view returns (address);
function factory() external view returns (address);
function gasPool() external view returns (address);
function troveManager(address) external view returns (bool);
}
IMetadataNFT.sol 19 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IMetadataNFT {
struct TroveData {
uint256 tokenId;
address owner;
IERC20 collToken;
IERC20 debtToken;
uint256 collAmount;
uint256 debtAmount;
uint256 interest;
}
function uri(TroveData memory _troveData) external view returns (string memory);
}
IPriceFeed.sol 29 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IPriceFeed {
event NewOracleRegistered(address token, address chainlinkAggregator, bool isEthIndexed);
event PriceFeedStatusUpdated(address token, address oracle, bool isWorking);
event PriceRecordUpdated(address indexed token, uint256 _price);
function fetchPrice(address _token) external returns (uint256);
function setOracle(address _token, address _chainlinkOracle, bytes4 sharePriceSignature, uint8 sharePriceDecimals, bool _isEthIndexed) external;
function MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND() external view returns (uint256);
function YALA_CORE() external view returns (address);
function RESPONSE_TIMEOUT() external view returns (uint256);
function TARGET_DIGITS() external view returns (uint256);
function guardian() external view returns (address);
function oracleRecords(address) external view returns (address chainLinkOracle, uint8 decimals, bytes4 sharePriceSignature, uint8 sharePriceDecimals, bool isFeedWorking, bool isEthIndexed);
function owner() external view returns (address);
function priceRecords(address) external view returns (uint96 scaledPrice, uint32 timestamp, uint32 lastUpdated, uint80 roundId);
}
ITroveManager.sol 135 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "./IPriceFeed.sol";
import "./IMetadataNFT.sol";
interface ITroveManager is IERC721Enumerable {
// Store the necessary data for a trove
struct Trove {
uint256 debt;
uint256 coll;
uint256 stake;
uint256 interest;
}
struct LocalTroveUpdateVariables {
uint256 id;
uint256 debtChange;
uint256 collChange;
uint256 interestRepayment;
bool isCollIncrease;
bool isDebtIncrease;
address receiver;
}
struct DeploymentParams {
uint256 interestRate; // 1e16 (1%)
uint256 maxDebt;
uint256 spYieldPCT;
uint256 liquidationPenaltySP;
uint256 liquidationPenaltyRedistribution;
uint256 maxCollGasCompensation;
uint256 MCR; // 11e17 (110%)
uint256 SCR;
uint256 CCR;
IMetadataNFT metadataNFT;
}
// Object containing the collateral and debt snapshots for a given active trove
struct RewardSnapshot {
uint256 collateral;
uint256 debt;
uint256 activeInterest;
uint256 defaultedInterest;
}
struct LiquidationValues {
uint256 collOffset;
uint256 debtOffset;
uint256 interestOffset;
uint256 collRedist;
uint256 debtRedist;
uint256 interestRedist;
uint256 debtGasCompensation;
uint256 collGasCompensation;
uint256 remainingDeposits;
uint256 collSurplus;
}
struct SingleLiquidation {
uint256 coll;
uint256 debt;
uint256 interest;
uint256 collGasCompensation;
uint256 debtGasCompensation;
uint256 collToLiquidate;
uint256 collOffset;
uint256 debtOffset;
uint256 interestOffset;
uint256 collRedist;
uint256 debtRedist;
uint256 interestRedist;
uint256 collSurplus;
}
enum TroveManagerOperation {
open,
close,
adjust,
liquidate
}
event CRUpdated(uint256 _MCR, uint256 _SCR, uint256 _CCR);
event ShutDown();
event PauseUpdated(bool _paused);
event PriceFeedUpdated(IPriceFeed priceFeed);
event MetadataNFTUpdated(IMetadataNFT _metadataNFT);
event InterestRateUpdated(uint256 _interestRate);
event MaxSystemDebtUpdated(uint256 _cap);
event SPYieldPCTUpdated(uint256 _spYielPCT);
event LIQUIDATION_PENALTY_SP_Updated(uint256 _penaltySP);
event LIQUIDATION_PENALTY_REDISTRIBUTION_Updated(uint256 _penaltyRedist);
event MAX_COLL_GAS_COMPENSATION_Updated(uint256 _maxCollGasCompensation);
event TroveOpened(uint256 id, address owner, uint256 _collateralAmount, uint256 _compositeDebt, uint256 stake);
event TroveUpdated(uint256 id, uint256 newColl, uint256 newDebt, uint256 newStake, uint256 newInterest, address _receiver, TroveManagerOperation operation);
event TotalStakesUpdated(uint256 newTotalStakes);
event LTermsUpdated(uint256 new_L_collateral, uint256 new_L_debt, uint256 new_L_defaulted_interest);
event Liquidated(address owner, uint256 id, uint256 coll, uint256 debt, uint256 interest, uint256 collSurplus);
event CollateralSent(address _account, uint256 _amount);
event CollSurplusClaimed(address _account, uint256 _amount);
event TroveClosed(uint256 id);
event InterestAccrued(uint256 interest);
event SPYieldAccrued(uint256 yieldFee);
function accrueInterests() external returns (uint256 yieldSP, uint256 yieldFee);
function collateralToken() external view returns (IERC20);
function totalActiveDebt() external view returns (uint256);
function defaultedDebt() external view returns (uint256);
function shutdownAt() external view returns (uint256);
function getEntireSystemDebt() external view returns (uint256);
function getEntireSystemBalances() external returns (uint256 coll, uint256 debt, uint256 interest, uint256 price);
function interestRate() external view returns (uint256);
function MCR() external view returns (uint256);
function SCR() external view returns (uint256);
function CCR() external view returns (uint256);
function maxSystemDebt() external view returns (uint256);
function SP_YIELD_PCT() external view returns (uint256);
function MAX_COLL_GAS_COMPENSATION() external view returns (uint256);
function LIQUIDATION_PENALTY_SP() external view returns (uint256);
function LIQUIDATION_PENALTY_REDISTRIBUTION() external view returns (uint256);
function getTCR() external returns (uint256);
function setParameters(IPriceFeed _priceFeed, IERC20 _collateral, DeploymentParams memory params) external;
function openTrove(address owner, uint256 _collateralAmount, uint256 _compositeDebt) external returns (uint256 id);
function updateTroveFromAdjustment(uint256 id, bool _isDebtIncrease, uint256 _debtChange, bool _isCollIncrease, uint256 _collChange, uint256 _interestRepayment, address _receiver) external returns (uint256, uint256, uint256, uint256);
function closeTrove(uint256 id, address _receiver, uint256 collAmount, uint256 debtAmount, uint256 interest) external;
function applyPendingRewards(uint256 id) external returns (uint256 coll, uint256 debt, uint256 interest);
function fetchPrice() external returns (uint256);
function getCurrentTrove(uint256 id) external view returns (Trove memory);
function getPendingYieldSP() external view returns (uint256);
function accountCollSurplus(address account) external view returns (uint256);
function hasShutdown() external view returns (bool);
function batchLiquidate(uint256[] memory ids) external;
}
IYalaCore.sol 45 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IYalaCore {
event NewOwnerCommitted(address owner, address pendingOwner, uint256 deadline);
event NewOwnerAccepted(address oldOwner, address owner);
event NewOwnerRevoked(address owner, address revokedOwner);
event FeeReceiverSet(address feeReceiver);
event GuardianSet(address guardian);
event Paused();
event Unpaused();
function acceptTransferOwnership() external;
function commitTransferOwnership(address newOwner) external;
function revokeTransferOwnership() external;
function setFeeReceiver(address _feeReceiver) external;
function setGuardian(address _guardian) external;
function setPaused(bool _paused) external;
function OWNERSHIP_TRANSFER_DELAY() external view returns (uint256);
function feeReceiver() external view returns (address);
function guardian() external view returns (address);
function owner() external view returns (address);
function ownershipTransferDeadline() external view returns (uint256);
function paused() external view returns (bool);
function pendingOwner() external view returns (address);
}
Read Contract
DEBT_GAS_COMPENSATION 0x4ba4a28b → uint256
DECIMAL_PRECISION 0xa20baee6 → uint256
YALA_CORE 0x08b6ab95 → address
collateraTokens 0xe75dd592 → address
debtToken 0xf8d89898 → address
factory 0xc45a0155 → address
getCompositeDebt 0x4ff81443 → uint256
guardian 0x452a9320 → address
isApprovedDelegate 0x1930e825 → bool
minNetDebt 0x969c2452 → uint256
owner 0x8da5cb5b → address
Write Contract 11 functions
These functions modify contract state and require a wallet transaction to execute.
addColl 0x7617cd08
address troveManager
uint256 id
uint256 _collateralAmount
adjustTrove 0x74ef871a
address troveManager
uint256 id
uint256 _collDeposit
uint256 _collWithdrawal
uint256 _debtChange
bool _isDebtIncrease
closeTrove 0x6229dcc5
address troveManager
uint256 id
address receiver
configureCollateral 0x778c5c64
address troveManager
address collateralToken
getTCR 0x3d4411a0
address troveManager
returns: uint256
openTrove 0x7ec940a8
address troveManager
address account
uint256 _collateralAmount
uint256 _debtAmount
returns: uint256
removeTroveManager 0xe19c80c2
address troveManager
repay 0x8cd2e0c7
address troveManager
uint256 id
uint256 _debtAmount
setDelegateApproval 0xc3c854b6
address _delegate
bool _isApproved
withdrawColl 0x658e7904
address troveManager
uint256 id
uint256 _collWithdrawal
withdrawDebt 0x41e5e1f5
address troveManager
uint256 id
uint256 _debtAmount
Recent Transactions
No transactions found for this address