Forkchoice Ethereum Mainnet

Address Contract Verified

Address 0x4e601103590b8971c208bF06B64ba1ef1c85B7e6
Balance 0 ETH
Nonce 1
Code Size 16295 bytes
Indexed Transactions 0 (1 on-chain, 1.4% indexed)
External Etherscan · Sourcify

Contract Bytecode

16295 bytes
Copy Bytecode
0x608060405234801561000f575f5ffd5b5060043610610201575f3560e01c80639c92ce8a11610123578063d3573a33116100b8578063edf8378111610088578063f57cca911161006e578063f57cca911461060c578063f897a22b1461061f578063fd60e7b514610646575f5ffd5b8063edf8378114610595578063ee97f7f3146105ed575f5ffd5b8063d3573a33146104b7578063d4f1bc58146104d7578063dc4d5e95146104ea578063e604994e14610509575f5ffd5b8063b5ed298a116100f3578063b5ed298a1461045f578063be3ac30914610472578063c67dd64014610485578063d0262ed014610498575f5ffd5b80639c92ce8a146104105780639d90ac8d14610431578063a2544c6d14610444578063a8bff6921461044c575f5ffd5b80634dd38ae411610199578063715018a611610169578063715018a6146103c157806386074f04146103c95780638caad7b5146103dc5780638e5a1a9f146103ef575f5ffd5b80634dd38ae4146103835780634e71e0c8146103a5578063535391a0146103af578063645006ca146103b8575f5ffd5b806337efa730116101d457806337efa730146102f95780633973b98f146103215780633ef1700714610334578063492d7b1c14610356575f5ffd5b80631d9eaedb14610205578063265b1a12146102305780632c6a9b4f1461027c578063325eb232146102dc575b5f5ffd5b610218610213366004613a5e565b610659565b60405161022793929190613aaf565b60405180910390f35b6102577f00000000000000000000000011ceee394842d9492f2c97050f66de0e3f89d3a681565b60405173ffffffffffffffffffffffffffffffffffffffff9091168152602001610227565b61028f61028a366004613ae7565b610676565b60408051835173ffffffffffffffffffffffffffffffffffffffff16815260208085015190820152838201519181019190915260609283015192810192909252608082015260a001610227565b600a546102e99060ff1681565b6040519015158152602001610227565b61030c610307366004613b07565b6107bd565b60408051928352602083019190915201610227565b61030c61032f366004613b71565b6107f2565b610347610342366004613b07565b610b1e565b60405161022793929190613c26565b610375610364366004613a5e565b60056020525f908152604090205481565b604051908152602001610227565b6102e9610391366004613a5e565b60066020525f908152604090205460ff1681565b6103ad610c33565b005b61037560085481565b61037560095481565b6103ad610c66565b6103756103d7366004613ae7565b610cca565b6103ad6103ea366004613a5e565b610cde565b6104026103fd366004613ae7565b610ceb565b604051610227929190613c5b565b61042361041e366004613c88565b610d03565b604051610227929190613cbb565b6103ad61043f366004613d57565b610d1a565b610423610d53565b61028f61045a366004613b07565b610d68565b6103ad61046d366004613c88565b610e9a565b610375610480366004613a5e565b610f5f565b61028f610493366004613ae7565b610fd1565b6103756104a6366004613a5e565b60076020525f908152604090205481565b6001546102579073ffffffffffffffffffffffffffffffffffffffff1681565b6104026104e5366004613ae7565b6110e8565b6103756104f8366004613a5e565b60046020525f908152604090205481565b61055e610517366004613ae7565b600360208181525f93845260408085209091529183529120805460018201546002830154929093015473ffffffffffffffffffffffffffffffffffffffff90911692919084565b6040805173ffffffffffffffffffffffffffffffffffffffff90951685526020850193909352918301526060820152608001610227565b6105bc7f313ce567add4d438edf58b94ff345d7d38c45b17dfc0f947988d7819dca364f981565b6040517fffffffff000000000000000000000000000000000000000000000000000000009091168152602001610227565b5f546102579073ffffffffffffffffffffffffffffffffffffffff1681565b61030c61061a366004613a5e565b6111f6565b6102577f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4881565b61030c610654366004613ae7565b611255565b60608060606106698460016112a1565b9250925092509193909250565b6106b360405180608001604052805f73ffffffffffffffffffffffffffffffffffffffff1681526020015f81526020015f81526020015f81525090565b5f6106bc611452565b6106c684846114c8565b505f83815260036020908152604080832085845290915290206001810154906106ee816114df565b6106f9858583611532565b610706858286600161155f565b61070f33611624565b61071933836116c3565b604080518681526020810186905290810183905233907fb9b571dd75d5201e8de3446f4c75e8568cbf1c0cc0580e55f81a14d5b9903d609060600160405180910390a260408051608081018252825473ffffffffffffffffffffffffffffffffffffffff16815260018301546020820152600283015491810191909152600390910154606082015291506107ad6001600255565b6107b65f611624565b9250929050565b5f5f6107c7611452565b6107d38585855f611704565b915091506107e05f611624565b6107ea6001600255565b935093915050565b5f5f6107fc611452565b5f6040518060c001604052808d8d808060200260200160405190810160405280939291908181526020018383602002808284375f920191909152505050908252506040805160208d810282810182019093528d82529283019290918e918e9182918501908490808284375f920191909152505050908252506040805160208b810282810182019093528b82529283019290918c918c9182918501908490808284375f92019190915250505090825250602080820189905260408083018990526060909201879052820151908201519192506108d69161183e565b1561090d576040517f981d21c400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f5b8160200151518110156109ea575f5f6109c08460200151848151811061093757610937613d72565b6020026020010151855f0151858151811061095457610954613d72565b602002602001015160035f8860200151888151811061097557610975613d72565b602002602001015181526020019081526020015f205f885f015188815181106109a0576109a0613d72565b602002602001015181526020019081526020015f20600101546001611704565b90925090506109cf8287613dcc565b95506109db8186613dcc565b9450505080600101905061090f565b505f816040015151118015610a0257505f8160600151115b15610a80575f5f610a6083604001515f81518110610a2257610a22613d72565b602090810291909101015184518051610a3d90600190613ddf565b81518110610a4d57610a4d613d72565b602002602001015185606001515f611704565b9092509050610a6f8286613dcc565b9450610a7b8185613dcc565b935050505b8060800151831015610abe576040517f72c05dff00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b8060a00151821115610afc576040517f0daa287b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b50610b065f611624565b610b106001600255565b995099975050505050505050565b6060805f83801580610b305750606481115b15610b39575060645b5f8681526007602052604081205490819003610b7f575050604080515f808252602080830182815283850185528983526005909152929020549094509092509050610c2a565b5f610b8a8288611852565b90505f815f015167ffffffffffffffff811115610ba957610ba9613df2565b604051908082528060200260200182016040528015610bd2578160200160208202803683370190505b505f8a8152600560205260409020546060840181905295509050895b610bfb81848c8c896118ad565b15610c1557610c0c8383838d6118fe565b96509050610bee565b610c1f83836119e7565b909850965050505050505b93509350939050565b610c3b611aeb565b5f80547fffffffffffffffffffffffff00000000000000000000000000000000000000001633179055565b610c6e611b3e565b5f80547fffffffffffffffffffffffff0000000000000000000000000000000000000000908116825560018054909116905560405133917f6172baf984ea013d88b784409f46655b96ba7f2ff91bca1ac9bcd27b113e6eb091a2565b5f610cd58383611b90565b90505b92915050565b610ce6611b3e565b600955565b606080610cf884846110e8565b915091509250929050565b606080610d11836001611bb2565b91509150915091565b610d22611b3e565b600a80547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016911515919091179055565b606080610d605f5f611bb2565b915091509091565b610da560405180608001604052805f73ffffffffffffffffffffffffffffffffffffffff1681526020015f81526020015f81526020015f81525090565b5f610dae611452565b610db9858585611ced565b5f8581526003602090815260408083208784529091529020610ddb8185611d39565b610de58185611dc6565b610dee33611624565b610df833856116c3565b604080518781526020810187905290810185905233907f3e5820dac2d2a1e9d7a5ef70398d513030c0829d3fa3ae5c91b812c1633af4649060600160405180910390a2600181015460408051608081018252835473ffffffffffffffffffffffffffffffffffffffff1681526020810183905260028401549181019190915260039092015460608301529092509050610e916001600255565b6107ea5f611624565b610ea2611b3e565b73ffffffffffffffffffffffffffffffffffffffff8116610eef576040517ff2365b5b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600180547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff831690811790915560405133907f322fd6444c59daffa82e4689b7685b6fafc6109a1eff8a6ca10c5a8e3206cda1905f90a350565b5f8181610f6a611df9565b90505f5b6009811015610fc9578215610fc9575f5f610fa2848460098110610f9457610f94613d72565b602002015160010b86611e54565b9092509050610fb18287613dcc565b9550610fbd8186613ddf565b94505050600101610f6e565b505050919050565b61100e60405180608001604052805f73ffffffffffffffffffffffffffffffffffffffff1681526020015f81526020015f81526020015f81525090565b5f611017611452565b600a5460ff161515600103611060575f831215611060576040517f94a3bb3c00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b61106a8484611f1b565b5f5f6110768686611f66565b9150915061108486866120d7565b61108d33611624565b6110968661211a565b604080518781526020810187905290810182905233907f2bacb630f67543e94c907fc983de496a472e0ab7cd95ddce4aed7549b277b82a9060600160405180910390a290925090506107ad6001600255565b6060805f5f5f5f6110f9888861215c565b93509350935093508067ffffffffffffffff81111561111a5761111a613df2565b604051908082528060200260200182016040528015611143578160200160208202803683370190505b5095505f5b8181101561118f5784818151811061116257611162613d72565b602002602001015187828151811061117c5761117c613d72565b6020908102919091010152600101611148565b5081156111da57604080516001808252818301909252906020808301908036833701905050945082855f815181106111c9576111c9613d72565b6020026020010181815250506111eb565b604080515f81526020810190915294505b505050509250929050565b5f5f5f5f5f61120486610659565b9250925092505f6112158385612292565b80925081975050505f5f61122d848787518c87612332565b909250905061123c8289613dcc565b97506112488184613dcc565b9650505050505050915091565b5f5f61125f611452565b5f848152600360209081526040808320868452909152902060019081015461128a9186918691611704565b915091506112975f611624565b6107b66001600255565b60608060605f6112af612380565b9050855f6112bb611df9565b90505f5b6009811080156112ce57505f83115b15611378575f5f6112f8858585600981106112eb576112eb613d72565b602002015160010b6110e8565b91509150611321868386866009811061131357611313613d72565b602002015160010b88612473565b94505f851180156113325750805115155b156113655761135b868286866009811061134e5761134e613d72565b602002015160010b61255a565b5f94505050611378565b50508061137190613e1f565b90506112bf565b5086801561138557505f82115b15611439575f6113936125ee565b90505f5b6008811080156113a657505f84115b15611436575f5f6113c3868585600881106112eb576112eb613d72565b915091506113ec87838686600881106113de576113de613d72565b602002015160010b89612473565b95505f861180156113fd5750805115155b1561142357611419878286866008811061134e5761134e613d72565b5f95505050611436565b50508061142f90613e1f565b9050611397565b50505b61144283612734565b9550955095505050509250925092565b60028054036114c2576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064015b60405180910390fd5b60028055565b6114d28282612964565b6114db816129aa565b5050565b805473ffffffffffffffffffffffffffffffffffffffff16331461152f576040517f291fc44200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b50565b5f82815260056020526040902054830361155a5760038101545f838152600560205260409020555b505050565b80156115925782546001840154611592916129f19173ffffffffffffffffffffffffffffffffffffffff90911690612a99565b61159d848484612bdf565b5f848152600360208181526040808420868552909152822080547fffffffffffffffffffffffff000000000000000000000000000000000000000016815560018101839055600281018390550181905560088054916115fb83613e56565b90915550505f82815260076020526040812080549161161983613e56565b919050555050505050565b6040517fc849a6b300000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff82811660048301527f00000000000000000000000011ceee394842d9492f2c97050f66de0e3f89d3a6169063c849a6b3906024015f604051808303815f87803b1580156116aa575f5ffd5b505af11580156116bc573d5f5f3e3d5ffd5b5050505050565b6114db73ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000011ceee394842d9492f2c97050f66de0e3f89d3a6168383612c5a565b5f5f61171286868686612d2e565b5f8681526003602090815260408083208884529091528120906117358688611b90565b905080156117435780611745565b855b825490915073ffffffffffffffffffffffffffffffffffffffff1661176d6129f18289612a99565b61177681611624565b611781818884612e1f565b85156117b15760038301545f898152600560205260408120919091556117ac908a9085908b9061155f565b6117ca565b86836001015f8282546117c49190613ddf565b90915550505b604080518a8152602081018a9052908101889052861515606082015273ffffffffffffffffffffffffffffffffffffffff82169033907ffbe916585c9d75b0b4ee74a38090990cc5ca465e497e24e117a4c98b262f2aaa9060800160405180910390a3508593509150505b94509492505050565b5f82515f148015610cd55750505115919050565b6118876040518060c001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f151581525090565b815f0361189657828152610cd8565b8183106118a357816118a5565b825b815292915050565b5f5f861180156118cd57505f848152600460205260409020546060860151105b80156118dd575084516040860151105b80156118f457508215806118f45750818560800151105b9695505050505050565b60608401515f908152600360209081526040808320848452909152812060018101546080870180518493929161193382613e1f565b905250600182015461195e576119498286612e6b565b60608a01919091528694509250611835915050565b8086106119c35787606001518789604001518151811061198057611980613d72565b60209081029190910101526040880180519061199b82613e1f565b9052506119a88187613ddf565b93506119b48286612e6b565b60608a019190915292506119dc565b606088015160208901819052600160a08a01525f945092505b505094509492505050565b606080836040015167ffffffffffffffff811115611a0757611a07613df2565b604051908082528060200260200182016040528015611a30578160200160208202803683370190505b5091505f5b8460400151811015611a8057838181518110611a5357611a53613d72565b6020026020010151838281518110611a6d57611a6d613d72565b6020908102919091010152600101611a35565b508360a0015115611ad35760408051600180825281830190925290602080830190803683370190505090508360200151815f81518110611ac257611ac2613d72565b6020026020010181815250506107b6565b50604080515f81526020810190915290939092509050565b60015473ffffffffffffffffffffffffffffffffffffffff163303611b0c57565b6040517ff2a87d5e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f5473ffffffffffffffffffffffffffffffffffffffff163303611b5e57565b6040517fb4ec2ff200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f5f611b9b83612eaf565b9050611baa8482612710612ede565b949350505050565b6060805f611bbe61300a565b90505f60085467ffffffffffffffff811115611bdc57611bdc613df2565b604051908082528060200260200182016040528015611c4a57816020015b611c3760405180608001604052805f73ffffffffffffffffffffffffffffffffffffffff1681526020015f81526020015f81526020015f81525090565b815260200190600190039081611bfa5790505b5090505f60085467ffffffffffffffff811115611c6957611c69613df2565b604051908082528060200260200182016040528015611c92578160200160208202803683370190505b5090505f805b8451811015611cd257611cc8858281518110611cb657611cb6613d72565b60200260200101518a8a878787613363565b9150600101611c98565b50611cde838383613448565b95509550505050509250929050565b5f8111611d26576040517f1f2a200500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b611d308383612964565b61155a826129aa565b815473ffffffffffffffffffffffffffffffffffffffff163314611d89576040517f291fc44200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b816001015481106114db576040517ffd7850ad00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b611dd36129f13383612a99565b80826001015f828254611de69190613ddf565b909155505060018201546114db906135a3565b611e016139e6565b50604080516101208101825261138881526109c460208201526105dc918101919091526103e860608201526101f4608082015261012c60a082015260c860c0820152606460e08201525f61010082015290565b5f828152600560209081526040808320546004909252822054829190845b8183108015611e8057505f81115b15611f05575f8381526003602090815260408083208a845290915290206001810154611eb157600301549250611e72565b5f5f611ebe838b866135df565b9092509050611ecd8289613dcc565b9750611ed98185613ddf565b9350611ee983600101548b611b90565b811015611ef857505050611f05565b5050600301549250611e72565b611f0f8187613ddf565b93505050509250929050565b5f8211611f54576040517f1f2a200500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b611f5d816129aa565b6114db826135a3565b611fa360405180608001604052805f73ffffffffffffffffffffffffffffffffffffffff1681526020015f81526020015f81526020015f81525090565b5f8281526004602090815260408083205480845260038352818420868552909252822060028101549192909190611fdb846001613dcc565b6040805160808101825233815260208082018b8152828401878152606084018681525f8b815260038086528782208f83528652878220875181547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff9091161781559451600186015592516002850155905192909101919091556004909152919091205490965090915082101561209f575f8281526003602081815260408084208a8552909152909120018490555b5f9081526003602090815260408083209783529681528682206002018590556004905294909420805460010190555090939092509050565b6120e461362e3384612a99565b60088054905f6120f383613e1f565b90915550505f81815260076020526040812080549161211183613e1f565b91905055505050565b61152f73ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000011ceee394842d9492f2c97050f66de0e3f89d3a6163330846136a9565b5f8181526007602052604081205460609190819081908067ffffffffffffffff81111561218b5761218b613df2565b6040519080825280602002602001820160405280156121b4578160200160208202803683370190505b505f87815260056020526040902054909550875b5f811180156121e357505f8881526004602052604090205482105b80156121ee57508284105b15612286575f8281526003602090815260408083208b84529091529020600181015461221f576003015491506121c8565b80600101548210612273578288868151811061223d5761223d613d72565b60209081029190910101528461225281613e1f565b9550508060010154826122659190613ddf565b915080600301549250612280565b8296506001955050612286565b506121c8565b50505092959194509250565b5f80805b845181101561232a575f8582815181106122b2576122b2613d72565b602002602001015190505f8583815181106122cf576122cf613d72565b6020908102919091018101515f84815260038352604080822083835290935291909120600101549091506123038183611b90565b61230d9087613dcc565b95506123198186613dcc565b945050600190920191506122969050565b509250929050565b5f5f5f87511115612376575f86868151811061235057612350613d72565b6020026020010151905083856123669190613ddf565b91506123728282611b90565b9250505b9550959350505050565b612388613a05565b612390611df9565b815260085467ffffffffffffffff8111156123ad576123ad613df2565b6040519080825280602002602001820160405280156123d6578160200160208202803683370190505b50602082015260085467ffffffffffffffff8111156123f7576123f7613df2565b604051908082528060200260200182016040528015612420578160200160208202803683370190505b50604082015260085467ffffffffffffffff81111561244157612441613df2565b60405190808252806020026020018201604052801561246a578160200160208202803683370190505b50606082015290565b805f5b8451811015612551578115612551575f85828151811061249857612498613d72565b6020908102919091018101515f81815260038352604080822089835290935291909120600101549091508015806124ce57508381115b156124da575050612549565b8588602001518960800151815181106124f5576124f5613d72565b60200260200101818152505081886040015189608001518151811061251c5761251c613d72565b60209081029190910101526080880180519061253782613e1f565b9052506125448185613ddf565b935050505b600101612476565b50949350505050565b81511561155a57815f8151811061257357612573613d72565b602002602001015183606001518460a001518151811061259557612595613d72565b6020026020010181815250508083602001518460a0015185608001516125bb9190613dcc565b815181106125cb576125cb613d72565b602090810291909101015260a083018051906125e682613e1f565b905250505050565b6125f6613a3f565b5060408051610100810182527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9c81527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3860208201527ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed4918101919091527ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0c60608201527ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc1860808201527ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa2460a08201527ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff63c60c08201527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec7860e082015290565b60608060608360a00151846080015161274d9190613dcc565b67ffffffffffffffff81111561276557612765613df2565b60405190808252806020026020018201604052801561278e578160200160208202803683370190505b509250836080015167ffffffffffffffff8111156127ae576127ae613df2565b6040519080825280602002602001820160405280156127d7578160200160208202803683370190505b5091508360a0015167ffffffffffffffff8111156127f7576127f7613df2565b604051908082528060200260200182016040528015612820578160200160208202803683370190505b5090505f5b84608001518110156128b0578460200151818151811061284757612847613d72565b602002602001015184828151811061286157612861613d72565b6020026020010181815250508460400151818151811061288357612883613d72565b602002602001015183828151811061289d5761289d613d72565b6020908102919091010152600101612825565b505f5b8460a0015181101561295c5784602001518186608001516128d49190613dcc565b815181106128e4576128e4613d72565b6020026020010151848287608001516128fd9190613dcc565b8151811061290d5761290d613d72565b6020026020010181815250508460600151818151811061292f5761292f613d72565b602002602001015182828151811061294957612949613d72565b60209081029190910101526001016128b3565b509193909250565b5f8181526004602052604090205482106114db576040517f3f6fa84e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f8181526006602052604090205460ff1661152f576040517f803e0be700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040517fb387cdfc00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8381166004830152602482018390527f00000000000000000000000011ceee394842d9492f2c97050f66de0e3f89d3a6169063b387cdfc906044015b5f604051808303815f87803b158015612a7f575f5ffd5b505af1158015612a91573d5f5f3e3d5ffd5b505050505050565b6040517fc849a6b300000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff83811660048301527f00000000000000000000000011ceee394842d9492f2c97050f66de0e3f89d3a6169063c849a6b3906024015f604051808303815f87803b158015612b1f575f5ffd5b505af1158015612b31573d5f5f3e3d5ffd5b50506040517f67bbdfaf00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff85811660048301527f00000000000000000000000011ceee394842d9492f2c97050f66de0e3f89d3a61692506367bbdfaf91506024015f604051808303815f87803b158015612bbb575f5ffd5b505af1158015612bcd573d5f5f3e3d5ffd5b5050505061155a82828563ffffffff16565b5f818152600560205260409020548303612c17576003918201545f818152602093845260408082209382529290935291206002015550565b600380830154600293840180545f908152602084815260408083208784528252808320860185905592549382529384528181209481529390925291209091015550565b60405173ffffffffffffffffffffffffffffffffffffffff831660248201526044810182905261155a9084907fa9059cbb00000000000000000000000000000000000000000000000000000000906064015b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08184030181529190526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fffffffff0000000000000000000000000000000000000000000000000000000090931692909217909152613707565b612d388484612964565b80612dca575f8211612d76576040517f1f2a200500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f8481526003602090815260408083208684529091529020600101548210612dca576040517ffd7850ad00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b612dd3836129aa565b5f838152600560205260409020548414612e19576040517f159460f000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b50505050565b612e6173ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48163385846136a9565b61155a33836116c3565b60038201545f811580612e8b57505f838152600460205260409020548210155b15612ea65750505f81815260046020526040902054806107b6565b50809250929050565b5f5f821215612ed257612ec182613e8a565b612ecd90612710613dcc565b610cd8565b610cd882612710613ddf565b5f80807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff858709858702925082811083820303915050805f03612f3457838281612f2a57612f2a613ec0565b0492505050613003565b808411612f9d576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f4d6174683a206d756c446976206f766572666c6f77000000000000000000000060448201526064016114b9565b5f848688098519600190810187169687900496828603819004959092119093035f82900391909104909201919091029190911760038402600290811880860282030280860282030280860282030280860282030280860282030280860290910302029150505b9392505050565b60408051601180825261024082019092526060915f91906020820161022080368337019050509050611388815f8151811061304757613047613d72565b6020026020010181815250506109c48160018151811061306957613069613d72565b6020026020010181815250506105dc8160028151811061308b5761308b613d72565b6020026020010181815250506103e8816003815181106130ad576130ad613d72565b6020026020010181815250506101f4816004815181106130cf576130cf613d72565b60200260200101818152505061012c816005815181106130f1576130f1613d72565b60200260200101818152505060c88160068151811061311257613112613d72565b60200260200101818152505060648160078151811061313357613133613d72565b6020026020010181815250505f8160088151811061315357613153613d72565b6020026020010181815250507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9c8160098151811061319357613193613d72565b6020026020010181815250507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3881600a815181106131d3576131d3613d72565b6020026020010181815250507ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed481600b8151811061321357613213613d72565b6020026020010181815250507ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0c81600c8151811061325357613253613d72565b6020026020010181815250507ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc1881600d8151811061329357613293613d72565b6020026020010181815250507ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa2481600e815181106132d3576132d3613d72565b6020026020010181815250507ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff63c81600f8151811061331357613313613d72565b6020026020010181815250507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec788160108151811061335357613353613d72565b6020908102919091010152919050565b5f8681526004602052604081205482915b8181101561343c575f8181526003602090815260408083208c8452909152902061339f818a8a613814565b156134335760408051608081018252825473ffffffffffffffffffffffffffffffffffffffff168152600183015460208201526002830154918101919091526003820154606082015287518890869081106133fc576133fc613d72565b60200260200101819052508986858151811061341a5761341a613d72565b60209081029190910101528361342f81613e1f565b9450505b50600101613374565b50509695505050505050565b6060808267ffffffffffffffff81111561346457613464613df2565b6040519080825280602002602001820160405280156134d257816020015b6134bf60405180608001604052805f73ffffffffffffffffffffffffffffffffffffffff1681526020015f81526020015f81526020015f81525090565b8152602001906001900390816134825790505b5091508267ffffffffffffffff8111156134ee576134ee613df2565b604051908082528060200260200182016040528015613517578160200160208202803683370190505b5090505f5b8381101561359a5785818151811061353657613536613d72565b602002602001015183828151811061355057613550613d72565b602002602001018190525084818151811061356d5761356d613d72565b602002602001015182828151811061358757613587613d72565b602090810291909101015260010161351c565b50935093915050565b60095481101561152f576040517f1fbaba3500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f5f5f6135f0866001015486611b90565b9050808410613608578560010154925080915061359a565b5f61361286612eaf565b90506136218561271083612ede565b9794965093945050505050565b6040517f2c12c07400000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8381166004830152602482018390527f00000000000000000000000011ceee394842d9492f2c97050f66de0e3f89d3a61690632c12c07490604401612a68565b60405173ffffffffffffffffffffffffffffffffffffffff80851660248301528316604482015260648101829052612e199085907f23b872dd0000000000000000000000000000000000000000000000000000000090608401612cac565b5f613768826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c65648152508573ffffffffffffffffffffffffffffffffffffffff1661387b9092919063ffffffff16565b905080515f14806137885750808060200190518101906137889190613eed565b61155a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e60448201527f6f7420737563636565640000000000000000000000000000000000000000000060648201526084016114b9565b5f8161384857835473ffffffffffffffffffffffffffffffffffffffff161580159061384357505f8460010154115b611baa565b835473ffffffffffffffffffffffffffffffffffffffff8481169116148015611baa57505f846001015411949350505050565b6060611baa84845f85855f5f8673ffffffffffffffffffffffffffffffffffffffff1685876040516138ad9190613f08565b5f6040518083038185875af1925050503d805f81146138e7576040519150601f19603f3d011682016040523d82523d5f602084013e6138ec565b606091505b50915091506138fd87838387613908565b979650505050505050565b6060831561399d5782515f036139965773ffffffffffffffffffffffffffffffffffffffff85163b613996576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016114b9565b5081611baa565b611baa83838151156139b25781518083602001fd5b806040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016114b99190613f1e565b6040518061012001604052806009906020820280368337509192915050565b6040518060c00160405280613a186139e6565b81526020016060815260200160608152602001606081526020015f81526020015f81525090565b6040518061010001604052806008906020820280368337509192915050565b5f60208284031215613a6e575f5ffd5b5035919050565b5f8151808452602084019350602083015f5b82811015613aa5578151865260209586019590910190600101613a87565b5093949350505050565b606081525f613ac16060830186613a75565b8281036020840152613ad38186613a75565b905082810360408401526118f48185613a75565b5f5f60408385031215613af8575f5ffd5b50508035926020909101359150565b5f5f5f60608486031215613b19575f5ffd5b505081359360208301359350604090920135919050565b5f5f83601f840112613b40575f5ffd5b50813567ffffffffffffffff811115613b57575f5ffd5b6020830191508360208260051b85010111156107b6575f5ffd5b5f5f5f5f5f5f5f5f5f60c08a8c031215613b89575f5ffd5b893567ffffffffffffffff811115613b9f575f5ffd5b613bab8c828d01613b30565b909a5098505060208a013567ffffffffffffffff811115613bca575f5ffd5b613bd68c828d01613b30565b90985096505060408a013567ffffffffffffffff811115613bf5575f5ffd5b613c018c828d01613b30565b9a9d999c50979a969997986060880135976080810135975060a0013595509350505050565b606081525f613c386060830186613a75565b8281036020840152613c4a8186613a75565b915050826040830152949350505050565b604081525f613c6d6040830185613a75565b8281036020840152613c7f8185613a75565b95945050505050565b5f60208284031215613c98575f5ffd5b813573ffffffffffffffffffffffffffffffffffffffff81168114613003575f5ffd5b604080825283519082018190525f9060208501906060840190835b81811015613d3657613d2083855173ffffffffffffffffffffffffffffffffffffffff81511682526020810151602083015260408101516040830152606081015160608301525050565b6020939093019260809290920191600101613cd6565b505083810360208501526118f48186613a75565b801515811461152f575f5ffd5b5f60208284031215613d67575f5ffd5b813561300381613d4a565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b80820180821115610cd857610cd8613d9f565b81810381811115610cd857610cd8613d9f565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b5f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8203613e4f57613e4f613d9f565b5060010190565b5f81613e6457613e64613d9f565b507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0190565b5f7f80000000000000000000000000000000000000000000000000000000000000008203613eba57613eba613d9f565b505f0390565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f60208284031215613efd575f5ffd5b815161300381613d4a565b5f82518060208501845e5f920191825250919050565b602081525f82518060208401528060208501604085015e5f6040828501015260407fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f8301168401019150509291505056fea26469706673582212209edc64fc18913c2cc8bb2370e4b488d83d4aa620c89f29403e55aa2dc0fc8de664736f6c634300081d0033

Verified Source Code Full Match

Compiler: v0.8.29+commit.ab55807c EVM: cancun Optimization: Yes (600000 runs)
QueContract.sol 427 lines
// SPDX-License-Identifier: -- WISE --
// @author: René Hochmuth

pragma solidity =0.8.29;

import "./QueContractUIHelper.sol";

/**
 * @title QueContract
 * @dev Main contract for the queue-based order fulfillment system.
 *
 * This contract implements a sophisticated queue mechanism that allows users to:
 * - Join a queue with vault tokens and specify an incentive rate
 * - Leave the queue and receive their tokens back
 * - Reduce their queue amount partially
 * - Fulfill orders by providing USD tokens in exchange for vault tokens
 *
 * The queue system features:
 * - Multiple incentive levels (positive and negative) for price discovery
 * - Doubly-linked list implementation for efficient order management
 * - Bulk order fulfillment for gas efficiency
 * - Partial order fulfillment capabilities
 * - Automatic order processing based on FIFO principles within each incentive level
 *
 * @notice This contract inherits from QueContractUIHelper which contains
 * the UI helper functions and order planning logic.
 */
contract QueContract is QueContractUIHelper {

    /**
     * @dev Constructor for the QueContract.
     * Initializes the queue contract with a reference to the forward vault.
     *
     * @param _forwardVault The address of the ForwardVaultERC20 contract
     */
    constructor(
        address _forwardVault
    )
        QueContractDeclarations(
            _forwardVault
        )
    {}

    /**
     * @dev Allows a user to join the queue with a specific amount and incentive.
     * Transfers tokens from the user to this contract and creates a new queue member.
     * Updates the proxy balance and emits a JoinQue event.
     * Returns the created queue member and the new member ID.
     *
     * @param _amount The amount of vault tokens to add to the queue
     * @param _incentive The incentive rate for this order (can be positive or negative)
     * @return member The created queue member structure
     * @return newId The unique ID assigned to this queue member
     */
    function joinQue(
        uint256 _amount,
        int256 _incentive
    )
        setProxyBenefactor
        nonReentrant
        external
        returns (
            QueMember memory,
            uint256
        )
    {
        if (negativeIncentivesNotAllowed == true) {
            require(
                _incentive >= 0,
                NegativeIncentiveNotAllowed()
            );
        }

        _validateJoinQue(
            _amount,
            _incentive
        );

        (
            QueMember memory member,
            uint256 newId
        ) = _createQueMember(
            _amount,
            _incentive
        );

        _updateJoinQueState(
            _amount,
            _incentive
        );

        _setProxyBenefactor(
            msg.sender
        );

        _transferTokensIn(
            _amount
        );

        emit JoinQue(
            msg.sender,
            _amount,
            _incentive,
            newId
        );

        return (
            member,
            newId
        );
    }

    /**
     * @dev Allows a user to leave the queue by removing their queue member.
     * Validates the member can leave, updates linked list pointers, and transfers tokens back to the user.
     * Emits a LeaveQue event with the cashed amount.
     * Returns the queue member and the withdrawn amount.
     *
     * @param _queMemberId The ID of the queue member to remove
     * @param _incentive The incentive level of the queue member
     * @return member The queue member structure that was removed
     * @return leftOverAmount The amount of tokens returned to the user
     */
    function leaveQue(
        uint256 _queMemberId,
        int256 _incentive
    )
        setProxyBenefactor
        nonReentrant
        external
        returns (
            QueMember memory,
            uint256 leftOverAmount
        )
    {
        _validateLeaveQue(
            _queMemberId,
            _incentive
        );

        QueMember storage member = QueMemberByIdAndIncentive[_queMemberId][_incentive];
        leftOverAmount = member.amount;

        _validateMemberCanLeave(
            member
        );

        _updateCurrentOrderIfNeeded(
            _queMemberId,
            _incentive,
            member
        );

        _finalizeMemberRemoval(
            _queMemberId,
            member,
            _incentive,
            true
        );

        _setProxyBenefactor(
            msg.sender
        );

        _transferTokensOut(
            msg.sender,
            leftOverAmount
        );

        emit LeaveQue(
            msg.sender,
            _queMemberId,
            _incentive,
            leftOverAmount
        );

        return (
            member,
            leftOverAmount
        );
    }

    /**
     * @dev Allows a user to reduce their queue amount by a specified amount.
     * Validates the reduction is possible, updates the member's amount, and transfers the reduced tokens out.
     * Ensures the remaining amount meets minimum deposit requirements.
     * Returns the queue member and the remaining amount after reduction.
     *
     * @param _queMemberId The ID of the queue member to reduce
     * @param _incentive The incentive level of the queue member
     * @param _reduceBy The amount to reduce the queue member by
     * @return member The updated queue member structure
     * @return leftOverAmount The remaining amount in the queue member
     */
    function reduceQueAmount(
        uint256 _queMemberId,
        int256 _incentive,
        uint256 _reduceBy
    )
        external
        setProxyBenefactor
        nonReentrant
        returns (
            QueMember memory,
            uint256 leftOverAmount
        )
    {
        _validateReduceAmount(
            _queMemberId,
            _incentive,
            _reduceBy
        );

        QueMember storage member = QueMemberByIdAndIncentive[_queMemberId][_incentive];

        _validateMemberCanReduce(
            member,
            _reduceBy
        );

        _executeReduction(
            member,
            _reduceBy
        );

        _setProxyBenefactor(
            msg.sender
        );

        _transferTokensOut(
            msg.sender,
            _reduceBy
        );

        emit ReduceQueAmount(
            msg.sender,
            _queMemberId,
            _incentive,
            _reduceBy
        );

        return (
            member,
            member.amount
        );
    }

    /**
     * @dev Fulfills a complete order for a specific queue member.
     * Processes the order by transferring discounted USD tokens to the member and vault tokens to the fulfiller.
     * Removes the member from the queue and updates the current order pointer.
     * Returns the forward vault token amount and stablecoin token amount processed.
     *
     * @param _queMemberId The ID of the queue member to fulfill
     * @param _incentive The incentive level of the queue member
     * @return forwardVaultTokenAmount The amount of vault tokens transferred to the fulfiller
     * @return stableCoinTokenAmount The amount of USD tokens transferred to the queue member
     */
    function fulfillOrder(
        uint256 _queMemberId,
        int256 _incentive
    )
        nonReentrant
        setProxyBenefactor
        external
        returns (
            uint256 forwardVaultTokenAmount,
            uint256 stableCoinTokenAmount
        )
    {
        return _processOrder(
            _queMemberId,
            _incentive,
            QueMemberByIdAndIncentive[_queMemberId][_incentive].amount,
            true
        );
    }

    /**
     * @dev Partially fulfills an order for a specific queue member with a specified amount.
     * Processes the partial order by transferring discounted USD tokens to the member and vault tokens to the fulfiller.
     * Reduces the member's amount but keeps them in the queue.
     * Returns the forward vault token amount and stablecoin token amount processed.
     *
     * @param _queMemberId The ID of the queue member to partially fulfill
     * @param _incentive The incentive level of the queue member
     * @param _amount The amount to fulfill (must be less than the member's total amount)
     * @return forwardVaultTokenAmount The amount of vault tokens transferred to the fulfiller
     * @return stableCoinTokenAmount The amount of USD tokens transferred to the queue member
     */
    function partiallyFulfillOrder(
        uint256 _queMemberId,
        int256 _incentive,
        uint256 _amount
    )
        nonReentrant
        setProxyBenefactor
        external
        returns (
            uint256 forwardVaultTokenAmount,
            uint256 stableCoinTokenAmount
        )
    {
        return _processOrder({
            _queMemberId: _queMemberId,
            _incentive: _incentive,
            _amount: _amount,
            _isFullFulfill: false
        });
    }

    /**
     * @dev Fulfills multiple orders in a single transaction for gas efficiency.
     * Processes a combination of full orders and partial orders across different incentives.
     * Validates that the total cost doesn't exceed the maximum USD spend and that the received amount meets minimum requirements.
     *
     * @param _incentives Array of incentive levels for each order
     * @param _memberIds Array of queue member IDs for full orders
     * @param _partialId Array of queue member IDs for partial orders
     * @param _partialAmount The amount to fulfill for the partial order
     * @param _minReceiveAmount Minimum amount of vault tokens that must be received
     * @param _maxUsdToSpend Maximum amount of USD tokens that can be spent
     * @return vaultTokensReceived Total amount of vault tokens received
     * @return usdSpent Total amount of USD tokens spent
     */
    function fulfillOrderBulk(
        int256[] calldata _incentives,
        uint256[] calldata _memberIds,
        uint256[] calldata _partialId,
        uint256 _partialAmount,
        uint256 _minReceiveAmount,
        uint256 _maxUsdToSpend
    )
        nonReentrant
        setProxyBenefactor
        external
        returns (
            uint256 vaultTokensReceived,
            uint256 usdSpent
        )
    {
        FulfillOrderBulkVars memory vars = FulfillOrderBulkVars({
            incentives: _incentives,
            orders: _memberIds,
            partials: _partialId,
            partialAmount: _partialAmount,
            minReceiveAmount: _minReceiveAmount,
            maxUsdToSpend: _maxUsdToSpend
        });

        require(
            _hasNoOrdersToProcess(vars.orders, vars.partials) == false,
            NoOrdersPresent()
        );

        for (uint256 i; i < vars.orders.length; ++i) {
            (
                uint256 vt,
                uint256 usd
            ) = _processOrder({
                _queMemberId: vars.orders[i],
                _incentive: vars.incentives[i],
                _amount: QueMemberByIdAndIncentive[vars.orders[i]][vars.incentives[i]].amount,
                _isFullFulfill: true
            });

            vaultTokensReceived += vt;
            usdSpent            += usd;
        }

        if (vars.partials.length > 0 && vars.partialAmount > 0) {

            (
                uint256 vt,
                uint256 usd
            ) = _processOrder({
                _queMemberId: vars.partials[0],
                _incentive: vars.incentives[vars.incentives.length - 1],
                _amount: vars.partialAmount,
                _isFullFulfill: false
            });

            vaultTokensReceived += vt;
            usdSpent            += usd;
         }

        require(
            vaultTokensReceived >= vars.minReceiveAmount,
            AmountReceivedTooLow()
        );

        require(
            usdSpent <= vars.maxUsdToSpend,
            AmountSpentTooHigh()
        );
    }

    /**
     * @dev Changes the minimum deposit amount for new queue members.
     * Only callable by the master account.
     *
     * @param _minDepositAmount The new minimum deposit amount
     */
    function changeMinDepositAmount(
        uint256 _minDepositAmount
    )
        external
        onlyMaster
    {
        minDepositAmount = _minDepositAmount;
    }

    /**
     * @dev Allows the master to set whether negative incentives are allowed.
     * Only callable by the master account.
     *
     * @param _negativeIncentivesNotAllowed The new value for negative incentives allowed
     */
    function setNegativeIncentivesNotAllowed(
        bool _negativeIncentivesNotAllowed
    )
        external
        onlyMaster
    {
        negativeIncentivesNotAllowed = _negativeIncentivesNotAllowed;
    }
}
QueContractUIHelper.sol 319 lines
// SPDX-License-Identifier: -- WISE --
// @author: René Hochmuth

pragma solidity =0.8.29;

import "./QueContractHelper.sol";

/**
 * @title QueContractUIHelper
 * @dev UI helper contract providing user-friendly functions for queue interaction and order planning.
 *
 * This contract provides:
 * - Order fulfillment planning and simulation
 * - Cost prediction functions for user interface
 * - Order retrieval functions for display purposes
 * - Bulk order analysis capabilities
 *
 * The contract implements user-friendly functions that:
 * - Allow users to predict costs before placing orders
 * - Enable order planning without execution
 * - Provide comprehensive order book visibility
 * - Support efficient bulk operations for UIs
 *
 * @notice This contract inherits from QueContractHelper which contains
 * the core order processing and solving logic.
 */
abstract contract QueContractUIHelper is QueContractHelper {

    /**
     * @dev Generates a fulfillment plan for a specific amount and incentive.
     * Traverses the queue to determine which orders need to be fulfilled to meet the requested amount.
     * Returns arrays of full and partial order IDs that would be processed.
     *
     * @param _amount The amount of vault tokens to acquire
     * @param _incentive The incentive level to process
     * @param _maxOrdersToConsider Maximum number of orders to consider (0 for unlimited)
     * @return fullOrderIds Array of full order IDs that can be completely fulfilled
     * @return partialOrderIds Array of partial order IDs (if needed)
     * @return nextStartingId The next order ID to start processing from after this plan
     */
    function getFulfillmentPlanForIncentive(
        uint256 _amount,
        int256 _incentive,
        uint256 _maxOrdersToConsider
    )
        public
        view
        returns (
            uint256[] memory fullOrderIds,
            uint256[] memory partialOrderIds,
            uint256 nextStartingId
        )
    {
        uint256 considerationLimit = _maxOrdersToConsider;

        if (considerationLimit == 0 || considerationLimit > MAX_ORDERS_TO_CONSIDER_LIMIT) {
            considerationLimit = MAX_ORDERS_TO_CONSIDER_LIMIT;
        }

        uint256 activeCount = activeOrderCountByIncentive[_incentive];
        if (activeCount == 0) {
            fullOrderIds = new uint256[](0);
            partialOrderIds = new uint256[](0);
            nextStartingId = currentOrderIdByIncentive[_incentive];
            return (
                fullOrderIds,
                partialOrderIds,
                nextStartingId
            );
        }

        PlanVars memory v = _initializePlanVars(
            activeCount,
            _maxOrdersToConsider
        );

        uint256[] memory tempFull = new uint256[](v.arraySize);
        v.current = currentOrderIdByIncentive[_incentive];
        nextStartingId = v.current;
        uint256 amountLeft = _amount;

        while (_shouldContinuePlanTraversal(amountLeft, v, _incentive, _maxOrdersToConsider, considerationLimit)) {
            (
                amountLeft,
                nextStartingId
            ) = _processOrderInPlan(
                v,
                tempFull,
                amountLeft,
                _incentive
            );
        }

        (
            fullOrderIds,
            partialOrderIds
        ) = _buildFinalOrderArrays(
            v,
            tempFull
        );
    }

    /**
     * @dev Solves for the optimal order combination to fulfill a specific amount across all incentives.
     * Returns arrays of incentives, order IDs, and partial order IDs needed to fulfill the amount.
     * Orders are prioritized by incentive level (highest to lowest).
     *
     * @param _amount The amount of vault tokens to acquire
     * @return incentives Array of incentive levels for each order
     * @return orders Array of full order IDs
     * @return partials Array of partial order IDs
     */
    function solveForAmount(
        uint256 _amount
    )
        public
        view
        returns (
            int256[] memory incentives,
            uint256[] memory orders,
            uint256[] memory partials
        )
    {
        return _solveForAmount(
            _amount,
            true
        );
    }

    /**
     * @dev Calculates the discounted amount for a given base amount and incentive.
     * Applies the incentive as a percentage discount or premium to the base amount.
     * Returns the final amount after applying the incentive factor.
     *
     * @param _amount The base amount to apply the incentive to
     * @param _incentive The incentive rate (positive for discount, negative for premium)
     * @return discountedAmount The final amount after applying the incentive
     */
    function predictDiscountedAmount(
        uint256 _amount,
        int256 _incentive
    )
        public
        pure
        returns (
            uint256 discountedAmount
        )
    {
        return _predictDiscountedAmount(
            _amount,
            _incentive
        );
    }

    /**
     * @notice Predicts the exact USDC cost to receive a specific amount of vault tokens.
     * @dev This function simulates a call to `fulfillOrderBySolveForAmount` by using the same
     * `solveForAmount` plan and `predictDiscountedAmount` calculations.
     *
     * @param _tokensToReceive The desired amount of vault tokens
     * @return costInUsd The exact cost in USDC to acquire the tokens
     * @return tokensAcquirable The actual amount of tokens that can be acquired. This may be less than
     * `_tokensToReceive` if the queue has insufficient liquidity
     */
    function predictCostForTokens(
        uint256 _tokensToReceive
    )
        public
        view
        returns (
            uint256 costInUsd,
            uint256 tokensAcquirable
        )
    {
        (
            int256[] memory incentives,
            uint256[] memory orders,
            uint256[] memory partials
        ) = solveForAmount(
            _tokensToReceive
        );

        uint256 totalTokensPlanned;

        (
            costInUsd,
            totalTokensPlanned
        ) = _calculateFullOrdersCost(
            orders,
            incentives
        );

        (
            uint256 partialCost,
            uint256 partialTokens
        ) = _calculatePartialOrderCost(
            partials,
            incentives,
            orders.length,
            _tokensToReceive,
            totalTokensPlanned
        );

        costInUsd += partialCost;
        tokensAcquirable = totalTokensPlanned + partialTokens;
    }

    /**
     * @dev Solves for the optimal order combination to fulfill a specific amount for a given incentive.
     * Returns arrays of full and partial order IDs that would be processed for that specific incentive.
     * Useful for planning order fulfillment within a single incentive level.
     *
     * @param _amount The amount of vault tokens to acquire
     * @param _incentive The incentive level to process
     * @return fullOrderIds Array of full order IDs that can be completely fulfilled
     * @return partialOrderIds Array of partial order IDs (if needed)
     */
    function solveForAmountWithIncentive(
        uint256 _amount,
        int256 _incentive
    )
        public
        view
        returns (
            uint256[] memory fullOrderIds,
            uint256[] memory partialOrderIds
        )
    {
        return _solveForAmountWithIncentive(
            _amount,
            _incentive
        );
    }

    /**
     * @notice Predicts the exact amount of vault tokens that will be received for a given USDC cost.
     * @dev This function simulates "spending" a USDC budget against the order book, starting
     * from the highest incentive, to calculate the total tokens acquired.
     *
     * @param _costInUsd The amount of USDC a user is willing to send
     * @return tokensReceived The exact amount of vault tokens that will be received
     */
    function predictTokensForCost(
        uint256 _costInUsd
    )
        public
        view
        returns (
            uint256 tokensReceived
        )
    {
        uint256 remainingUsd = _costInUsd;
        int16[9] memory incs = _initializePositiveIncentivesArray();

        for (uint256 i = 0; i < incs.length; i++) {
            if (remainingUsd == 0) break;

            (
                uint256 tokens,
                uint256 spent
            ) = _processIncentiveForCost(
                incs[i],
                remainingUsd
            );

            tokensReceived += tokens;
            remainingUsd -= spent;
        }

        return tokensReceived;
    }

    /**
     * @dev Retrieves all active orders for a specific user address.
     * Returns arrays of QueMember structs and their corresponding incentives.
     * Only includes orders where the member matches the specified user address.
     *
     * @param _user The address of the user whose orders to retrieve
     * @return Array of QueMember structs for the user's orders
     * @return Array of incentive levels corresponding to each order
     */
    function getAllOrdersfromAddress(
        address _user
    )
        public
        view
        returns (
            QueMember[] memory,
            int256[] memory
        )
    {
        return _collectAllOrders(
            _user,
            true
        );
    }

    /**
     * @dev Retrieves all active orders across all users in the system.
     * Returns arrays of QueMember structs and their corresponding incentives.
     * Includes all orders regardless of the member address.
     *
     * @return Array of QueMember structs for all active orders
     * @return Array of incentive levels corresponding to each order
     */
    function getAllOrdersOverall()
        public
        view
        returns (
            QueMember[] memory,
            int256[] memory
        )
    {
        return _collectAllOrders(
            address(0),
            false
        );
    }
}
QueContractHelper.sol 419 lines
// SPDX-License-Identifier: -- WISE --
// @author: René Hochmuth

pragma solidity =0.8.29;

import "./QueContractLowLevelHelper.sol";

/**
 * @title QueContractHelper
 * @dev Helper contract containing the core logic for queue operations and order processing.
 *
 * This contract provides:
 * - Order processing logic for both full and partial fulfillments
 * - Queue traversal algorithms for order planning
 * - Cost calculation functions for order optimization
 * - Bulk order solving capabilities across multiple incentives
 *
 * The contract implements sophisticated order management that:
 * - Processes orders based on FIFO principles within each incentive level
 * - Handles both full and partial order fulfillments
 * - Optimizes order combinations for cost efficiency
 * - Supports bulk operations for gas efficiency
 *
 * @notice This contract inherits from QueContractLowLevelHelper which contains
 * the low-level helper functions and data structures.
 */
abstract contract QueContractHelper is QueContractLowLevelHelper {

    /**
     * @dev Modifier that sets the proxy benefactor for the forward vault during function execution.
     * Ensures the proxy benefactor is reset to zero address after the function completes.
     */
    modifier setProxyBenefactor() {
        _;

        _setProxyBenefactor(
            ZERO_ADDRESS
        );
    }

    /**
     * @dev Processes an order by validating it, calculating discounted amounts, and executing transfers.
     * Updates order state and emits an OrderProcessed event.
     * Returns the forward vault token amount and stablecoin token amount processed.
     *
     * @param _queMemberId The ID of the queue member to process
     * @param _incentive The incentive level of the order
     * @param _amount The amount to process (full amount for complete fulfillment, partial for partial fulfillment)
     * @param _isFullFulfill True if this is a complete fulfillment, false for partial
     * @return forwardVaultTokenAmount The amount of vault tokens transferred to the fulfiller
     * @return stableCoinTokenAmount The amount of USD tokens transferred to the queue member
     */
    function _processOrder(
        uint256 _queMemberId,
        int256 _incentive,
        uint256 _amount,
        bool _isFullFulfill
    )
        internal
        returns (
            uint256 forwardVaultTokenAmount,
            uint256 stableCoinTokenAmount
        )
    {
        _validateOrderProcessing(
            _queMemberId,
            _incentive,
            _amount,
            _isFullFulfill
        );

        QueMember storage member = QueMemberByIdAndIncentive[_queMemberId][_incentive];

        uint256 discountedAmount = _predictDiscountedAmount(
            _amount,
            _incentive
        );

        discountedAmount = discountedAmount == 0
            ? _amount
            : discountedAmount;

        address cashedMember = member.member;

        _changeProxyAccounting(
            _decreaseProxyBalance,
            cashedMember,
            _amount
        );

        _setProxyBenefactor(
            cashedMember
        );

        _executeTransfers(
            cashedMember,
            _amount,
            discountedAmount
        );

        if (_isFullFulfill) {
            currentOrderIdByIncentive[_incentive] = member.headPointer;

            _finalizeMemberRemoval(
                _queMemberId,
                member,
                _incentive,
                false
            );

        } else {
            member.amount -= _amount;
        }

        emit OrderProcessed(
            msg.sender,
            cashedMember,
            _queMemberId,
            _incentive,
            _amount,
            _isFullFulfill
        );

        return (
            _amount,
            discountedAmount
        );
    }

    /**
     * @dev Processes an order within a plan traversal.
     * Handles empty orders, full orders, and partial orders based on remaining amount.
     * Returns the new remaining amount and next starting ID.
     *
     * @param _v The plan variables containing traversal state
     * @param _tempFull Temporary array to store full order IDs
     * @param _amountLeft The remaining amount to process
     * @param _incentive The incentive level being processed
     * @return newAmountLeft The remaining amount after processing this order
     * @return nextStartingId The next order ID to start processing from
     */
    function _processOrderInPlan(
        PlanVars memory _v,
        uint256[] memory _tempFull,
        uint256 _amountLeft,
        int256 _incentive
    )
        internal
        view
        returns (
            uint256 newAmountLeft,
            uint256 nextStartingId
        )
    {
        QueMember storage entry = QueMemberByIdAndIncentive[_v.current][_incentive];
        uint256 amt = entry.amount;
        _v.ordersConsidered++;

        if (_isEmptyOrder(entry)) {
            (
                _v.current,
                nextStartingId
            ) = _moveToNextOrder(
                entry,
                _incentive
            );

            return (
                _amountLeft,
                nextStartingId
            );
        }

        if (_amountLeft >= amt) {
            _tempFull[_v.fullIndex] = _v.current;
            _v.fullIndex++;
            newAmountLeft = _amountLeft - amt;
            (
                _v.current,
                nextStartingId
            ) = _moveToNextOrder(
                entry,
                _incentive
            );

        } else {
            _v.partialId = _v.current;
            _v.hasPartial = true;
            newAmountLeft = 0;
            nextStartingId = _v.current;
        }
    }

    /**
     * @dev Traverses orders for a specific amount and incentive.
     * Builds arrays of full orders and identifies partial orders needed.
     * Returns temporary arrays and flags for order processing.
     *
     * @param _amount The amount of tokens to acquire
     * @param _incentive The incentive level to process
     * @return tempFull Array of full order IDs that can be completely fulfilled
     * @return partialId ID of the partial order (if needed)
     * @return hasPartial True if a partial order is needed
     * @return fullIndex Number of full orders found
     */
    function _traverseOrdersForAmount(
        uint256 _amount,
        int256 _incentive
    )
        internal
        view
        returns (
            uint256[] memory tempFull,
            uint256 partialId,
            bool hasPartial,
            uint256 fullIndex
        )
    {
        uint256 total = activeOrderCountByIncentive[_incentive];
        tempFull = new uint256[](total);
        uint256 current = currentOrderIdByIncentive[_incentive];
        uint256 amountLeft = _amount;

        while (amountLeft > 0 && current < earliestValidQueMemberByIncentive[_incentive] && fullIndex < total) {
            QueMember storage entry = QueMemberByIdAndIncentive[current][_incentive];

            if (_isEmptyOrder(entry)) {
                current = entry.headPointer;
                continue;
            }

            if (amountLeft >= entry.amount) {
                tempFull[fullIndex] = current;
                fullIndex++;
                amountLeft -= entry.amount;
                current = entry.headPointer;
            } else {
                partialId = current;
                hasPartial = true;
                break;
            }
        }
    }

    /**
     * @dev Processes all orders for a specific incentive during cost calculation.
     * Traverses the queue for the incentive and calculates total tokens and USD spent.
     *
     * @param _incentive The incentive level to process
     * @param _remainingUsd The remaining USD budget to spend
     * @return tokensReceived The total tokens that can be acquired
     * @return usdSpent The total USD that will be spent
     */
    function _processIncentiveForCost(
        int256 _incentive,
        uint256 _remainingUsd
    )
        internal
        view
        returns (
            uint256 tokensReceived,
            uint256 usdSpent
        )
    {
        uint256 currentOrderId = currentOrderIdByIncentive[_incentive];
        uint256 earliestId = earliestValidQueMemberByIncentive[_incentive];
        uint256 remainingBudget = _remainingUsd;

        while (currentOrderId < earliestId && remainingBudget > 0) {
            QueMember storage entry = QueMemberByIdAndIncentive[currentOrderId][_incentive];

            if (_isEmptyOrder(entry)) {
                currentOrderId = entry.headPointer;
                continue;
            }

            (
                uint256 tokens,
                uint256 spent
            ) = _processOrderForCost(
                entry,
                _incentive,
                remainingBudget
            );

            tokensReceived += tokens;
            remainingBudget -= spent;

            if (spent < _predictDiscountedAmount(entry.amount, _incentive)) {
                break;
            }

            currentOrderId = entry.headPointer;
        }

        usdSpent = _remainingUsd - remainingBudget;
    }

    /**
     * @dev Solves for the optimal order combination to fulfill a specific amount for a given incentive.
     * Returns arrays of full and partial order IDs that would be processed for that specific incentive.
     *
     * @param _amount The amount of tokens to acquire
     * @param _incentive The incentive level to process
     * @return fullOrderIds Array of full order IDs that can be completely fulfilled
     * @return partialOrderIds Array of partial order IDs (if needed)
     */
    function _solveForAmountWithIncentive(
        uint256 _amount,
        int256 _incentive
    )
        public
        view
        returns (
            uint256[] memory fullOrderIds,
            uint256[] memory partialOrderIds
        )
    {
        (
            uint256[] memory tempFull,
            uint256 partialId,
            bool hasPartial,
            uint256 fullIndex
        ) = _traverseOrdersForAmount(
            _amount,
            _incentive
        );

        fullOrderIds = new uint256[](fullIndex);

        for (uint256 i; i < fullIndex; i++) {
            fullOrderIds[i] = tempFull[i];
        }

        if (hasPartial) {
            partialOrderIds = new uint256[](1);
            partialOrderIds[0] = partialId;
        } else {
            partialOrderIds = new uint256[](0);
        }
    }

    /**
     * @dev Solves for the optimal order combination to fulfill a specific amount across all incentives.
     * Processes orders starting from the highest incentive down to the lowest.
     * Returns arrays of incentives, order IDs, and partial order IDs needed.
     *
     * @param _amount The amount of tokens to acquire
     * @param _allowNegativeIncentives Whether to consider negative incentives if positive ones are insufficient
     * @return incentives Array of incentive levels for each order
     * @return orders Array of full order IDs
     * @return partials Array of partial order IDs
     */
    function _solveForAmount(
        uint256 _amount,
        bool    _allowNegativeIncentives
    )
        internal
        view
        returns (
            int256[] memory incentives,
            uint256[] memory orders,
            uint256[] memory partials
        )
    {
        SolveForAmountVars memory v = _initializeSolveVars();
        uint256 remainingAmount = _amount;

        int16[9] memory pos = _initializePositiveIncentivesArray();

        for (uint256 i; i < pos.length && remainingAmount > 0; ++i) {
            (
                uint256[] memory fullIds,
                uint256[] memory partialIds
            ) = _solveForAmountWithIncentive(remainingAmount, pos[i]);

            remainingAmount = _processFullOrdersForIncentive(
                v,
                fullIds,
                pos[i],
                remainingAmount
            );

            if (remainingAmount > 0 && partialIds.length != 0) {
                _processPartialOrderForIncentive(v, partialIds, pos[i]);
                remainingAmount = 0;
                break;
            }
        }

        if (_allowNegativeIncentives && remainingAmount > 0) {
            int16[8] memory neg = _initializeNegativeIncentivesArray();

            for (uint256 j; j < neg.length && remainingAmount > 0; ++j) {
                (
                    uint256[] memory fullIds,
                    uint256[] memory partialIds
                ) = _solveForAmountWithIncentive(remainingAmount, neg[j]);

                remainingAmount = _processFullOrdersForIncentive(
                    v,
                    fullIds,
                    neg[j],
                    remainingAmount
                );

                if (remainingAmount > 0 && partialIds.length != 0) {
                    _processPartialOrderForIncentive(v, partialIds, neg[j]);
                    remainingAmount = 0;
                    break;
                }
            }
        }

        return _buildSolveResults(
            v
        );
    }
}
QueContractLowLevelHelper.sol 1095 lines
// SPDX-License-Identifier: -- WISE --
// @author: René Hochmuth

pragma solidity =0.8.29;

import "./QueContractDeclarations.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";

/**
 * @title QueContractLowLevelHelper
 * @dev Low-level helper contract containing the foundational logic for queue operations.
 *
 * This contract provides:
 * - Queue member creation and management
 * - Token transfer operations with safety checks
 * - Validation functions for all queue operations
 * - Linked list manipulation for efficient queue traversal
 * - Order processing and fulfillment logic
 * - Cost calculation and optimization algorithms
 *
 * The contract implements sophisticated queue management that:
 * - Maintains doubly-linked lists for each incentive level
 * - Ensures queue integrity during member additions and removals
 * - Provides efficient order traversal and processing
 * - Handles complex order solving across multiple incentives
 * - Supports bulk operations for gas efficiency
 *
 * @notice This contract inherits from QueContractDeclarations which contains
 * all the state variables, events, and error definitions.
 */
abstract contract QueContractLowLevelHelper is QueContractDeclarations {

    using SafeERC20 for IERC20;

    /**
     * @dev Sets the proxy benefactor for the forward vault.
     * Internal function used by the setProxyBenefactor modifier.
     */
    function _setProxyBenefactor(
        address _user
    )
        internal
    {
        forwardVault.setProxyBenefactor(
            _user
        );
    }

    /**
     * @dev Validates the parameters for joining the queue.
     * Ensures amount is greater than zero, incentive is allowed, and amount meets minimum deposit requirements.
     */
    function _validateJoinQue(
        uint256 _amount,
        int256 _incentive
    )
        internal
        view
    {
        require(
            _amount > 0,
            ZeroAmount()
        );

        _requireIncentiveAllowed(
            _incentive
        );

        _requireMinDeposit(
            _amount
        );
    }

    /**
     * @dev Transfers vault tokens from the sender to this contract.
     * Uses SafeERC20 for secure token transfers.
     */
    function _transferTokensIn(
        uint256 _amount
    )
        internal
    {
        IERC20(address(forwardVault)).safeTransferFrom(
            msg.sender,
            address(this),
            _amount
        );
    }

    /**
     * @dev Creates a new queue member with the specified amount and incentive.
     * Ensures that both forward and back links are written so the
     * list remains well-formed even when the new slot is the current
     * "first-free" sentinel.
     */
    function _createQueMember(
        uint256 _amount,
        int256  _incentive
    )
        internal
        returns (
            QueMember memory member,
            uint256 newId
        )
    {
        newId = earliestValidQueMemberByIncentive[_incentive];
        QueMember storage hole = QueMemberByIdAndIncentive[newId][_incentive];

        uint256 prevId = hole.tailPointer;

        uint256 nextId = newId + 1;

        member = QueMember({
            member:      msg.sender,
            amount:      _amount,
            tailPointer: prevId,
            headPointer: nextId
        });

        QueMemberByIdAndIncentive[newId][_incentive] = member;

        if (prevId < earliestValidQueMemberByIncentive[_incentive]) {
            QueMemberByIdAndIncentive[prevId][_incentive].headPointer = newId;
        }

        QueMemberByIdAndIncentive[nextId][_incentive].tailPointer = newId;

        unchecked { ++earliestValidQueMemberByIncentive[_incentive]; }
    }

    /**
     * @dev Updates the state after a user joins the queue.
     * Increases the proxy balance for the user and increments order counters.
     */
    function _updateJoinQueState(
        uint256 _amount,
        int256 _incentive
    )
        internal
    {
        _changeProxyAccounting(
            _increaseProxyBalance,
            msg.sender,
            _amount
        );

        totalActiveOrders++;
        activeOrderCountByIncentive[_incentive]++;
    }

    /**
     * @dev Validates the parameters for leaving the queue.
     * Ensures the queue member ID is valid and the incentive is allowed.
     */
    function _validateLeaveQue(
        uint256 _queMemberId,
        int256 _incentive
    )
        internal
        view
    {
        _requireValidMemberId(
            _queMemberId,
            _incentive
        );

        _requireIncentiveAllowed(
            _incentive
        );
    }

    /**
     * @dev Validates a partial order by ensuring the fill amount is valid.
     * Checks that the partial fill amount is greater than zero and less than the order amount.
     */
    function _validatePartialOrder(
        uint256 _orderId,
        uint256 _partialFillAmount,
        int256 _incentive
    )
        internal
        view
    {
        require(
            _partialFillAmount > 0,
            ZeroAmount()
        );

        require(
            _partialFillAmount < QueMemberByIdAndIncentive[_orderId][_incentive].amount,
            AmountTooHigh()
        );

        _requireIncentiveAllowed(
            _incentive
        );

        _requireValidMemberId(
            _orderId,
            _incentive
        );
    }

    /**
     * @dev Checks if there are no orders to process.
     * Returns true if both orders and partials arrays are empty.
     */
    function _hasNoOrdersToProcess(
        uint256[] memory _orders,
        uint256[] memory _partials
    )
        internal
        pure
        returns (bool)
    {
        return _orders.length == 0 && _partials.length == 0;
    }

    /**
     * @dev Validates the parameters for reducing a queue amount.
     * Ensures the reduction amount is greater than zero, queue member ID is valid, and incentive is allowed.
     */
    function _validateReduceAmount(
        uint256 _queMemberId,
        int256 _incentive,
        uint256 _reduceBy
    )
        internal
        view
    {
        require(
            _reduceBy > 0,
            ZeroAmount()
        );

        _requireValidMemberId(
            _queMemberId,
            _incentive
        );

        _requireIncentiveAllowed(
            _incentive
        );
    }

    /**
     * @dev Executes the reduction of a member's queue amount.
     * Decreases the proxy balance and updates the member's amount.
     * Ensures the remaining amount meets minimum deposit requirements.
     */
    function _executeReduction(
        QueMember storage _member,
        uint256 _reduceBy
    )
        internal
    {
        _changeProxyAccounting(
            _decreaseProxyBalance,
            msg.sender,
            _reduceBy
        );

        _member.amount -= _reduceBy;

        _requireMinDeposit(
            _member.amount
        );
    }

    /**
     * @dev Increases the proxy balance for a user.
     */
    function _increaseProxyBalance(
        address _user,
        uint256 _amount
    )
        internal
    {
        forwardVault.increaseProxyBalance(
            _user,
            _amount
        );
    }

    /**
     * @dev Decreases the proxy balance for a user.
     */
    function _decreaseProxyBalance(
        address _user,
        uint256 _amount
    )
        internal
    {
        forwardVault.decreaseProxyBalance(
            _user,
            _amount
        );
    }

    /**
     * @dev Changes the proxy accounting for a user.
     * @param _changeProxyBalance The function to use for changing the proxy balance.
     * @param _user The address of the user whose balance is being changed.
     * @param _amount The amount to change the balance by.
     */
    function _changeProxyAccounting(
        function (address,uint256) internal _changeProxyBalance,
        address _user,
        uint256 _amount
    )
        internal
    {
        forwardVault.setProxyBenefactor(
            _user
        );

        forwardVault.triggerAssignInterest(
            _user
        );

        _changeProxyBalance(
            _user,
            _amount
        );
    }

    /**
     * @dev Validates that a member can reduce their queue amount.
     * Ensures the caller is the member, the member has a positive amount, and the reduction is valid.
     */
    function _validateMemberCanReduce(
        QueMember storage _member,
        uint256 _reduceBy
    )
        internal
        view
    {
        require(
            _member.member == msg.sender,
            NotMember()
        );

        require(
            _reduceBy < _member.amount,
            AmountTooHigh()
        );
    }

    /**
     * @dev Validates that a member can leave the queue.
     * Ensures the caller is the member and the member has a positive amount.
     */
    function _validateMemberCanLeave(
        QueMember storage _member
    )
        internal
        view
    {
        require(
            _member.member == msg.sender,
            NotMember()
        );
    }

    /**
     * @dev Updates the current order pointer if the leaving member is the current order.
     * Moves the current order pointer to the next member in the queue.
     */
    function _updateCurrentOrderIfNeeded(
        uint256 _queMemberId,
        int256 _incentive,
        QueMember storage _member
    )
        internal
    {
        if (_queMemberId == currentOrderIdByIncentive[_incentive]) {
            currentOrderIdByIncentive[_incentive] = _member.headPointer;
        }
    }

    /**
     * @dev Updates the linked list pointers when removing a member.
     * Connects the previous member's head pointer to the next member's tail pointer.
     */
    function _updateLinkedListPointers(
        uint256 _queMemberId,
        QueMember storage _member,
        int256 _incentive
    )
        internal
    {
        if (_queMemberId == currentOrderIdByIncentive[_incentive]) {
            QueMemberByIdAndIncentive[_member.headPointer][_incentive].tailPointer = _member.headPointer;
            return;
        }

        QueMemberByIdAndIncentive[_member.tailPointer][_incentive].headPointer = _member.headPointer;
        QueMemberByIdAndIncentive[_member.headPointer][_incentive].tailPointer = _member.tailPointer;
    }

    /**
     * @dev Transfers vault tokens from this contract to the specified _to address.
     * Uses SafeERC20 for secure token transfers.
     */
    function _transferTokensOut(
        address _to,
        uint256 _amount
    )
        internal
    {
        IERC20(address(forwardVault)).safeTransfer(
            _to,
            _amount
        );
    }

    /**
     * @dev Re-usable incentive check.
     */
    function _requireIncentiveAllowed(
        int256 _incentive
    )
        internal
        view
    {
        require(
            incentiveAllowed[_incentive],
            IncentiveNotAllowed()
        );
    }

    /**
     * @dev Shared min-deposit guard.
     */
    function _requireMinDeposit(
        uint256 _amount
    )
        internal
        view
    {
        require(
            _amount >= minDepositAmount,
            AmountTooLow()
        );
    }

    /**
     * @dev Shared ID-range guard.
     */
    function _requireValidMemberId(
        uint256 _id,
        int256 _incentive
    )
        internal
        view
    {
        require(
            _id < earliestValidQueMemberByIncentive[_incentive],
            QueMemberIdTooHigh()
        );
    }

    /**
     * @dev Validates order processing parameters.
     * Ensures the order is ready to be processed and the incentive is allowed.
     */
    function _validateOrderProcessing(
        uint256 _queMemberId,
        int256 _incentive,
        uint256 _amount,
        bool _isFullFulfill
    )
        internal
        view
    {
        _requireValidMemberId(
            _queMemberId,
            _incentive
        );

        if (!_isFullFulfill) {
            require(
                _amount > 0,
                ZeroAmount()
            );

            require(
                _amount < QueMemberByIdAndIncentive[_queMemberId][_incentive].amount,
                AmountTooHigh()
            );
        }

        _requireIncentiveAllowed(
            _incentive
        );

        require(
            currentOrderIdByIncentive[_incentive] == _queMemberId,
            OrderNotReady()
        );
    }

    /**
     * @dev Executes the token transfers for order fulfillment.
     * Transfers discounted USD tokens to the member and vault tokens to the fulfiller.
     */
    function _executeTransfers(
        address _cashedMember,
        uint256 _amount,
        uint256 _discountedAmount
    )
        internal
    {
        usdToken.safeTransferFrom(
            msg.sender,
            _cashedMember,
            _discountedAmount
        );

        _transferTokensOut(
            msg.sender,
            _amount
        );
    }

    /**
     * @dev Initializes an array containing negative incentives in ascending order.
     */
    function _initializeNegativeIncentivesArray()
        internal
        pure
        returns (int16[8] memory)
    {
        return [
            int16(-100),  int16(-200),  int16(-300),  int16(-500),
            int16(-1000), int16(-1500), int16(-2500), int16(-5000)
        ];
    }

    /**
     * @dev Initializes an array containing all allowed incentives in descending order.
     * Returns a fixed-size array with all positive and negative incentive values.
     */
    function _initializeAllIncentivesArray()
        internal
        pure
        returns (int256[] memory)
    {
        int256[] memory allIncentives = new int256[](17);

        allIncentives[0] = 5000;
        allIncentives[1] = 2500;
        allIncentives[2] = 1500;
        allIncentives[3] = 1000;
        allIncentives[4] = 500;
        allIncentives[5] = 300;
        allIncentives[6] = 200;
        allIncentives[7] = 100;
        allIncentives[8] = 0;
        allIncentives[9] = -100;
        allIncentives[10] = -200;
        allIncentives[11] = -300;
        allIncentives[12] = -500;
        allIncentives[13] = -1000;
        allIncentives[14] = -1500;
        allIncentives[15] = -2500;
        allIncentives[16] = -5000;

        return allIncentives;
    }

    /**
     * @dev Initializes an array containing only positive incentives in descending order.
     * Returns a fixed-size array with positive incentive values for cost calculations.
     */
    function _initializePositiveIncentivesArray()
        internal
        pure
        returns (int16[9] memory)
    {
        return [
            int16(5000), int16(2500), int16(1500), int16(1000),
            int16(500), int16(300), int16(200), int16(100), int16(0)
        ];
    }

    /**
     * @dev Calculates the discount factor for a given incentive.
     * Applies the incentive as a percentage to the precision rate.
     * Returns the factor used for discount calculations.
     */
    function _calculateDiscountFactor(
        int256 _incentive
    )
        internal
        pure
        returns (uint256)
    {
        return _incentive >= 0
            ? PRECISION_RATE - uint256(_incentive)
            : PRECISION_RATE + uint256(-_incentive);
    }

    /**
     * @dev Checks if a queue entry is empty (has zero amount).
     * Returns true if the entry has no amount, false otherwise.
     */
    function _isEmptyOrder(
        QueMember storage _entry
    )
        internal
        view
        returns (bool)
    {
        return _entry.amount == 0;
    }

    /**
     * @dev Moves to the next order in the queue.
     * Updates the current order pointer and returns the new current and next IDs.
     */
    function _moveToNextOrder(
        QueMember storage _entry,
        int256 _incentive
    )
        internal
        view
        returns (
            uint256 newCurrent,
            uint256 newNextId
        )
    {
        newCurrent = _entry.headPointer;
        if (newCurrent == 0 || newCurrent >= earliestValidQueMemberByIncentive[_incentive]) {
            newNextId = earliestValidQueMemberByIncentive[_incentive];
            newCurrent = earliestValidQueMemberByIncentive[_incentive];
        } else {
            newNextId = newCurrent;
        }
    }

    /**
     * @dev Determines if plan traversal should continue based on remaining amount and limits.
     * Checks if there's still amount to process, orders to consider, and if limits are respected.
     */
    function _shouldContinuePlanTraversal(
        uint256 _amountLeft,
        PlanVars memory _v,
        int256 _incentive,
        uint256 _maxOrdersToConsider,
        uint256 _considerationLimit
    )
        internal
        view
        returns (bool)
    {
        return _amountLeft > 0 &&
            _v.current < earliestValidQueMemberByIncentive[_incentive] &&
            _v.fullIndex < _v.arraySize &&
            (_maxOrdersToConsider == 0 || _v.ordersConsidered < _considerationLimit);
    }

    /**
     * @dev Builds the final order arrays from temporary storage.
     * Creates properly sized arrays for full orders and partial orders.
     * Returns the final arrays ready for processing.
     */
    function _buildFinalOrderArrays(
        PlanVars memory _v,
        uint256[] memory _tempFull
    )
        internal
        pure
        returns (
            uint256[] memory fullOrderIds,
            uint256[] memory partialOrderIds
        )
    {
        fullOrderIds = new uint256[](_v.fullIndex);

        for (uint256 i; i < _v.fullIndex; i++) {
            fullOrderIds[i] = _tempFull[i];
        }

        if (_v.hasPartial) {
            partialOrderIds = new uint256[](1);
            partialOrderIds[0] = _v.partialId;
        } else {
            partialOrderIds = new uint256[](0);
        }
    }

    /**
     * @dev Initializes plan variables based on active count and maximum orders to consider.
     * Sets the array size for temporary storage based on the provided limits.
     */
    function _initializePlanVars(
        uint256 _activeCount,
        uint256 _maxOrdersToConsider
    )
        internal
        pure
        returns (
            PlanVars memory v
        )
    {
        if (_maxOrdersToConsider == 0) {
            v.arraySize = _activeCount;
        } else {
            v.arraySize = _activeCount < _maxOrdersToConsider
                ? _activeCount
                : _maxOrdersToConsider;
        }
    }

    /**
     * @dev Initializes solve variables for amount solving operations.
     * Sets up arrays for incentives, orders, and partials with appropriate sizes.
     */
    function _initializeSolveVars()
        internal
        view
        returns (
            SolveForAmountVars memory v
        )
    {
        v.incs = _initializePositiveIncentivesArray();
        v.tempIncentives = new int256[](totalActiveOrders);
        v.tempOrders = new uint256[](totalActiveOrders);
        v.tempPartials = new uint256[](totalActiveOrders);
    }

    /**
     * @dev Processes full orders for a specific incentive during amount solving.
     * Populates temporary arrays with order information and updates remaining amount.
     * Returns the new remaining amount after processing full orders.
     */
    function _processFullOrdersForIncentive(
        SolveForAmountVars memory _v,
        uint256[] memory _fullIds,
        int256 _incentive,
        uint256 _remainingAmount
    )
        internal
        view
        returns (
            uint256 newRemainingAmount
        )
    {
        newRemainingAmount = _remainingAmount;

        for (uint256 j; j < _fullIds.length; j++) {
            if (newRemainingAmount == 0) {
                break;
            }

            uint256 id = _fullIds[j];
            uint256 amt = QueMemberByIdAndIncentive[id][_incentive].amount;

            if (amt == 0 || amt > newRemainingAmount) {
                continue;
            }

            _v.tempIncentives[_v.orderIndex] = _incentive;
            _v.tempOrders[_v.orderIndex] = id;
            _v.orderIndex++;
            newRemainingAmount -= amt;
        }
    }

    /**
     * @dev Processes partial orders for a specific incentive during amount solving.
     * Adds partial order information to temporary arrays for later processing.
     */
    function _processPartialOrderForIncentive(
        SolveForAmountVars memory _v,
        uint256[] memory _partialIds,
        int256 _incentive
    )
        internal
        pure
    {
        if (_partialIds.length != 0) {
            _v.tempPartials[_v.partialIndex] = _partialIds[0];
            _v.tempIncentives[_v.orderIndex + _v.partialIndex] = _incentive;
            _v.partialIndex++;
        }
    }

    /**
     * @dev Builds the final solve results from temporary arrays.
     * Creates properly sized arrays for incentives, orders, and partials.
     * Returns the final arrays ready for order fulfillment.
     */
    function _buildSolveResults(
        SolveForAmountVars memory _v
    )
        internal
        pure
        returns (
            int256[] memory incentives,
            uint256[] memory orders,
            uint256[] memory partials
        )
    {
        incentives = new int256[](_v.orderIndex + _v.partialIndex);
        orders = new uint256[](_v.orderIndex);
        partials = new uint256[](_v.partialIndex);

        for (uint256 k; k < _v.orderIndex; k++) {
            incentives[k] = _v.tempIncentives[k];
            orders[k] = _v.tempOrders[k];
        }

        for (uint256 l; l < _v.partialIndex; l++) {
            incentives[_v.orderIndex + l] = _v.tempIncentives[_v.orderIndex + l];
            partials[l] = _v.tempPartials[l];
        }
    }

    /**
     * @dev Collects orders for a specific incentive and user.
     * Filters orders based on user address and active status.
     * Returns the new index after collecting orders.
     */
    function _collectOrdersForIncentive(
        int256 _currentIncentive,
        address _user,
        bool _checkUser,
        QueMember[] memory _tempOrders,
        int256[] memory _tempIncentives,
        uint256 _currentIndex
    )
        internal
        view
        returns (
            uint256 newIndex
        )
    {
        newIndex = _currentIndex;
        uint256 maxIdForIncentive = earliestValidQueMemberByIncentive[_currentIncentive];

        for (uint256 id = 0; id < maxIdForIncentive; id++) {
            QueMember storage member = QueMemberByIdAndIncentive[id][_currentIncentive];

            if (_shouldIncludeOrder(member, _user, _checkUser)) {
                _tempOrders[newIndex] = member;
                _tempIncentives[newIndex] = _currentIncentive;
                newIndex++;
            }
        }
    }

    /**
     * @dev Determines if an order should be included in collection results.
     * Checks user address and active status based on the checkUser flag.
     */
    function _shouldIncludeOrder(
        QueMember storage _member,
        address _user,
        bool _checkUser
    )
        internal
        view
        returns (bool)
    {
        return _checkUser
            ? (_member.member == _user && _member.amount > 0)
            : (_member.member != ZERO_ADDRESS && _member.amount > 0);
    }

    /**
     * @dev Copies temporary arrays to final arrays with actual length.
     * Creates properly sized arrays and copies data from temporary storage.
     */
    function _copyToFinalArrays(
        QueMember[] memory _tempOrders,
        int256[] memory _tempIncentives,
        uint256 _actualLength
    )
        internal
        pure
        returns (
            QueMember[] memory actualOrders,
            int256[] memory actualIncentives
        )
    {
        actualOrders = new QueMember[](_actualLength);
        actualIncentives = new int256[](_actualLength);

        for (uint256 j = 0; j < _actualLength; j++) {
            actualOrders[j] = _tempOrders[j];
            actualIncentives[j] = _tempIncentives[j];
        }
    }

    /**
     * @dev Collects all orders across all incentives for a specific user or all users.
     * Uses the checkUser flag to determine if filtering by user address is needed.
     */
    function _collectAllOrders(
        address _user,
        bool _checkUser
    )
        internal
        view
        returns (
            QueMember[] memory,
            int256[] memory
        )
    {
        int256[] memory allIncentives = _initializeAllIncentivesArray();
        QueMember[] memory tempOrders = new QueMember[](totalActiveOrders);
        int256[] memory tempIncentives = new int256[](totalActiveOrders);
        uint256 index = 0;

        for (uint256 i = 0; i < allIncentives.length; i++) {
            index = _collectOrdersForIncentive(
                allIncentives[i],
                _user,
                _checkUser,
                tempOrders,
                tempIncentives,
                index
            );
        }

        return _copyToFinalArrays(
            tempOrders,
            tempIncentives,
            index
        );
    }

    /**
     * @dev Calculates the total cost and tokens planned for full orders.
     * Sums up the discounted amounts and total tokens across all orders.
     */
    function _calculateFullOrdersCost(
        uint256[] memory _orders,
        int256[] memory _incentives
    )
        internal
        view
        returns (
            uint256 costInUsd,
            uint256 totalTokensPlanned
        )
    {
        for (uint256 i = 0; i < _orders.length; i++) {
            uint256 orderId = _orders[i];
            int256 incentive = _incentives[i];
            uint256 orderAmount = QueMemberByIdAndIncentive[orderId][incentive].amount;

            costInUsd += _predictDiscountedAmount(
                orderAmount,
                incentive
            );

            totalTokensPlanned += orderAmount;
        }
    }

    /**
     * @dev Predicts the discounted amount for a given base amount and incentive.
     * Applies the incentive factor to calculate the final discounted amount.
     */
    function _predictDiscountedAmount(
        uint256 _amount,
        int256 _incentive
    )
        internal
        pure
        returns (uint256)
    {
        uint256 factor = _calculateDiscountFactor(
            _incentive
        );

        return Math.mulDiv(
            _amount,
            factor,
            PRECISION_RATE
        );
    }

    /**
     * @dev Calculates the cost and tokens for partial orders.
     * Determines the remaining tokens needed and calculates the partial cost.
     */
    function _calculatePartialOrderCost(
        uint256[] memory _partials,
        int256[] memory _incentives,
        uint256 _ordersLength,
        uint256 _tokensToReceive,
        uint256 _totalTokensPlanned
    )
        internal
        pure
        returns (
            uint256 partialCost,
            uint256 partialTokens
        )
    {
        if (_partials.length > 0) {
            int256 partialIncentive = _incentives[_ordersLength];
            partialTokens = _tokensToReceive - _totalTokensPlanned;
            partialCost = _predictDiscountedAmount(
                partialTokens,
                partialIncentive
            );
        }
    }

    /**
     * @dev Processes an order for cost calculation.
     * Determines how many tokens can be acquired and how much USD will be spent.
     */
    function _processOrderForCost(
        QueMember storage _entry,
        int256 _incentive,
        uint256 _remainingUsd
    )
        internal
        view
        returns (
            uint256 tokensAcquired,
            uint256 usdSpent
        )
    {
        uint256 orderCost = _predictDiscountedAmount(
            _entry.amount,
            _incentive
        );

        if (_remainingUsd >= orderCost) {
            tokensAcquired = _entry.amount;
            usdSpent = orderCost;
        } else {
            uint256 factor = _calculateDiscountFactor(
                _incentive
            );

            tokensAcquired = Math.mulDiv(
                _remainingUsd,
                PRECISION_RATE,
                factor
            );

            usdSpent = _remainingUsd;
        }
    }

    /**
     * @dev Zero-outs an order after it leaves the book (leave or full-fill)
     * and always un-links it from the doubly-linked list so that
     * no live neighbour ever keeps a pointer to an empty "hole".
     *
     * - `_handleAccounting == true`  →  update proxy balances as well
     * - `_handleAccounting == false` →  proxy accounting was already
     *                                   handled earlier in the call
     *
     * Keeping the DLL tight guarantees that every iteration over
     * `headPointer`/`tailPointer` only visits live nodes, satisfying the
     * `invariant_linkedListsHealthy` check.
     */
    function _finalizeMemberRemoval(
        uint256 _queMemberId,
        QueMember storage _member,
        int256  _incentive,
        bool    _handleAccounting
    )
        internal
    {
        if (_handleAccounting) {
            _changeProxyAccounting(
                _decreaseProxyBalance,
                _member.member,
                _member.amount
            );
        }

        _updateLinkedListPointers(
            _queMemberId,
            _member,
            _incentive
        );

        delete QueMemberByIdAndIncentive[_queMemberId][_incentive];

        totalActiveOrders--;
        activeOrderCountByIncentive[_incentive]--;
    }
}
QueContractDeclarations.sol 203 lines
// SPDX-License-Identifier: -- WISE --
// @author: René Hochmuth

pragma solidity =0.8.29;

import "../../OwnableMaster.sol";
import "../IForwardVaultERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

/**
 * @title QueContractDeclarations
 * @dev Declaration contract containing all state variables, events, and error definitions for the queue system.
 *
 * This contract defines:
 * - All state variables for queue management
 * - Events for tracking queue operations
 * - Custom errors for gas-efficient reverts
 * - Data structures for queue members and planning
 * - Mappings for order tracking and incentive management
 *
 * The contract serves as the foundation for:
 * - Queue member creation and management
 * - Order tracking across multiple incentive levels
 * - Doubly-linked list implementation for efficient traversal
 * - Bulk order processing and optimization
 *
 * @notice This contract inherits from OwnableMaster and ReentrancyGuard to provide
 * the necessary security and access control for the queue system.
 */
contract QueContractDeclarations is OwnableMaster, ReentrancyGuard {

    error ZeroAmount();
    error NotMember();
    error MemberAlreadyLeft();
    error IncentiveMismatch();
    error QueMemberIdTooHigh();
    error OrderNotReady();
    error AmountTooHigh();
    error IncentiveNotAllowed();
    error AmountTooLow();
    error NotProxyBenefactor();
    error AmountReceivedTooLow();
    error AmountSpentTooHigh();
    error NoOrdersPresent();
    error NegativeIncentiveNotAllowed();

    event JoinQue(
        address indexed member,
        uint256 amount,
        int256 incentive,
        uint256 queMemberId
    );

    event LeaveQue(
        address indexed member,
        uint256 queMemberId,
        int256 incentive,
        uint256 amount
    );

    event ReduceQueAmount(
        address indexed member,
        uint256 queMemberId,
        int256 incentive,
        uint256 reduceBy
    );

    event OrderProcessed(
        address indexed fulfiller,
        address indexed member,
        uint256 queMemberId,
        int256 incentive,
        uint256 amount,
        bool isFullFulfill
    );

    struct QueMember {
        address member;
        uint256 amount;
        uint256 tailPointer;
        uint256 headPointer;
    }

    struct SolveForAmountVars {
        int16[9] incs;
        int256[] tempIncentives;
        uint256[] tempOrders;
        uint256[] tempPartials;
        uint256 orderIndex;
        uint256 partialIndex;
    }

    struct PlanVars {
        uint256 arraySize;
        uint256 partialId;
        uint256 fullIndex;
        uint256 current;
        uint256 ordersConsidered;
        bool hasPartial;
    }

    struct FulfillOrderBulkVars {
        int256[] incentives;
        uint256[] orders;
        uint256[] partials;
        uint256 partialAmount;
        uint256 minReceiveAmount;
        uint256 maxUsdToSpend;
    }

    mapping(uint256 => mapping(int256 => QueMember)) public QueMemberByIdAndIncentive;

    mapping(int256 => uint256) public earliestValidQueMemberByIncentive;

    mapping(int256 => uint256) public currentOrderIdByIncentive;

    mapping(int256 => bool) public incentiveAllowed;

    mapping(int256 => uint256) public activeOrderCountByIncentive;

    uint256 public totalActiveOrders;

    uint256 constant PRECISION_RATE = 10_000;

    uint256 constant MAX_ORDERS_TO_CONSIDER_LIMIT = 100;

    uint256 public minDepositAmount;

    IForwardVaultERC20 public immutable forwardVault;

    IERC20 public immutable usdToken;

    bool public negativeIncentivesNotAllowed;

    bytes4 public constant IERC20Decimals = bytes4(
        keccak256("decimals()")
    );

    constructor(
        address _forwardVault
    )
        OwnableMaster(
            msg.sender
        )
    {
        _initializeIncentives();

        forwardVault = IForwardVaultERC20(
            _forwardVault
        );

        usdToken = IERC20(
            forwardVault.USD_TOKEN()
        );

        (
            bool success,
            bytes memory data
        ) = address(usdToken).staticcall(
            abi.encodeWithSelector(
                IERC20Decimals
            )
        );

        require(
            success,
            "Failed to get decimals"
        );

        minDepositAmount = 50 * 10 ** abi.decode(
            data,
            (uint8)
        );
    }

    function _initializeIncentives()
        internal
    {
        int256[] memory allowed = new int256[](17);
        allowed[0] = 0;
        allowed[1] = 100;
        allowed[2] = 200;
        allowed[3] = 300;
        allowed[4] = 500;
        allowed[5] = 1000;
        allowed[6] = 1500;
        allowed[7] = 2500;
        allowed[8] = 5000;
        allowed[9] = -100;
        allowed[10] = -200;
        allowed[11] = -300;
        allowed[12] = -500;
        allowed[13] = -1000;
        allowed[14] = -1500;
        allowed[15] = -2500;
        allowed[16] = -5000;

        for (uint256 i = 0; i < allowed.length; i++) {
            incentiveAllowed[allowed[i]] = true;
        }
    }
}
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));
    }
}
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);
        }
    }
}
OwnableMaster.sol 114 lines
// SPDX-License-Identifier: -- WISE --

pragma solidity =0.8.29;

error NoValue();
error NotMaster();
error NotProposed();

contract OwnableMaster {

    address public master;
    address public proposedMaster;

    address internal constant ZERO_ADDRESS = address(0x0);

    modifier onlyProposed() {
        _onlyProposed();
        _;
    }

    function _onlyMaster()
        private
        view
    {
        if (msg.sender == master) {
            return;
        }

        revert NotMaster();
    }

    modifier onlyMaster() {
        _onlyMaster();
        _;
    }

    function _onlyProposed()
        private
        view
    {
        if (msg.sender == proposedMaster) {
            return;
        }

        revert NotProposed();
    }

    event MasterProposed(
        address indexed proposer,
        address indexed proposedMaster
    );

    event RenouncedOwnership(
        address indexed previousMaster
    );

    constructor(
        address _master
    ) {
        if (_master == ZERO_ADDRESS) {
            revert NoValue();
        }
        master = _master;
    }

    /**
     * @dev Allows to propose next master.
     * Must be claimed by proposer.
     */
    function proposeOwner(
        address _proposedOwner
    )
        external
        onlyMaster
    {
        if (_proposedOwner == ZERO_ADDRESS) {
            revert NoValue();
        }

        proposedMaster = _proposedOwner;

        emit MasterProposed(
            msg.sender,
            _proposedOwner
        );
    }

    /**
     * @dev Allows to claim master role.
     * Must be called by proposer.
     */
    function claimOwnership()
        external
        onlyProposed
    {
        master = msg.sender;
    }

    /**
     * @dev Removes master role.
     * No ability to be in control.
     */
    function renounceOwnership()
        external
        onlyMaster
    {
        master = ZERO_ADDRESS;
        proposedMaster = ZERO_ADDRESS;

        emit RenouncedOwnership(
            msg.sender
        );
    }
}
IForwardVaultERC20.sol 207 lines
// SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.29;

/**
 * @title IForwardVaultERC20
 * @dev Interface for the Forward Vault ERC20 contract.
 *
 * This interface defines the external functions that can be called on the ForwardVaultERC20 contract.
 * It includes functions for:
 * - Interest rate queries and management
 * - Deposit and withdrawal operations
 * - Interest claiming and compounding
 * - Token transfer operations
 * - Supply management (mint/burn)
 * - Proxy balance management
 * - Ownership management
 * 
 * @notice This interface is used by external contracts that need to interact with
 * the ForwardVaultERC20 contract, such as the QueContract.
 */
interface IForwardVaultERC20 {
    
    /**
     * @dev Returns the current interest rate in basis points.
     * @return The annual interest rate as a percentage (e.g., 500 = 5%)
     */
    function interestRate()
        external
        view
        returns (uint256);

    /**
     * @dev Allows users to deposit USD tokens into the vault.
     * @param _amount The amount of USD tokens to deposit
     */
    function deposit(
        uint256 _amount
    )
        external;

    /**
     * @dev Allows users to claim their earned interest.
     * @return The amount of interest claimed
     */
    function claimInterest()
        external
        returns (uint256);

    /**
     * @dev Returns the address of the USD token contract.
     * @return The address of the USD token (e.g., USDC, USDT)
     */
    function USD_TOKEN()
        external
        view
        returns (address);

    /**
     * @dev Transfers vault tokens to another address.
     * @param _to The address to transfer tokens to
     * @param _amount The amount of tokens to transfer
     * @return True if the transfer was successful
     */
    function transfer(
        address _to,
        uint256 _amount
    )
        external
        returns (bool);

    /**
     * @dev Transfers vault tokens from one address to another using allowance.
     * @param _from The address to transfer tokens from
     * @param _to The address to transfer tokens to
     * @param _amount The amount of tokens to transfer
     * @return True if the transfer was successful
     */
    function transferFrom(
        address _from,
        address _to,
        uint256 _amount
    )
        external
        returns (bool);

    /**
     * @dev Burns vault tokens from a specific address (owner only).
     * @param _user The address to burn tokens from
     * @param _amount The amount of tokens to burn
     */
    function burnSupply(
        address _user,
        uint256 _amount
    )
        external;

    /**
     * @dev Mints vault tokens to a specific address (owner only).
     * @param _user The address to mint tokens to
     * @param _amount The amount of tokens to mint
     */
    function mintSupply(
        address _user,
        uint256 _amount
    )
        external;

    /**
     * @dev Returns the total interest earned by a user (cashed + pending).
     * @param _user The address of the user
     * @return The total interest amount
     */
    function getTotalInterestUser(
        address _user
    )
        external
        view
        returns (uint256);

    /**
     * @dev Proposes a new owner for the contract.
     * @param _newOwner The address of the proposed new owner
     */
    function proposeOwner(
        address _newOwner
    )
        external;

    /**
     * @dev Claims ownership of the contract (must be the proposed owner).
     */
    function claimOwnership()
        external;

    /**
     * @dev Returns the current owner/master of the contract.
     * @return The address of the current owner
     */
    function master()
        external
        view
        returns (address);

    /**
     * @dev Sets whether interest should be transferred with tokens.
     * @param _transferInterestWithTokens True to transfer interest with tokens, false to keep with sender
     */
    function setTransferInterestWithTokens(
        bool _transferInterestWithTokens
    )
        external;

    /**
     * @dev Increases the proxy balance for a user (interest rate proxy only).
     * @param _proxyUser The address of the user whose balance is being increased
     * @param _amount The amount to increase the balance by
     */
    function increaseProxyBalance(
        address _proxyUser,
        uint256 _amount
    )
        external;

    /**
     * @dev Decreases the proxy balance for a user (interest rate proxy only).
     * @param _proxyUser The address of the user whose balance is being decreased
     * @param _amount The amount to decrease the balance by
     */
    function decreaseProxyBalance(
        address _proxyUser,
        uint256 _amount
    )
        external;

    /**
     * @dev Sets the current proxy benefactor (interest rate proxy only).
     * @param _proxyBeneFactor The address of the proxy benefactor
     */
    function setProxyBenefactor(
        address _proxyBeneFactor
    )
        external;

    /**
     * @dev Returns the current proxy benefactor address.
     * @return The address of the current proxy benefactor
     */
    function currentProxyBenefactor()
        external
        view
        returns (address);

    /**
     * @dev Triggers interest assignment for a user (interest rate proxy only).
     * @param _user The address of the user to assign interest to
     */
    function triggerAssignInterest(
        address _user
    )
        external;

    function totalDepositCap()
        external
        view
        returns (uint256);
}

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);
}
ReentrancyGuard.sol 77 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}
IERC20Permit.sol 60 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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.
 */
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].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

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

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}
Address.sol 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);
        }
    }
}

Read Contract

IERC20Decimals 0xedf83781 → bytes4
QueMemberByIdAndIncentive 0xe604994e → address, uint256, uint256, uint256
_solveForAmountWithIncentive 0xd4f1bc58 → uint256[], uint256[]
activeOrderCountByIncentive 0xd0262ed0 → uint256
currentOrderIdByIncentive 0x492d7b1c → uint256
earliestValidQueMemberByIncentive 0xdc4d5e95 → uint256
forwardVault 0x265b1a12 → address
getAllOrdersOverall 0xa2544c6d → tuple[], int256[]
getAllOrdersfromAddress 0x9c92ce8a → tuple[], int256[]
getFulfillmentPlanForIncentive 0x3ef17007 → uint256[], uint256[], uint256
incentiveAllowed 0x4dd38ae4 → bool
master 0xee97f7f3 → address
minDepositAmount 0x645006ca → uint256
negativeIncentivesNotAllowed 0x325eb232 → bool
predictCostForTokens 0xf57cca91 → uint256, uint256
predictDiscountedAmount 0x86074f04 → uint256
predictTokensForCost 0xbe3ac309 → uint256
proposedMaster 0xd3573a33 → address
solveForAmount 0x1d9eaedb → int256[], uint256[], uint256[]
solveForAmountWithIncentive 0x8e5a1a9f → uint256[], uint256[]
totalActiveOrders 0x535391a0 → uint256
usdToken 0xf897a22b → address

Write Contract 11 functions

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

changeMinDepositAmount 0x8caad7b5
uint256 _minDepositAmount
claimOwnership 0x4e71e0c8
No parameters
fulfillOrder 0xfd60e7b5
uint256 _queMemberId
int256 _incentive
returns: uint256, uint256
fulfillOrderBulk 0x3973b98f
int256[] _incentives
uint256[] _memberIds
uint256[] _partialId
uint256 _partialAmount
uint256 _minReceiveAmount
uint256 _maxUsdToSpend
returns: uint256, uint256
joinQue 0xc67dd640
uint256 _amount
int256 _incentive
returns: tuple, uint256
leaveQue 0x2c6a9b4f
uint256 _queMemberId
int256 _incentive
returns: tuple, uint256
partiallyFulfillOrder 0x37efa730
uint256 _queMemberId
int256 _incentive
uint256 _amount
returns: uint256, uint256
proposeOwner 0xb5ed298a
address _proposedOwner
reduceQueAmount 0xa8bff692
uint256 _queMemberId
int256 _incentive
uint256 _reduceBy
returns: tuple, uint256
renounceOwnership 0x715018a6
No parameters
setNegativeIncentivesNotAllowed 0x9d90ac8d
bool _negativeIncentivesNotAllowed

Recent Transactions

This address has 1 on-chain transactions, but only 1.4% of the chain is indexed. Transactions will appear as indexing progresses. View on Etherscan →