Address Contract Verified
Address
0x95A3832889B2c3455077991b834efA2d4fA3A945
Balance
0 ETH
Nonce
1
Code Size
18731 bytes
Creator
0x880AAE98...e703 at tx 0x7cd895ee...f47a80
Indexed Transactions
0
Contract Bytecode
18731 bytes
0x6080604052600436106103015760003560e01c80637dafa36411610191578063d73792a9116100e2578063ed8e84f311610090578063ed8e84f314610837578063edfb780114610857578063f1dc3cc91461086e578063f2fde38b1461088e578063f3de036214610786578063f446c1d0146108ae578063fc0c546a146108c3578063fee3f7f9146108e357600080fd5b8063d73792a914610786578063ddca3f431461079f578063e2e7d264146107b5578063e3103273146107d5578063e3698853146107f5578063e38244621461080a578063e5d9e9031461082057600080fd5b8063aaf5eb681161013f578063aaf5eb68146106dc578063ab5ac061146106f8578063b4b577ad1461070d578063bb7b8b8014610723578063bc063e1a14610738578063c661065714610751578063ca8ca1541461077157600080fd5b80637dafa364146105f657806385f11d1e146106165780638da5cb5b146106365780639a1d6ed3146106585780639c868ac01461066e578063a139c37014610688578063a6b0a718146106a857600080fd5b80634239b1c111610256578063556d6e9f11610204578063556d6e9f1461052357806358680d0b146105435780635b36389c146105595780635b41b908146105795780635b5a14671461058c57806362203d74146105ac5780636d4366b7146105cc578063715018a6146105e157600080fd5b80634239b1c11461046d5780634488ddf01461048d5780634903b0d1146104a35780634f12fe97146104c35780634fb08c5e146104d8578063524c3901146104f85780635409491a1461050d57600080fd5b80632a426896116102b35780632a426896146103b15780633046f972146103c757806330c54085146103dc578063392e53cd146103f157806339698415146104205780633c157e6414610437578063405e28f81461045757600080fd5b806306e9481c146103065780630b4c7e4d1461033057806314052288146103455780632081066c1461035b578063226840fb1461037157806325d2edf014610386578063293577501461039c575b600080fd5b34801561031257600080fd5b5061031d6201518081565b6040519081526020015b60405180910390f35b61034361033e3660046142b3565b6108f9565b005b34801561035157600080fd5b5061031d60115481565b34801561036757600080fd5b5061031d60105481565b34801561037d57600080fd5b50610343610f4b565b34801561039257600080fd5b5061031d6159d881565b3480156103a857600080fd5b5061031d600281565b3480156103bd57600080fd5b5061031d60155481565b3480156103d357600080fd5b50610343610faa565b3480156103e857600080fd5b5061034361100e565b3480156103fd57600080fd5b5060165461041090610100900460ff1681565b6040519015158152602001610327565b34801561042c57600080fd5b5061031d620f424081565b34801561044357600080fd5b506103436104523660046142de565b611192565b34801561046357600080fd5b5061031d60125481565b34801561047957600080fd5b50610343610488366004614317565b61139d565b34801561049957600080fd5b5061031d600c5481565b3480156104af57600080fd5b5061031d6104be3660046143b6565b6117d5565b3480156104cf57600080fd5b506103436117ec565b3480156104e457600080fd5b5061031d6104f33660046142de565b6118f1565b34801561050457600080fd5b50610343611909565b34801561051957600080fd5b5061031d600e5481565b34801561052f57600080fd5b5061031d61053e3660046143cf565b611a6f565b34801561054f57600080fd5b5061031d60135481565b34801561056557600080fd5b506103436105743660046143fb565b611bba565b610343610587366004614428565b611e3f565b34801561059857600080fd5b506103436105a73660046142de565b61220f565b3480156105b857600080fd5b5061031d6105c73660046143b6565b61238c565b3480156105d857600080fd5b5061031d601281565b3480156105ed57600080fd5b5061034361239c565b34801561060257600080fd5b5061031d6106113660046143b6565b6123d7565b34801561062257600080fd5b5061031d6106313660046143cf565b6123e7565b34801561064257600080fd5b5061064b6124c3565b604051610327919061445a565b34801561066457600080fd5b5061031d6108fc81565b34801561067a57600080fd5b506016546104109060ff1681565b34801561069457600080fd5b506103436106a33660046143b6565b6124d2565b3480156106b457600080fd5b5061064b7f000000000000000000000000880aae9893ab8b5117b11c7d1fb6fafad1cee70381565b3480156106e857600080fd5b5061031d670de0b6b3a764000081565b34801561070457600080fd5b5061031d600a81565b34801561071957600080fd5b5061031d600f5481565b34801561072f57600080fd5b5061031d61258b565b34801561074457600080fd5b5061031d64012a05f20081565b34801561075d57600080fd5b5061064b61076c3660046143b6565b612647565b34801561077d57600080fd5b50610343612667565b34801561079257600080fd5b5061031d6402540be40081565b3480156107ab57600080fd5b5061031d600a5481565b3480156107c157600080fd5b5061031d6107d03660046143b6565b6126ef565b3480156107e157600080fd5b506103436107f03660046142b3565b6127f0565b34801561080157600080fd5b50610343612dac565b34801561081657600080fd5b5061031d60145481565b34801561082c57600080fd5b5061031d6203f48081565b34801561084357600080fd5b5061031d61085236600461447c565b612e58565b34801561086357600080fd5b5061031d624f1a0081565b34801561087a57600080fd5b506103436108893660046143cf565b61301c565b34801561089a57600080fd5b506103436108a93660046144b4565b6131de565b3480156108ba57600080fd5b5061031d61327b565b3480156108cf57600080fd5b50600d5461064b906001600160a01b031681565b3480156108ef57600080fd5b5061031d600b5481565b600260015414156109255760405162461bcd60e51b815260040161091c906144cf565b60405180910390fd5b600260015560165460ff161561094d5760405162461bcd60e51b815260040161091c90614506565b600d54600160a01b900460ff1661097c57341561097c5760405162461bcd60e51b815260040161091c90614526565b610984614177565b60006109926001600261456b565b61099d906004614582565b6002600a546109ac9190614582565b6109b691906145a1565b600b5490915060006109c661328a565b90506000600d60009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a1d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a4191906145c3565b6040805180820191829052919250600091829160089060029082845b815481526020019060010190808311610a5d57505050505090506000831115610a8d57610a8a818561332b565b91505b6000604051806040016040528083600060028110610aad57610aad6145dc565b6020020151815260200183600160028110610aca57610aca6145dc565b60200201519052905060005b6002811015610bb65784610b555760008b8260028110610af857610af86145dc565b602002015111610b555760405162461bcd60e51b815260206004820152602260248201527f496e697469616c206465706f73697420726571756972657320616c6c20636f696044820152616e7360f01b606482015260840161091c565b8a8160028110610b6757610b676145dc565b6020020151838260028110610b7e57610b7e6145dc565b6020020151610b8d91906145f2565b828260028110610b9f57610b9f6145dc565b602002015280610bae8161460a565b915050610ad6565b506000610bc3828761332b565b9050838111610c145760405162461bcd60e51b815260206004820152601a60248201527f4431206d7573742062652067726561746572207468616e204430000000000000604482015260640161091c565b808515610dc25760005b6002811015610db057600086868360028110610c3c57610c3c6145dc565b6020020151610c4b9086614582565b610c5591906145a1565b90506000858360028110610c6b57610c6b6145dc565b6020020151821115610c9f57858360028110610c8957610c896145dc565b6020020151610c98908361456b565b9050610cc4565b81868460028110610cb257610cb26145dc565b6020020151610cc1919061456b565b90505b6402540be400610cd4828e614582565b610cde91906145a1565b8d8460028110610cf057610cf06145dc565b60200201526402540be4008b8e8560028110610d0e57610d0e6145dc565b6020020151610d1d9190614582565b610d2791906145a1565b868460028110610d3957610d396145dc565b6020020151610d48919061456b565b60088460028110610d5b57610d5b6145dc565b01558c8360028110610d6f57610d6f6145dc565b6020020151868460028110610d8657610d866145dc565b60200201818151610d97919061456b565b905250829150610da890508161460a565b915050610c1e565b50610dbb838861332b565b9050610dd1565b610dcf6008846002614195565b505b600086610ddf575081610e01565b85610dea818461456b565b610df49089614582565b610dfe91906145a1565b90505b8b811015610e215760405162461bcd60e51b815260040161091c90614625565b60005b6002811015610e895760008e8260028110610e4157610e416145dc565b60200201519050600060068360028110610e5d57610e5d6145dc565b01546001600160a01b03169050610e74818361333f565b50508080610e819061460a565b915050610e24565b50600d546040516340c10f1960e01b81526001600160a01b03909116906340c10f1990610ebc9033908590600401614653565b600060405180830381600087803b158015610ed657600080fd5b505af1158015610eea573d6000803e3d6000fd5b503392507f26f55a85081d24974e85c6c00045d0f0453991e95873f52bff0d21af4079a76891508f90508d86610f20868d6145f2565b604051610f30949392919061468f565b60405180910390a25050600180555050505050505050505050565b33610f546124c3565b6001600160a01b031614610f7a5760405162461bcd60e51b815260040161091c906146bc565b600060128190556040517f1b4883af197c705114490f8d84f9ce30bef6a6199f7b7b649e845577cf0769a19190a1565b33610fb36124c3565b6001600160a01b031614610fd95760405162461bcd60e51b815260040161091c906146bc565b6016805460ff191690556040517f061284ffa2814ace135f62907c78a7cff0f070efe7e6a0a42740ea1da2c8bdc890600090a1565b336110176124c3565b6001600160a01b03161461103d5760405162461bcd60e51b815260040161091c906146bc565b60005b600281101561118f57600073eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee60068360028110611073576110736145dc565b01546001600160a01b031614156110aa5760088260028110611097576110976145dc565b01546110a3904761456b565b905061114f565b600882600281106110bd576110bd6145dc565b0154600683600281106110d2576110d26145dc565b01546040516370a0823160e01b81526001600160a01b03909116906370a082319061110190309060040161445a565b602060405180830381865afa15801561111e573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061114291906145c3565b61114c919061456b565b90505b801561117c5761117c6006836002811061116b5761116b6145dc565b01546001600160a01b03168261339c565b50806111878161460a565b915050611040565b50565b3361119b6124c3565b6001600160a01b0316146111c15760405162461bcd60e51b815260040161091c906146bc565b620151806010546111d291906145f2565b4210156112135760405162461bcd60e51b815260206004820152600f60248201526e646576203a20746f6f206561726c7960881b604482015260640161091c565b61122062015180426145f2565b81101561123f5760405162461bcd60e51b815260040161091c906146f1565b600061124961328a565b905060008311801561125d5750620f424083105b6112b75760405162461bcd60e51b815260206004820152602560248201527f5f6675747572655f41206d757374206265206265747765656e203020616e64206044820152644d41585f4160d81b606482015260840161091c565b8083101580156112d157506112cd600a82614582565b8311155b806112f0575080831080156112f05750806112ed600a85614582565b10155b61133c5760405162461bcd60e51b815260206004820152601b60248201527f496c6c6567616c20706172616d65746572205f6675747572655f410000000000604482015260640161091c565b600e819055600f839055426010819055601183905560408051838152602081018690528082019290925260608201849052517fa2b71ec6df949300b59aab36b55e189697b750119dd349fcfa8c0f779e83c2549181900360800190a1505050565b601654610100900460ff16156113f55760405162461bcd60e51b815260206004820152601f60248201527f4f7065726174696f6e733a20416c726561647920696e697469616c697a656400604482015260640161091c565b336001600160a01b037f000000000000000000000000880aae9893ab8b5117b11c7d1fb6fafad1cee70316146114675760405162461bcd60e51b81526020600482015260176024820152764f7065726174696f6e733a204e6f7420666163746f727960481b604482015260640161091c565b620f42408511156114af5760405162461bcd60e51b81526020600482015260126024820152715f412065786365656473206d6178696d756d60701b604482015260640161091c565b64012a05f2008411156114fb5760405162461bcd60e51b81526020600482015260146024820152735f6665652065786365656473206d6178696d756d60601b604482015260640161091c565b6402540be4008311156115505760405162461bcd60e51b815260206004820152601a60248201527f5f61646d696e5f6665652065786365656473206d6178696d756d000000000000604482015260640161091c565b6016805461ff00191661010017905560005b600281101561177657600087826002811061157f5761157f6145dc565b60200201516001600160a01b031614156115ca5760405162461bcd60e51b815260206004820152600c60248201526b5a45524f204164647265737360a01b604482015260640161091c565b600073eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee8883600281106115f3576115f36145dc565b60200201516001600160a01b031614156116225750600d805460ff60a01b1916600160a01b17905560126116a0565b878260028110611634576116346145dc565b60200201516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611676573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061169a9190614721565b60ff1690505b60128111156116fd5760405162461bcd60e51b8152602060048201526024808201527f546865206d6178696d756d20646563696d616c2063616e6e6f742065786365656044820152630c84062760e31b606482015260840161091c565b61170881601261456b565b61171390600a614828565b60028360028110611726576117266145dc565b015560028281811061173a5761173a6145dc565b015461174e90670de0b6b3a7640000614582565b60048360028110611761576117616145dc565b0155508061176e8161460a565b915050611562565b5061178460068760026141cf565b50600e859055600f859055600a849055600b8390556117a6624f1a00426145f2565b601555600d80546001600160a01b0319166001600160a01b0383161790556117cd826131de565b505050505050565b600881600281106117e557600080fd5b0154905081565b336117f56124c3565b6001600160a01b03161461181b5760405162461bcd60e51b815260040161091c906146bc565b60125442101561183d5760405162461bcd60e51b815260040161091c906146f1565b60125461189b5760405162461bcd60e51b815260206004820152602660248201527f61646d696e5f616374696f6e735f646561646c696e652073686f756c64206e6f60448201526507420626520360d41b606482015260840161091c565b6000601255601354600a819055601454600b8190556040517fbe12859b636aed607d5230b2cc2711f68d70e51060e6cca1f575ef5d2fcc95d1926118e792908252602082015260400190565b60405180910390a1565b6000806118fe84846133df565b509150505b92915050565b336119126124c3565b6001600160a01b0316146119385760405162461bcd60e51b815260040161091c906146bc565b60005b6002811015611a435773eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6006826002811061196c5761196c6145dc565b01546001600160a01b03161415611998574760088260028110611991576119916145dc565b0155611a31565b600681600281106119ab576119ab6145dc565b01546040516370a0823160e01b81526001600160a01b03909116906370a08231906119da90309060040161445a565b602060405180830381865afa1580156119f7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a1b91906145c3565b60088260028110611a2e57611a2e6145dc565b01555b80611a3b8161460a565b91505061193b565b506040517f2c7203581ca666b8c5094c11c03f0b19b3750234a9d281bcbc88a260bcb006de90600090a1565b604080518082019182905260009182919060049060029082845b815481526020019060010190808311611a8957505050505090506000611aad6136df565b90506000670de0b6b3a7640000838860028110611acc57611acc6145dc565b6020020151611adb9087614582565b611ae591906145a1565b828860028110611af757611af76145dc565b6020020151611b0691906145f2565b90506000611b1688888486613798565b90506000848860028110611b2c57611b2c6145dc565b6020020151670de0b6b3a7640000600184878c60028110611b4f57611b4f6145dc565b6020020151611b5e919061456b565b611b68919061456b565b611b729190614582565b611b7c91906145a1565b905060006402540be40082600a54611b949190614582565b611b9e91906145a1565b9050611baa818361456b565b96505050505050505b9392505050565b60026001541415611bdd5760405162461bcd60e51b815260040161091c906144cf565b6002600155600d54604080516318160ddd60e01b815290516000926001600160a01b0316916318160ddd9160048083019260209291908290030181865afa158015611c2c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c5091906145c3565b9050611c5a614177565b611c62614177565b60005b6002811015611d87576000848760088460028110611c8557611c856145dc565b0154611c919190614582565b611c9b91906145a1565b9050858260028110611caf57611caf6145dc565b6020020151811015611d1c5760405162461bcd60e51b815260206004820152603060248201527f5769746864726177616c20726573756c74656420696e20666577657220636f6960448201526f1b9cc81d1a185b88195e1c1958dd195960821b606482015260840161091c565b8060088360028110611d3057611d306145dc565b016000828254611d40919061456b565b90915550819050848360028110611d5957611d596145dc565b6020020152611d746006836002811061116b5761116b6145dc565b5080611d7f8161460a565b915050611c65565b50600d5460405163079cc67960e41b81526001600160a01b03909116906379cc679090611dba9033908990600401614653565b600060405180830381600087803b158015611dd457600080fd5b505af1158015611de8573d6000803e3d6000fd5b503392507f7c363854ccf79623411f8995b362bce5eddff18c927edc6f5dbbb5e05819a82c915084905083611e1d898861456b565b604051611e2c93929190614834565b60405180910390a2505060018055505050565b60026001541415611e625760405162461bcd60e51b815260040161091c906144cf565b600260015560165460ff1615611e8a5760405162461bcd60e51b815260040161091c90614506565b600d54600160a01b900460ff16611eb9573415611eb95760405162461bcd60e51b815260040161091c90614526565b604080518082019182905260009160089060029082845b815481526020019060010190808311611ed057505050505090506000611ef582613994565b90506000670de0b6b3a764000060048860028110611f1557611f156145dc565b0154611f219087614582565b611f2b91906145a1565b828860028110611f3d57611f3d6145dc565b6020020151611f4c91906145f2565b90506000611f5c88888486613798565b90506000600182858a60028110611f7557611f756145dc565b6020020151611f84919061456b565b611f8e919061456b565b905060006402540be400600a5483611fa69190614582565b611fb091906145a1565b905060048960028110611fc557611fc56145dc565b0154670de0b6b3a7640000611fda838561456b565b611fe49190614582565b611fee91906145a1565b9150868210156120575760405162461bcd60e51b815260206004820152602e60248201527f45786368616e676520726573756c74656420696e20666577657220636f696e7360448201526d081d1a185b88195e1c1958dd195960921b606482015260840161091c565b60006402540be400600b548361206d9190614582565b61207791906145a1565b905060048a6002811061208c5761208c6145dc565b01546120a0670de0b6b3a764000083614582565b6120aa91906145a1565b905088878c600281106120bf576120bf6145dc565b60200201516120ce91906145f2565b60088c600281106120e1576120e16145dc565b01558083888c600281106120f7576120f76145dc565b6020020151612106919061456b565b612110919061456b565b60088b60028110612123576121236145dc565b0155600060068c6002811061213a5761213a6145dc565b01546001600160a01b0316905073eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81141561218757348a146121825760405162461bcd60e51b815260040161091c90614526565b61219c565b61219c6001600160a01b03821633308d613a51565b600060068c600281106121b1576121b16145dc565b01546001600160a01b031690506121c8818661339c565b604080518e8152602081018d90529081018d90526060810186905233907fb2e76ae99761dc136e598d4a629bb347eccb9532a5f8bbd72e18467c3c34cc9890608001610f30565b336122186124c3565b6001600160a01b03161461223e5760405162461bcd60e51b815260040161091c906146bc565b6012541561228e5760405162461bcd60e51b815260206004820181905260248201527f61646d696e5f616374696f6e735f646561646c696e65206d7573742062652030604482015260640161091c565b64012a05f2008211156122de5760405162461bcd60e51b81526020600482015260186024820152776465763a206665652065786365656473206d6178696d756d60401b604482015260640161091c565b6402540be4008111156123335760405162461bcd60e51b815260206004820152601e60248201527f6465763a2061646d696e206665652065786365656473206d6178696d756d0000604482015260640161091c565b6123406203f480426145f2565b60128190556013839055601482905560408051848152602081018490527f351fc5da2fbf480f2225debf3664a4bc90fa9923743aad58b4603f648e931fe0910160405180910390a25050565b600481600281106117e557600080fd5b336123a56124c3565b6001600160a01b0316146123cb5760405162461bcd60e51b815260040161091c906146bc565b6123d56000613ac2565b565b600281600281106117e557600080fd5b6000806123f26136df565b604080518082019182905291925060009190600290819081845b81548152602001906001019080831161240c5750505050509050600081876002811061243a5761243a6145dc565b60200201516124499086614582565b83886002811061245b5761245b6145dc565b602002015161246a91906145f2565b9050600061247a88888487613798565b90506000838860028110612490576124906145dc565b6020020151600183878b600281106124aa576124aa6145dc565b60200201516124b9919061456b565b611b72919061456b565b6000546001600160a01b031690565b336124db6124c3565b6001600160a01b0316146125015760405162461bcd60e51b815260040161091c906146bc565b6108fc811015801561251557506159d88111155b61254f5760405162461bcd60e51b815260206004820152600b60248201526a496c6c6567616c2067617360a81b604482015260640161091c565b600c8190556040518181527f320c5e7159406866d39a81979ca1c22276b644dfcfd52ee1f335ee467ad0ec67906020015b60405180910390a150565b6000806125a66125996136df565b6125a161328a565b613b12565b90506000600d60009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156125fd573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061262191906145c3565b905080612636670de0b6b3a764000084614582565b61264091906145a1565b9250505090565b6006816002811061265757600080fd5b01546001600160a01b0316905081565b336126706124c3565b6001600160a01b0316146126965760405162461bcd60e51b815260040161091c906146bc565b60006126a061328a565b600e819055600f81905542601081905560118190556040519192507f46e22fb3709ad289f62ce63d469248536dbc78d82b84a3d7e74ad606dc2019389161258091848252602082015260400190565b600073eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee60068360028110612719576127196145dc565b01546001600160a01b03161415612749576008826002811061273d5761273d6145dc565b0154611903904761456b565b6008826002811061275c5761275c6145dc565b015460068360028110612771576127716145dc565b01546040516370a0823160e01b81526001600160a01b03909116906370a08231906127a090309060040161445a565b602060405180830381865afa1580156127bd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127e191906145c3565b611903919061456b565b919050565b600260015414156128135760405162461bcd60e51b815260040161091c906144cf565b600260015560165460ff161561283b5760405162461bcd60e51b815260040161091c90614506565b600d54604080516318160ddd60e01b815290516000926001600160a01b0316916318160ddd9160048083019260209291908290030181865afa158015612885573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128a991906145c3565b9050600081116128f45760405162461bcd60e51b81526020600482015260166024820152756465763a207a65726f20746f74616c20737570706c7960501b604482015260640161091c565b60006129026001600261456b565b61290d906004614582565b6002600a5461291c9190614582565b61292691906145a1565b600b54909150600061293661328a565b60408051808201918290529192506000919060089060029082845b8154815260200190600101908083116129515750505050509050600060405180604001604052808360006002811061298b5761298b6145dc565b60200201518152602001836001600281106129a8576129a86145dc565b60200201519052905060006129bd838561332b565b905060005b6002811015612a1a578981600281106129dd576129dd6145dc565b60200201518382600281106129f4576129f46145dc565b60200201818151612a05919061456b565b90525080612a128161460a565b9150506129c2565b506000612a27838661332b565b9050612a31614177565b60005b6002811015612bc657600084878360028110612a5257612a526145dc565b6020020151612a619086614582565b612a6b91906145a1565b90506000868360028110612a8157612a816145dc565b6020020151821115612ab557868360028110612a9f57612a9f6145dc565b6020020151612aae908361456b565b9050612ada565b81878460028110612ac857612ac86145dc565b6020020151612ad7919061456b565b90505b6402540be400612aea828d614582565b612af491906145a1565b848460028110612b0657612b066145dc565b60200201526402540be4008a858560028110612b2457612b246145dc565b6020020151612b339190614582565b612b3d91906145a1565b878460028110612b4f57612b4f6145dc565b6020020151612b5e919061456b565b60088460028110612b7157612b716145dc565b0155838360028110612b8557612b856145dc565b6020020151878460028110612b9c57612b9c6145dc565b60200201818151612bad919061456b565b905250829150612bbe90508161460a565b915050612a34565b506000612bd3858861332b565b90506000848b612be3848361456b565b612bed9190614582565b612bf791906145a1565b905060008111612c555760405162461bcd60e51b815260206004820152602360248201527f746f6b656e5f616d6f756e74206d75737420626520677265617465722074686160448201526206e20360ec1b606482015260840161091c565b612c606001826145f2565b90508b811115612c825760405162461bcd60e51b815260040161091c90614625565b600d5460405163079cc67960e41b81526001600160a01b03909116906379cc679090612cb49033908590600401614653565b600060405180830381600087803b158015612cce57600080fd5b505af1158015612ce2573d6000803e3d6000fd5b5050505060005b6002811015612d605760008e8260028110612d0657612d066145dc565b60200201511115612d4e57612d4e60068260028110612d2757612d276145dc565b01546001600160a01b03168f8360028110612d4457612d446145dc565b602002015161339c565b80612d588161460a565b915050612ce9565b50612d6b818c61456b565b9a50336001600160a01b03167f2b5508378d7e19e0d5fa338419034731416c4f5b219a10379956f764317fd47e8e85878f604051610f30949392919061468f565b33612db56124c3565b6001600160a01b031614612ddb5760405162461bcd60e51b815260040161091c906146bc565b4260155411612e205760405162461bcd60e51b8152602060048201526011602482015270457863656564656420646561646c696e6560781b604482015260640161091c565b6016805460ff191660011790556040517fbe26733c2bf6ff3ea5ba8cfe744422bd49052ff9ed5685c9e81e6f9321dbaddd90600090a1565b604080518082019182905260009182919060089060029082845b815481526020019060010190808311612e7257505050505090506000612e9661328a565b90506000612ea4838361332b565b905060005b6002811015612f4a578515612efa57868160028110612eca57612eca6145dc565b6020020151848260028110612ee157612ee16145dc565b60200201818151612ef291906145f2565b905250612f38565b868160028110612f0c57612f0c6145dc565b6020020151848260028110612f2357612f236145dc565b60200201818151612f34919061456b565b9052505b80612f428161460a565b915050612ea9565b506000612f57848461332b565b90506000600d60009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612fae573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612fd291906145c3565b905060008715612fed57612fe6848461456b565b9050612ffa565b612ff7838561456b565b90505b836130058383614582565b61300f91906145a1565b9998505050505050505050565b6002600154141561303f5760405162461bcd60e51b815260040161091c906144cf565b600260015560165460ff16156130675760405162461bcd60e51b815260040161091c90614506565b60008061307485856133df565b91509150828210156130c35760405162461bcd60e51b8152602060048201526018602482015277139bdd08195b9bdd59da0818dbda5b9cc81c995b5bdd995960421b604482015260640161091c565b6402540be400600b54826130d79190614582565b6130e191906145a1565b6130eb90836145f2565b600885600281106130fe576130fe6145dc565b01600082825461310e919061456b565b9091555050600d5460405163079cc67960e41b81526001600160a01b03909116906379cc6790906131459033908990600401614653565b600060405180830381600087803b15801561315f57600080fd5b505af1158015613173573d6000803e3d6000fd5b5050505061319e6006856002811061318d5761318d6145dc565b01546001600160a01b03168361339c565b604080518581526020810187905290810183905233907f5ad056f2e28a8cec232015406b843668c1e36cda598127ec3b8c59b8c72773a090606001611e2c565b336131e76124c3565b6001600160a01b03161461320d5760405162461bcd60e51b815260040161091c906146bc565b6001600160a01b0381166132725760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b606482015260840161091c565b61118f81613ac2565b600061328561328a565b905090565b601154600f54600091904282111561190357600e54601054818311156132ef576132b4818561456b565b6132be824261456b565b6132c8848661456b565b6132d29190614582565b6132dc91906145a1565b6132e690836145f2565b94505050505090565b6132f9818561456b565b613303824261456b565b61330d858561456b565b6133179190614582565b61332191906145a1565b6132e6908361456b565b6000611bb361333984613994565b83613b12565b6001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415613387573481146133835760405162461bcd60e51b815260040161091c90614526565b5050565b6133836001600160a01b038316333084613a51565b6001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14156133cb576133833382613ca8565b6133836001600160a01b0383163383613d4a565b60008060006133ec61328a565b905060006133fc6001600261456b565b613407906004614582565b6002600a546134169190614582565b61342091906145a1565b604080518082019182905291925060009190600290819081845b81548152602001906001019080831161343a57505050505090506000600d60009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156134a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134cd91906145c3565b905060006134d96136df565b905060006134e78287613b12565b90506000836134f6838d614582565b61350091906145a1565b61350a908361456b565b905082600061351b898d8486613d69565b90506000878d60028110613531576135316145dc565b602002015182878f60028110613549576135496145dc565b6020020151613558919061456b565b61356291906145a1565b905060005b600281101561365e5760008e8214156135b9578387878a856002811061358f5761358f6145dc565b602002015161359e9190614582565b6135a891906145a1565b6135b2919061456b565b905061360a565b86868984600281106135cd576135cd6145dc565b60200201516135dc9190614582565b6135e691906145a1565b8883600281106135f8576135f86145dc565b6020020151613607919061456b565b90505b6402540be40061361a828d614582565b61362491906145a1565b858360028110613636576136366145dc565b60200201818151613647919061456b565b9052508190506136568161460a565b915050613567565b50600061366d8b8f8688613d69565b848f6002811061367f5761367f6145dc565b602002015161368e919061456b565b9050888e600281106136a2576136a26145dc565b60200201516136b260018361456b565b6136bc91906145a1565b9050806136c9818461456b565b9c509c5050505050505050505050509250929050565b6136e7614177565b60408051808201918290529060049060029082845b8154815260200190600101908083116136fc575050505050905060005b600281101561379457670de0b6b3a76400006008826002811061373e5761373e6145dc565b0154838360028110613752576137526145dc565b60200201516137619190614582565b61376b91906145a1565b82826002811061377d5761377d6145dc565b60200201528061378c8161460a565b915050613719565b5090565b60008385141580156137aa5750600285105b80156137b65750600284105b6137f65760405162461bcd60e51b815260206004820152601160248201527024b63632b3b0b6103830b930b6b2ba32b960791b604482015260640161091c565b600061380061328a565b9050600061380e8483613b12565b90508060008061381f600286614582565b90506000805b60028110156138a8578b81141561383e57899150613868565b8a811461386357888160028110613857576138576145dc565b60200201519150613868565b613896565b61387282856145f2565b935061387f600283614582565b6138898787614582565b61389391906145a1565b94505b806138a08161460a565b915050613825565b506138b4600283614582565b6138be8686614582565b6138c891906145a1565b935060006138d683876145a1565b6138e090856145f2565b9050600086815b60ff8110156139825781925088848360026139029190614582565b61390c91906145f2565b613916919061456b565b886139218480614582565b61392b91906145f2565b61393591906145a1565b91508282111561395a57600161394b848461456b565b1161395557613982565b613970565b6001613966838561456b565b1161397057613982565b8061397a8161460a565b9150506138e7565b509d9c50505050505050505050505050565b61399c614177565b60408051808201918290529060049060029082845b8154815260200190600101908083116139b1575050505050905060005b6002811015613a4b57670de0b6b3a76400008382600281106139f2576139f26145dc565b6020020151838360028110613a0957613a096145dc565b6020020151613a189190614582565b613a2291906145a1565b828260028110613a3457613a346145dc565b602002015280613a438161460a565b9150506139ce565b50919050565b6040516001600160a01b0380851660248301528316604482015260648101829052613abc9085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152613f24565b50505050565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b60008060005b6002811015613b5657848160028110613b3357613b336145dc565b6020020151613b4290836145f2565b915080613b4e8161460a565b915050613b18565b5080613b66576000915050611903565b60008181613b75600287614582565b905060005b60ff811015613c9c578260005b6002811015613bdb5760028a8260028110613ba457613ba46145dc565b6020020151613bb39190614582565b613bbd8684614582565b613bc791906145a1565b915080613bd38161460a565b915050613b87565b508394508060026001613bee91906145f2565b613bf89190614582565b84613c0460018661456b565b613c0e9190614582565b613c1891906145f2565b84613c24600284614582565b613c2e8987614582565b613c3891906145f2565b613c429190614582565b613c4c91906145a1565b935084841115613c72576001613c62868661456b565b11613c6d5750613c9c565b613c89565b6001613c7e858761456b565b11613c895750613c9c565b5080613c948161460a565b915050613b7a565b50909695505050505050565b6000826001600160a01b0316600c5483604051600060405180830381858888f193505050503d8060008114613cf9576040519150601f19603f3d011682016040523d82523d6000602084013e613cfe565b606091505b5050905080613d455760405162461bcd60e51b8152602060048201526013602482015272109390881d1c985b9cd9995c8819985a5b1959606a1b604482015260640161091c565b505050565b613d458363a9059cbb60e01b8484604051602401613a85929190614653565b600060028410613db25760405162461bcd60e51b81526020600482015260146024820152736465763a20692061626f7665204e5f434f494e5360601b604482015260640161091c565b81600080613dc1600289614582565b90506000805b6002811015613e3a57888114613df557878160028110613de957613de96145dc565b60200201519150613dfa565b613e28565b613e0482856145f2565b9350613e11600283614582565b613e1b8887614582565b613e2591906145a1565b94505b80613e328161460a565b915050613dc7565b50613e46600283614582565b613e508786614582565b613e5a91906145a1565b93506000613e6883886145a1565b613e7290856145f2565b9050600087815b60ff811015613f14578192508984836002613e949190614582565b613e9e91906145f2565b613ea8919061456b565b88613eb38480614582565b613ebd91906145f2565b613ec791906145a1565b915082821115613eec576001613edd848461456b565b11613ee757613f14565b613f02565b6001613ef8838561456b565b11613f0257613f14565b80613f0c8161460a565b915050613e79565b509b9a5050505050505050505050565b6000613f79826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316613ff69092919063ffffffff16565b805190915015613d455780806020019051810190613f97919061485d565b613d455760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161091c565b6060614005848460008561400d565b949350505050565b60608247101561406e5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b606482015260840161091c565b6001600160a01b0385163b6140c55760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161091c565b600080866001600160a01b031685876040516140e191906148a6565b60006040518083038185875af1925050503d806000811461411e576040519150601f19603f3d011682016040523d82523d6000602084013e614123565b606091505b509150915061413382828661413e565b979650505050505050565b6060831561414d575081611bb3565b82511561415d5782518084602001fd5b8160405162461bcd60e51b815260040161091c91906148c2565b60405180604001604052806002906020820280368337509192915050565b82600281019282156141c3579160200282015b828111156141c35782518255916020019190600101906141a8565b50613794929150614217565b82600281019282156141c3579160200282015b828111156141c357825182546001600160a01b0319166001600160a01b039091161782556020909201916001909101906141e2565b5b808211156137945760008155600101614218565b6040805190810167ffffffffffffffff8111828210171561425d57634e487b7160e01b600052604160045260246000fd5b60405290565b600082601f83011261427457600080fd5b61427c61422c565b80604084018581111561428e57600080fd5b845b818110156142a8578035845260209384019301614290565b509095945050505050565b600080606083850312156142c657600080fd5b6142d08484614263565b946040939093013593505050565b600080604083850312156142f157600080fd5b50508035926020909101359150565b80356001600160a01b03811681146127eb57600080fd5b60008060008060008060e0878903121561433057600080fd5b87601f88011261433f57600080fd5b61434761422c565b80604089018a81111561435957600080fd5b895b8181101561437a5761436c81614300565b84526020938401930161435b565b5090975035955050606087013593506080870135925061439c60a08801614300565b91506143aa60c08801614300565b90509295509295509295565b6000602082840312156143c857600080fd5b5035919050565b6000806000606084860312156143e457600080fd5b505081359360208301359350604090920135919050565b6000806060838503121561440e57600080fd5b8235915061441f8460208501614263565b90509250929050565b6000806000806080858703121561443e57600080fd5b5050823594602084013594506040840135936060013592509050565b6001600160a01b0391909116815260200190565b801515811461118f57600080fd5b6000806060838503121561448f57600080fd5b6144998484614263565b915060408301356144a98161446e565b809150509250929050565b6000602082840312156144c657600080fd5b611bb382614300565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b60208082526006908201526512da5b1b195960d21b604082015260600190565b602080825260159082015274496e636f6e73697374656e74207175616e7469747960581b604082015260600190565b634e487b7160e01b600052601160045260246000fd5b60008282101561457d5761457d614555565b500390565b600081600019048311821515161561459c5761459c614555565b500290565b6000826145be57634e487b7160e01b600052601260045260246000fd5b500490565b6000602082840312156145d557600080fd5b5051919050565b634e487b7160e01b600052603260045260246000fd5b6000821982111561460557614605614555565b500190565b600060001982141561461e5761461e614555565b5060010190565b602080825260149082015273536c697070616765207363726577656420796f7560601b604082015260600190565b6001600160a01b03929092168252602082015260400190565b8060005b6002811015613abc578151845260209384019390910190600101614670565b60c0810161469d828761466c565b6146aa604083018661466c565b608082019390935260a0015292915050565b6020808252818101527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604082015260600190565b6020808252601690820152756465763a20696e73756666696369656e742074696d6560501b604082015260600190565b60006020828403121561473357600080fd5b815160ff81168114611bb357600080fd5b600181815b8085111561477f57816000190482111561476557614765614555565b8085161561477257918102915b93841c9390800290614749565b509250929050565b60008261479657506001611903565b816147a357506000611903565b81600181146147b957600281146147c3576147df565b6001915050611903565b60ff8411156147d4576147d4614555565b50506001821b611903565b5060208310610133831016604e8410600b8410161715614802575081810a611903565b61480c8383614744565b806000190482111561482057614820614555565b029392505050565b6000611bb38383614787565b60a08101614842828661466c565b61484f604083018561466c565b826080830152949350505050565b60006020828403121561486f57600080fd5b8151611bb38161446e565b60005b8381101561489557818101518382015260200161487d565b83811115613abc5750506000910152565b600082516148b881846020870161487a565b9190910192915050565b60208152600082518060208401526148e181604085016020870161487a565b601f01601f1916919091016040019291505056fea26469706673582212201e3d34d8dc76b32f3f336a45636f73765a13007ed41ad27fa869d83470c6b59564736f6c634300080a0033
Verified Source Code Full Match
Compiler: v0.8.10+commit.fc410830
EVM: london
Optimization: Yes (100 runs)
PancakeStableSwapTwoPool.sol 774 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "@openzeppelin-4.5.0/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin-4.5.0/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin-4.5.0/contracts/security/ReentrancyGuard.sol";
import "./interfaces/IPancakeStableSwapLP.sol";
contract PancakeStableSwapTwoPool is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
uint256 public constant N_COINS = 2;
uint256 public constant MAX_DECIMAL = 18;
uint256 public constant FEE_DENOMINATOR = 1e10;
uint256 public constant PRECISION = 1e18;
uint256[N_COINS] public PRECISION_MUL;
uint256[N_COINS] public RATES;
uint256 public constant MAX_ADMIN_FEE = 1e10;
uint256 public constant MAX_FEE = 5e9;
uint256 public constant MAX_A = 1e6;
uint256 public constant MAX_A_CHANGE = 10;
uint256 public constant MIN_BNB_GAS = 2300;
uint256 public constant MAX_BNB_GAS = 23000;
uint256 public constant ADMIN_ACTIONS_DELAY = 3 days;
uint256 public constant MIN_RAMP_TIME = 1 days;
address[N_COINS] public coins;
uint256[N_COINS] public balances;
uint256 public fee; // fee * 1e10.
uint256 public admin_fee; // admin_fee * 1e10.
uint256 public bnb_gas = 4029; // transfer bnb gas.
IPancakeStableSwapLP public token;
address constant BNB_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
bool support_BNB;
uint256 public initial_A;
uint256 public future_A;
uint256 public initial_A_time;
uint256 public future_A_time;
uint256 public admin_actions_deadline;
uint256 public future_fee;
uint256 public future_admin_fee;
uint256 public kill_deadline;
uint256 public constant KILL_DEADLINE_DT = 2 * 30 days;
bool public is_killed;
address public immutable STABLESWAP_FACTORY;
bool public isInitialized;
event TokenExchange(
address indexed buyer,
uint256 sold_id,
uint256 tokens_sold,
uint256 bought_id,
uint256 tokens_bought
);
event AddLiquidity(
address indexed provider,
uint256[N_COINS] token_amounts,
uint256[N_COINS] fees,
uint256 invariant,
uint256 token_supply
);
event RemoveLiquidity(
address indexed provider,
uint256[N_COINS] token_amounts,
uint256[N_COINS] fees,
uint256 token_supply
);
event RemoveLiquidityOne(address indexed provider, uint256 index, uint256 token_amount, uint256 coin_amount);
event RemoveLiquidityImbalance(
address indexed provider,
uint256[N_COINS] token_amounts,
uint256[N_COINS] fees,
uint256 invariant,
uint256 token_supply
);
event CommitNewFee(uint256 indexed deadline, uint256 fee, uint256 admin_fee);
event NewFee(uint256 fee, uint256 admin_fee);
event RampA(uint256 old_A, uint256 new_A, uint256 initial_time, uint256 future_time);
event StopRampA(uint256 A, uint256 t);
event SetBNBGas(uint256 bnb_gas);
event RevertParameters();
event DonateAdminFees();
event Kill();
event Unkill();
/**
* @notice constructor
*/
constructor() {
STABLESWAP_FACTORY = msg.sender;
}
/**
* @notice initialize
* @param _coins: Addresses of ERC20 conracts of coins (c-tokens) involved
* @param _A: Amplification coefficient multiplied by n * (n - 1)
* @param _fee: Fee to charge for exchanges
* @param _admin_fee: Admin fee
* @param _owner: Owner
* @param _LP: LP address
*/
function initialize(
address[N_COINS] memory _coins,
uint256 _A,
uint256 _fee,
uint256 _admin_fee,
address _owner,
address _LP
) external {
require(!isInitialized, "Operations: Already initialized");
require(msg.sender == STABLESWAP_FACTORY, "Operations: Not factory");
require(_A <= MAX_A, "_A exceeds maximum");
require(_fee <= MAX_FEE, "_fee exceeds maximum");
require(_admin_fee <= MAX_ADMIN_FEE, "_admin_fee exceeds maximum");
isInitialized = true;
for (uint256 i = 0; i < N_COINS; i++) {
require(_coins[i] != address(0), "ZERO Address");
uint256 coinDecimal;
if (_coins[i] == BNB_ADDRESS) {
coinDecimal = 18;
support_BNB = true;
} else {
coinDecimal = IERC20Metadata(_coins[i]).decimals();
}
require(coinDecimal <= MAX_DECIMAL, "The maximum decimal cannot exceed 18");
//set PRECISION_MUL and RATES
PRECISION_MUL[i] = 10**(MAX_DECIMAL - coinDecimal);
RATES[i] = PRECISION * PRECISION_MUL[i];
}
coins = _coins;
initial_A = _A;
future_A = _A;
fee = _fee;
admin_fee = _admin_fee;
kill_deadline = block.timestamp + KILL_DEADLINE_DT;
token = IPancakeStableSwapLP(_LP);
transferOwnership(_owner);
}
function get_A() internal view returns (uint256) {
//Handle ramping A up or down
uint256 t1 = future_A_time;
uint256 A1 = future_A;
if (block.timestamp < t1) {
uint256 A0 = initial_A;
uint256 t0 = initial_A_time;
// Expressions in uint256 cannot have negative numbers, thus "if"
if (A1 > A0) {
return A0 + ((A1 - A0) * (block.timestamp - t0)) / (t1 - t0);
} else {
return A0 - ((A0 - A1) * (block.timestamp - t0)) / (t1 - t0);
}
} else {
// when t1 == 0 or block.timestamp >= t1
return A1;
}
}
function A() external view returns (uint256) {
return get_A();
}
function _xp() internal view returns (uint256[N_COINS] memory result) {
result = RATES;
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (result[i] * balances[i]) / PRECISION;
}
}
function _xp_mem(uint256[N_COINS] memory _balances) internal view returns (uint256[N_COINS] memory result) {
result = RATES;
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (result[i] * _balances[i]) / PRECISION;
}
}
function get_D(uint256[N_COINS] memory xp, uint256 amp) internal pure returns (uint256) {
uint256 S;
for (uint256 i = 0; i < N_COINS; i++) {
S += xp[i];
}
if (S == 0) {
return 0;
}
uint256 Dprev;
uint256 D = S;
uint256 Ann = amp * N_COINS;
for (uint256 j = 0; j < 255; j++) {
uint256 D_P = D;
for (uint256 k = 0; k < N_COINS; k++) {
D_P = (D_P * D) / (xp[k] * N_COINS); // If division by 0, this will be borked: only withdrawal will work. And that is good
}
Dprev = D;
D = ((Ann * S + D_P * N_COINS) * D) / ((Ann - 1) * D + (N_COINS + 1) * D_P);
// Equality with the precision of 1
if (D > Dprev) {
if (D - Dprev <= 1) {
break;
}
} else {
if (Dprev - D <= 1) {
break;
}
}
}
return D;
}
function get_D_mem(uint256[N_COINS] memory _balances, uint256 amp) internal view returns (uint256) {
return get_D(_xp_mem(_balances), amp);
}
function get_virtual_price() external view returns (uint256) {
/**
Returns portfolio virtual price (for calculating profit)
scaled up by 1e18
*/
uint256 D = get_D(_xp(), get_A());
/**
D is in the units similar to DAI (e.g. converted to precision 1e18)
When balanced, D = n * x_u - total virtual value of the portfolio
*/
uint256 token_supply = token.totalSupply();
return (D * PRECISION) / token_supply;
}
function calc_token_amount(uint256[N_COINS] memory amounts, bool deposit) external view returns (uint256) {
/**
Simplified method to calculate addition or reduction in token supply at
deposit or withdrawal without taking fees into account (but looking at
slippage).
Needed to prevent front-running, not for precise calculations!
*/
uint256[N_COINS] memory _balances = balances;
uint256 amp = get_A();
uint256 D0 = get_D_mem(_balances, amp);
for (uint256 i = 0; i < N_COINS; i++) {
if (deposit) {
_balances[i] += amounts[i];
} else {
_balances[i] -= amounts[i];
}
}
uint256 D1 = get_D_mem(_balances, amp);
uint256 token_amount = token.totalSupply();
uint256 difference;
if (deposit) {
difference = D1 - D0;
} else {
difference = D0 - D1;
}
return (difference * token_amount) / D0;
}
function add_liquidity(uint256[N_COINS] memory amounts, uint256 min_mint_amount) external payable nonReentrant {
//Amounts is amounts of c-tokens
require(!is_killed, "Killed");
if (!support_BNB) {
require(msg.value == 0, "Inconsistent quantity"); // Avoid sending BNB by mistake.
}
uint256[N_COINS] memory fees;
uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
uint256 _admin_fee = admin_fee;
uint256 amp = get_A();
uint256 token_supply = token.totalSupply();
//Initial invariant
uint256 D0;
uint256[N_COINS] memory old_balances = balances;
if (token_supply > 0) {
D0 = get_D_mem(old_balances, amp);
}
uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1]];
for (uint256 i = 0; i < N_COINS; i++) {
if (token_supply == 0) {
require(amounts[i] > 0, "Initial deposit requires all coins");
}
// balances store amounts of c-tokens
new_balances[i] = old_balances[i] + amounts[i];
}
// Invariant after change
uint256 D1 = get_D_mem(new_balances, amp);
require(D1 > D0, "D1 must be greater than D0");
// We need to recalculate the invariant accounting for fees
// to calculate fair user's share
uint256 D2 = D1;
if (token_supply > 0) {
// Only account for fees if we are not the first to deposit
for (uint256 i = 0; i < N_COINS; i++) {
uint256 ideal_balance = (D1 * old_balances[i]) / D0;
uint256 difference;
if (ideal_balance > new_balances[i]) {
difference = ideal_balance - new_balances[i];
} else {
difference = new_balances[i] - ideal_balance;
}
fees[i] = (_fee * difference) / FEE_DENOMINATOR;
balances[i] = new_balances[i] - ((fees[i] * _admin_fee) / FEE_DENOMINATOR);
new_balances[i] -= fees[i];
}
D2 = get_D_mem(new_balances, amp);
} else {
balances = new_balances;
}
// Calculate, how much pool tokens to mint
uint256 mint_amount;
if (token_supply == 0) {
mint_amount = D1; // Take the dust if there was any
} else {
mint_amount = (token_supply * (D2 - D0)) / D0;
}
require(mint_amount >= min_mint_amount, "Slippage screwed you");
// Take coins from the sender
for (uint256 i = 0; i < N_COINS; i++) {
uint256 amount = amounts[i];
address coin = coins[i];
transfer_in(coin, amount);
}
// Mint pool tokens
token.mint(msg.sender, mint_amount);
emit AddLiquidity(msg.sender, amounts, fees, D1, token_supply + mint_amount);
}
function get_y(
uint256 i,
uint256 j,
uint256 x,
uint256[N_COINS] memory xp_
) internal view returns (uint256) {
// x in the input is converted to the same price/precision
require((i != j) && (i < N_COINS) && (j < N_COINS), "Illegal parameter");
uint256 amp = get_A();
uint256 D = get_D(xp_, amp);
uint256 c = D;
uint256 S_;
uint256 Ann = amp * N_COINS;
uint256 _x;
for (uint256 k = 0; k < N_COINS; k++) {
if (k == i) {
_x = x;
} else if (k != j) {
_x = xp_[k];
} else {
continue;
}
S_ += _x;
c = (c * D) / (_x * N_COINS);
}
c = (c * D) / (Ann * N_COINS);
uint256 b = S_ + D / Ann; // - D
uint256 y_prev;
uint256 y = D;
for (uint256 m = 0; m < 255; m++) {
y_prev = y;
y = (y * y + c) / (2 * y + b - D);
// Equality with the precision of 1
if (y > y_prev) {
if (y - y_prev <= 1) {
break;
}
} else {
if (y_prev - y <= 1) {
break;
}
}
}
return y;
}
function get_dy(
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256) {
// dx and dy in c-units
uint256[N_COINS] memory rates = RATES;
uint256[N_COINS] memory xp = _xp();
uint256 x = xp[i] + ((dx * rates[i]) / PRECISION);
uint256 y = get_y(i, j, x, xp);
uint256 dy = ((xp[j] - y - 1) * PRECISION) / rates[j];
uint256 _fee = (fee * dy) / FEE_DENOMINATOR;
return dy - _fee;
}
function get_dy_underlying(
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256) {
// dx and dy in underlying units
uint256[N_COINS] memory xp = _xp();
uint256[N_COINS] memory precisions = PRECISION_MUL;
uint256 x = xp[i] + dx * precisions[i];
uint256 y = get_y(i, j, x, xp);
uint256 dy = (xp[j] - y - 1) / precisions[j];
uint256 _fee = (fee * dy) / FEE_DENOMINATOR;
return dy - _fee;
}
function exchange(
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy
) external payable nonReentrant {
require(!is_killed, "Killed");
if (!support_BNB) {
require(msg.value == 0, "Inconsistent quantity"); // Avoid sending BNB by mistake.
}
uint256[N_COINS] memory old_balances = balances;
uint256[N_COINS] memory xp = _xp_mem(old_balances);
uint256 x = xp[i] + (dx * RATES[i]) / PRECISION;
uint256 y = get_y(i, j, x, xp);
uint256 dy = xp[j] - y - 1; // -1 just in case there were some rounding errors
uint256 dy_fee = (dy * fee) / FEE_DENOMINATOR;
// Convert all to real units
dy = ((dy - dy_fee) * PRECISION) / RATES[j];
require(dy >= min_dy, "Exchange resulted in fewer coins than expected");
uint256 dy_admin_fee = (dy_fee * admin_fee) / FEE_DENOMINATOR;
dy_admin_fee = (dy_admin_fee * PRECISION) / RATES[j];
// Change balances exactly in same way as we change actual ERC20 coin amounts
balances[i] = old_balances[i] + dx;
// When rounding errors happen, we undercharge admin fee in favor of LP
balances[j] = old_balances[j] - dy - dy_admin_fee;
address iAddress = coins[i];
if (iAddress == BNB_ADDRESS) {
require(dx == msg.value, "Inconsistent quantity");
} else {
IERC20(iAddress).safeTransferFrom(msg.sender, address(this), dx);
}
address jAddress = coins[j];
transfer_out(jAddress, dy);
emit TokenExchange(msg.sender, i, dx, j, dy);
}
function remove_liquidity(uint256 _amount, uint256[N_COINS] memory min_amounts) external nonReentrant {
uint256 total_supply = token.totalSupply();
uint256[N_COINS] memory amounts;
uint256[N_COINS] memory fees; //Fees are unused but we've got them historically in event
for (uint256 i = 0; i < N_COINS; i++) {
uint256 value = (balances[i] * _amount) / total_supply;
require(value >= min_amounts[i], "Withdrawal resulted in fewer coins than expected");
balances[i] -= value;
amounts[i] = value;
transfer_out(coins[i], value);
}
token.burnFrom(msg.sender, _amount); // dev: insufficient funds
emit RemoveLiquidity(msg.sender, amounts, fees, total_supply - _amount);
}
function remove_liquidity_imbalance(uint256[N_COINS] memory amounts, uint256 max_burn_amount)
external
nonReentrant
{
require(!is_killed, "Killed");
uint256 token_supply = token.totalSupply();
require(token_supply > 0, "dev: zero total supply");
uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
uint256 _admin_fee = admin_fee;
uint256 amp = get_A();
uint256[N_COINS] memory old_balances = balances;
uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1]];
uint256 D0 = get_D_mem(old_balances, amp);
for (uint256 i = 0; i < N_COINS; i++) {
new_balances[i] -= amounts[i];
}
uint256 D1 = get_D_mem(new_balances, amp);
uint256[N_COINS] memory fees;
for (uint256 i = 0; i < N_COINS; i++) {
uint256 ideal_balance = (D1 * old_balances[i]) / D0;
uint256 difference;
if (ideal_balance > new_balances[i]) {
difference = ideal_balance - new_balances[i];
} else {
difference = new_balances[i] - ideal_balance;
}
fees[i] = (_fee * difference) / FEE_DENOMINATOR;
balances[i] = new_balances[i] - ((fees[i] * _admin_fee) / FEE_DENOMINATOR);
new_balances[i] -= fees[i];
}
uint256 D2 = get_D_mem(new_balances, amp);
uint256 token_amount = ((D0 - D2) * token_supply) / D0;
require(token_amount > 0, "token_amount must be greater than 0");
token_amount += 1; // In case of rounding errors - make it unfavorable for the "attacker"
require(token_amount <= max_burn_amount, "Slippage screwed you");
token.burnFrom(msg.sender, token_amount); // dev: insufficient funds
for (uint256 i = 0; i < N_COINS; i++) {
if (amounts[i] > 0) {
transfer_out(coins[i], amounts[i]);
}
}
token_supply -= token_amount;
emit RemoveLiquidityImbalance(msg.sender, amounts, fees, D1, token_supply);
}
function get_y_D(
uint256 A_,
uint256 i,
uint256[N_COINS] memory xp,
uint256 D
) internal pure returns (uint256) {
/**
Calculate x[i] if one reduces D from being calculated for xp to D
Done by solving quadratic equation iteratively.
x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)
x_1**2 + b*x_1 = c
x_1 = (x_1**2 + c) / (2*x_1 + b)
*/
// x in the input is converted to the same price/precision
require(i < N_COINS, "dev: i above N_COINS");
uint256 c = D;
uint256 S_;
uint256 Ann = A_ * N_COINS;
uint256 _x;
for (uint256 k = 0; k < N_COINS; k++) {
if (k != i) {
_x = xp[k];
} else {
continue;
}
S_ += _x;
c = (c * D) / (_x * N_COINS);
}
c = (c * D) / (Ann * N_COINS);
uint256 b = S_ + D / Ann;
uint256 y_prev;
uint256 y = D;
for (uint256 k = 0; k < 255; k++) {
y_prev = y;
y = (y * y + c) / (2 * y + b - D);
// Equality with the precision of 1
if (y > y_prev) {
if (y - y_prev <= 1) {
break;
}
} else {
if (y_prev - y <= 1) {
break;
}
}
}
return y;
}
function _calc_withdraw_one_coin(uint256 _token_amount, uint256 i) internal view returns (uint256, uint256) {
// First, need to calculate
// * Get current D
// * Solve Eqn against y_i for D - _token_amount
uint256 amp = get_A();
uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
uint256[N_COINS] memory precisions = PRECISION_MUL;
uint256 total_supply = token.totalSupply();
uint256[N_COINS] memory xp = _xp();
uint256 D0 = get_D(xp, amp);
uint256 D1 = D0 - (_token_amount * D0) / total_supply;
uint256[N_COINS] memory xp_reduced = xp;
uint256 new_y = get_y_D(amp, i, xp, D1);
uint256 dy_0 = (xp[i] - new_y) / precisions[i]; // w/o fees
for (uint256 k = 0; k < N_COINS; k++) {
uint256 dx_expected;
if (k == i) {
dx_expected = (xp[k] * D1) / D0 - new_y;
} else {
dx_expected = xp[k] - (xp[k] * D1) / D0;
}
xp_reduced[k] -= (_fee * dx_expected) / FEE_DENOMINATOR;
}
uint256 dy = xp_reduced[i] - get_y_D(amp, i, xp_reduced, D1);
dy = (dy - 1) / precisions[i]; // Withdraw less to account for rounding errors
return (dy, dy_0 - dy);
}
function calc_withdraw_one_coin(uint256 _token_amount, uint256 i) external view returns (uint256) {
(uint256 dy, ) = _calc_withdraw_one_coin(_token_amount, i);
return dy;
}
function remove_liquidity_one_coin(
uint256 _token_amount,
uint256 i,
uint256 min_amount
) external nonReentrant {
// Remove _amount of liquidity all in a form of coin i
require(!is_killed, "Killed");
(uint256 dy, uint256 dy_fee) = _calc_withdraw_one_coin(_token_amount, i);
require(dy >= min_amount, "Not enough coins removed");
balances[i] -= (dy + (dy_fee * admin_fee) / FEE_DENOMINATOR);
token.burnFrom(msg.sender, _token_amount); // dev: insufficient funds
transfer_out(coins[i], dy);
emit RemoveLiquidityOne(msg.sender, i, _token_amount, dy);
}
function transfer_out(address coin_address, uint256 value) internal {
if (coin_address == BNB_ADDRESS) {
_safeTransferBNB(msg.sender, value);
} else {
IERC20(coin_address).safeTransfer(msg.sender, value);
}
}
function transfer_in(address coin_address, uint256 value) internal {
if (coin_address == BNB_ADDRESS) {
require(value == msg.value, "Inconsistent quantity");
} else {
IERC20(coin_address).safeTransferFrom(msg.sender, address(this), value);
}
}
function _safeTransferBNB(address to, uint256 value) internal {
(bool success, ) = to.call{gas: bnb_gas, value: value}("");
require(success, "BNB transfer failed");
}
// Admin functions
function set_bnb_gas(uint256 _bnb_gas) external onlyOwner {
require(_bnb_gas >= MIN_BNB_GAS && _bnb_gas <= MAX_BNB_GAS, "Illegal gas");
bnb_gas = _bnb_gas;
emit SetBNBGas(_bnb_gas);
}
function ramp_A(uint256 _future_A, uint256 _future_time) external onlyOwner {
require(block.timestamp >= initial_A_time + MIN_RAMP_TIME, "dev : too early");
require(_future_time >= block.timestamp + MIN_RAMP_TIME, "dev: insufficient time");
uint256 _initial_A = get_A();
require(_future_A > 0 && _future_A < MAX_A, "_future_A must be between 0 and MAX_A");
require(
(_future_A >= _initial_A && _future_A <= _initial_A * MAX_A_CHANGE) ||
(_future_A < _initial_A && _future_A * MAX_A_CHANGE >= _initial_A),
"Illegal parameter _future_A"
);
initial_A = _initial_A;
future_A = _future_A;
initial_A_time = block.timestamp;
future_A_time = _future_time;
emit RampA(_initial_A, _future_A, block.timestamp, _future_time);
}
function stop_rampget_A() external onlyOwner {
uint256 current_A = get_A();
initial_A = current_A;
future_A = current_A;
initial_A_time = block.timestamp;
future_A_time = block.timestamp;
// now (block.timestamp < t1) is always False, so we return saved A
emit StopRampA(current_A, block.timestamp);
}
function commit_new_fee(uint256 new_fee, uint256 new_admin_fee) external onlyOwner {
require(admin_actions_deadline == 0, "admin_actions_deadline must be 0"); // dev: active action
require(new_fee <= MAX_FEE, "dev: fee exceeds maximum");
require(new_admin_fee <= MAX_ADMIN_FEE, "dev: admin fee exceeds maximum");
admin_actions_deadline = block.timestamp + ADMIN_ACTIONS_DELAY;
future_fee = new_fee;
future_admin_fee = new_admin_fee;
emit CommitNewFee(admin_actions_deadline, new_fee, new_admin_fee);
}
function apply_new_fee() external onlyOwner {
require(block.timestamp >= admin_actions_deadline, "dev: insufficient time");
require(admin_actions_deadline != 0, "admin_actions_deadline should not be 0");
admin_actions_deadline = 0;
fee = future_fee;
admin_fee = future_admin_fee;
emit NewFee(fee, admin_fee);
}
function revert_new_parameters() external onlyOwner {
admin_actions_deadline = 0;
emit RevertParameters();
}
function admin_balances(uint256 i) external view returns (uint256) {
if (coins[i] == BNB_ADDRESS) {
return address(this).balance - balances[i];
} else {
return IERC20(coins[i]).balanceOf(address(this)) - balances[i];
}
}
function withdraw_admin_fees() external onlyOwner {
for (uint256 i = 0; i < N_COINS; i++) {
uint256 value;
if (coins[i] == BNB_ADDRESS) {
value = address(this).balance - balances[i];
} else {
value = IERC20(coins[i]).balanceOf(address(this)) - balances[i];
}
if (value > 0) {
transfer_out(coins[i], value);
}
}
}
function donate_admin_fees() external onlyOwner {
for (uint256 i = 0; i < N_COINS; i++) {
if (coins[i] == BNB_ADDRESS) {
balances[i] = address(this).balance;
} else {
balances[i] = IERC20(coins[i]).balanceOf(address(this));
}
}
emit DonateAdminFees();
}
function kill_me() external onlyOwner {
require(kill_deadline > block.timestamp, "Exceeded deadline");
is_killed = true;
emit Kill();
}
function unkill_me() external onlyOwner {
is_killed = false;
emit Unkill();
}
}
IPancakeStableSwapLP.sol 15 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IPancakeStableSwapLP {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
function mint(address _to, uint256 _amount) external;
function burnFrom(address _to, uint256 _amount) external;
function setMinter(address _newMinter) external;
}
Address.sol 222 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.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
* ====
*
* [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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason 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 {
// 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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
Context.sol 24 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
Ownable.sol 76 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
IERC20.sol 82 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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);
/**
* @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);
}
ReentrancyGuard.sol 63 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
SafeERC20.sol 99 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.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;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
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));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
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");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @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");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
IERC20Metadata.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
MockToken.sol 22 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/token/ERC20/ERC20.sol";
contract MockToken is ERC20 {
constructor() ERC20("Binance USD", "BUSD") {
// _mint(msg.sender, 100000 ether);
}
function decimals() public pure override returns (uint8) {
return 18;
}
function mint(address _to, uint256 _amount) external {
_mint(_to, _amount);
}
function burnFrom(address _to, uint256 _amount) external {
_burn(_to, _amount);
}
}
PancakeStableSwapFactory.sol 211 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "./interfaces/IPancakeStableSwap.sol";
import "./interfaces/IPancakeStableSwapLP.sol";
import "./interfaces/IPancakeStableSwapDeployer.sol";
import "./interfaces/IPancakeStableSwapLPFactory.sol";
contract PancakeStableSwapFactory is Ownable {
struct StableSwapPairInfo {
address swapContract;
address token0;
address token1;
address LPContract;
}
struct StableSwapThreePoolPairInfo {
address swapContract;
address token0;
address token1;
address token2;
address LPContract;
}
mapping(address => mapping(address => mapping(address => StableSwapThreePoolPairInfo))) public stableSwapPairInfo;
// Query three pool pair infomation by two tokens.
mapping(address => mapping(address => StableSwapThreePoolPairInfo)) threePoolInfo;
mapping(uint256 => address) public swapPairContract;
IPancakeStableSwapLPFactory public immutable LPFactory;
IPancakeStableSwapDeployer public immutable SwapTwoPoolDeployer;
IPancakeStableSwapDeployer public immutable SwapThreePoolDeployer;
address constant ZEROADDRESS = address(0);
uint256 public pairLength;
event NewStableSwapPair(address indexed swapContract, address tokenA, address tokenB, address tokenC, address LP);
/**
* @notice constructor
* _LPFactory: LP factory
* _SwapTwoPoolDeployer: Swap two pool deployer
* _SwapThreePoolDeployer: Swap three pool deployer
*/
constructor(
IPancakeStableSwapLPFactory _LPFactory,
IPancakeStableSwapDeployer _SwapTwoPoolDeployer,
IPancakeStableSwapDeployer _SwapThreePoolDeployer
) {
LPFactory = _LPFactory;
SwapTwoPoolDeployer = _SwapTwoPoolDeployer;
SwapThreePoolDeployer = _SwapThreePoolDeployer;
}
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
}
function sortTokens(
address tokenA,
address tokenB,
address tokenC
)
internal
pure
returns (
address,
address,
address
)
{
require(tokenA != tokenB && tokenA != tokenC && tokenB != tokenC, "IDENTICAL_ADDRESSES");
address tmp;
if (tokenA > tokenB) {
tmp = tokenA;
tokenA = tokenB;
tokenB = tmp;
}
if (tokenB > tokenC) {
tmp = tokenB;
tokenB = tokenC;
tokenC = tmp;
if (tokenA > tokenB) {
tmp = tokenA;
tokenA = tokenB;
tokenB = tmp;
}
}
return (tokenA, tokenB, tokenC);
}
/**
* @notice createSwapPair
* @param _tokenA: Addresses of ERC20 conracts .
* @param _tokenB: Addresses of ERC20 conracts .
* @param _A: Amplification coefficient multiplied by n * (n - 1)
* @param _fee: Fee to charge for exchanges
* @param _admin_fee: Admin fee
*/
function createSwapPair(
address _tokenA,
address _tokenB,
uint256 _A,
uint256 _fee,
uint256 _admin_fee
) external onlyOwner {
require(_tokenA != ZEROADDRESS && _tokenB != ZEROADDRESS && _tokenA != _tokenB, "Illegal token");
(address t0, address t1) = sortTokens(_tokenA, _tokenB);
address LP = LPFactory.createSwapLP(t0, t1, ZEROADDRESS, address(this));
address swapContract = SwapTwoPoolDeployer.createSwapPair(t0, t1, _A, _fee, _admin_fee, msg.sender, LP);
IPancakeStableSwapLP(LP).setMinter(swapContract);
addPairInfoInternal(swapContract, t0, t1, ZEROADDRESS, LP);
}
/**
* @notice createThreePoolPair
* @param _tokenA: Addresses of ERC20 conracts .
* @param _tokenB: Addresses of ERC20 conracts .
* @param _tokenC: Addresses of ERC20 conracts .
* @param _A: Amplification coefficient multiplied by n * (n - 1)
* @param _fee: Fee to charge for exchanges
* @param _admin_fee: Admin fee
*/
function createThreePoolPair(
address _tokenA,
address _tokenB,
address _tokenC,
uint256 _A,
uint256 _fee,
uint256 _admin_fee
) external onlyOwner {
require(
_tokenA != ZEROADDRESS &&
_tokenB != ZEROADDRESS &&
_tokenC != ZEROADDRESS &&
_tokenA != _tokenB &&
_tokenA != _tokenC &&
_tokenB != _tokenC,
"Illegal token"
);
(address t0, address t1, address t2) = sortTokens(_tokenA, _tokenB, _tokenC);
address LP = LPFactory.createSwapLP(t0, t1, t2, address(this));
address swapContract = SwapThreePoolDeployer.createSwapPair(t0, t1, t2, _A, _fee, _admin_fee, msg.sender, LP);
IPancakeStableSwapLP(LP).setMinter(swapContract);
addPairInfoInternal(swapContract, t0, t1, t2, LP);
}
function addPairInfoInternal(
address _swapContract,
address _t0,
address _t1,
address _t2,
address _LP
) internal {
StableSwapThreePoolPairInfo storage info = stableSwapPairInfo[_t0][_t1][_t2];
info.swapContract = _swapContract;
info.token0 = _t0;
info.token1 = _t1;
info.token2 = _t2;
info.LPContract = _LP;
swapPairContract[pairLength] = _swapContract;
pairLength += 1;
if (_t2 != ZEROADDRESS) {
addThreePoolPairInfo(_t0, _t1, _t2, info);
}
emit NewStableSwapPair(_swapContract, _t0, _t1, _t2, _LP);
}
function addThreePoolPairInfo(
address _t0,
address _t1,
address _t2,
StableSwapThreePoolPairInfo memory info
) internal {
threePoolInfo[_t0][_t1] = info;
threePoolInfo[_t0][_t2] = info;
threePoolInfo[_t1][_t2] = info;
}
function addPairInfo(address _swapContract) external onlyOwner {
IPancakeStableSwap swap = IPancakeStableSwap(_swapContract);
uint256 N_COINS = swap.N_COINS();
if (N_COINS == 2) {
addPairInfoInternal(_swapContract, swap.coins(0), swap.coins(1), ZEROADDRESS, swap.token());
} else if (N_COINS == 3) {
addPairInfoInternal(_swapContract, swap.coins(0), swap.coins(1), swap.coins(2), swap.token());
}
}
function getPairInfo(address _tokenA, address _tokenB) external view returns (StableSwapPairInfo memory info) {
(address t0, address t1) = sortTokens(_tokenA, _tokenB);
StableSwapThreePoolPairInfo memory pairInfo = stableSwapPairInfo[t0][t1][ZEROADDRESS];
info.swapContract = pairInfo.swapContract;
info.token0 = pairInfo.token0;
info.token1 = pairInfo.token1;
info.LPContract = pairInfo.LPContract;
}
function getThreePoolPairInfo(address _tokenA, address _tokenB)
external
view
returns (StableSwapThreePoolPairInfo memory info)
{
(address t0, address t1) = sortTokens(_tokenA, _tokenB);
info = threePoolInfo[t0][t1];
}
}
IPancakeStableSwap.sol 41 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IPancakeStableSwap {
function token() external view returns (address);
function balances(uint256 i) external view returns (uint256);
function N_COINS() external view returns (uint256);
function RATES(uint256 i) external view returns (uint256);
function coins(uint256 i) external view returns (address);
function PRECISION_MUL(uint256 i) external view returns (uint256);
function fee() external view returns (uint256);
function admin_fee() external view returns (uint256);
function A() external view returns (uint256);
function get_D_mem(uint256[2] memory _balances, uint256 amp) external view returns (uint256);
function get_y(
uint256 i,
uint256 j,
uint256 x,
uint256[2] memory xp_
) external view returns (uint256);
function calc_withdraw_one_coin(uint256 _token_amount, uint256 i) external view returns (uint256);
function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external payable;
function remove_liquidity(uint256 _amount, uint256[2] memory min_amounts) external;
function remove_liquidity_imbalance(uint256[2] memory amounts, uint256 max_burn_amount) external;
function transferOwnership(address newOwner) external;
}
PancakeStableSwapWBNBHelper.sol 121 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin-4.5.0/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "../interfaces/IWBNB.sol";
import "../interfaces/IPancakeStableSwap.sol";
contract PancakeStableSwapWBNBHelper is Ownable {
using SafeERC20 for IERC20;
uint256 public constant N_COINS = 2;
IWBNB public immutable WBNB;
// Record whether approved for stable swap smart contract.
mapping(address => bool) isApproved;
mapping(address => bool) public isWhitelist;
error NotWBNBPair();
error NotWhitelist();
error InvalidNCOINS();
event UpdateWhitelist(address swap, bool status);
constructor(IWBNB _WBNB) {
WBNB = _WBNB;
}
function setWhiteList(address _swap, bool _status) external onlyOwner {
isWhitelist[_swap] = _status;
emit UpdateWhitelist(_swap, _status);
}
function initSwapPair(IPancakeStableSwap swap) internal {
address token0 = swap.coins(0);
address token1 = swap.coins(1);
address LPToken = swap.token();
IERC20(token0).safeApprove(address(swap), type(uint256).max);
IERC20(token1).safeApprove(address(swap), type(uint256).max);
IERC20(LPToken).safeApprove(address(swap), type(uint256).max);
isApproved[address(swap)] = true;
}
function add_liquidity(
IPancakeStableSwap swap,
uint256[N_COINS] memory amounts,
uint256 min_mint_amount
) external payable {
if (!isWhitelist[address(swap)]) revert NotWhitelist();
if (swap.N_COINS() != N_COINS) revert InvalidNCOINS();
if (!isApproved[address(swap)]) initSwapPair(swap);
address token0 = swap.coins(0);
address token1 = swap.coins(1);
uint256 WBNBIndex;
if (token0 == address(WBNB)) {
WBNBIndex = 0;
} else if (token1 == address(WBNB)) {
WBNBIndex = 1;
} else {
revert NotWBNBPair();
}
require(msg.value == amounts[WBNBIndex], "Inconsistent quantity");
WBNB.deposit{value: msg.value}();
if (WBNBIndex == 0) {
IERC20(token1).safeTransferFrom(msg.sender, address(this), amounts[1]);
} else {
IERC20(token0).safeTransferFrom(msg.sender, address(this), amounts[0]);
}
swap.add_liquidity(amounts, min_mint_amount);
address LPToken = swap.token();
uint256 mintedLPAmount = IERC20(LPToken).balanceOf(address(this));
IERC20(LPToken).safeTransfer(msg.sender, mintedLPAmount);
}
function remove_liquidity(
IPancakeStableSwap swap,
uint256 _amount,
uint256[N_COINS] memory min_amounts
) external {
if (!isWhitelist[address(swap)]) revert NotWhitelist();
if (swap.N_COINS() != N_COINS) revert InvalidNCOINS();
if (!isApproved[address(swap)]) initSwapPair(swap);
address token0 = swap.coins(0);
address token1 = swap.coins(1);
uint256 WBNBIndex;
if (token0 == address(WBNB)) {
WBNBIndex = 0;
} else if (token1 == address(WBNB)) {
WBNBIndex = 1;
} else {
revert NotWBNBPair();
}
address LPToken = swap.token();
IERC20(LPToken).safeTransferFrom(msg.sender, address(this), _amount);
swap.remove_liquidity(_amount, min_amounts);
uint256 WBNBBalance = WBNB.balanceOf(address(this));
WBNB.withdraw(WBNBBalance);
_safeTransferBNB(msg.sender, address(this).balance);
if (WBNBIndex == 0) {
uint256 token1Balance = IERC20(token1).balanceOf(address(this));
IERC20(token1).safeTransfer(msg.sender, token1Balance);
} else {
uint256 token0Balance = IERC20(token0).balanceOf(address(this));
IERC20(token0).safeTransfer(msg.sender, token0Balance);
}
}
function _safeTransferBNB(address to, uint256 value) internal {
(bool success, ) = to.call{gas: 2300, value: value}("");
require(success, "TransferHelper: BNB_TRANSFER_FAILED");
}
receive() external payable {
assert(msg.sender == address(WBNB)); // only accept BNB from the WBNB contract
}
}
IWBNB.sol 14 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IWBNB {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
function balanceOf(address account) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
}
PancakeStableSwapTwoPoolDeployer.sol 54 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "./PancakeStableSwapTwoPool.sol";
contract PancakeStableSwapTwoPoolDeployer is Ownable {
uint256 public constant N_COINS = 2;
/**
* @notice constructor
*/
constructor() {}
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
}
/**
* @notice createSwapPair
* @param _tokenA: Addresses of ERC20 conracts .
* @param _tokenB: Addresses of ERC20 conracts .
* @param _A: Amplification coefficient multiplied by n * (n - 1)
* @param _fee: Fee to charge for exchanges
* @param _admin_fee: Admin fee
* @param _admin: Admin
* @param _LP: LP
*/
function createSwapPair(
address _tokenA,
address _tokenB,
uint256 _A,
uint256 _fee,
uint256 _admin_fee,
address _admin,
address _LP
) external onlyOwner returns (address) {
require(_tokenA != address(0) && _tokenB != address(0) && _tokenA != _tokenB, "Illegal token");
(address t0, address t1) = sortTokens(_tokenA, _tokenB);
address[N_COINS] memory coins = [t0, t1];
// create swap contract
bytes memory bytecode = type(PancakeStableSwapTwoPool).creationCode;
bytes32 salt = keccak256(abi.encodePacked(t0, t1, msg.sender, block.timestamp, block.chainid));
address swapContract;
assembly {
swapContract := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
PancakeStableSwapTwoPool(swapContract).initialize(coins, _A, _fee, _admin_fee, _admin, _LP);
return swapContract;
}
}
PancakeStableSwapThreePool.sol 774 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "@openzeppelin-4.5.0/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin-4.5.0/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin-4.5.0/contracts/security/ReentrancyGuard.sol";
import "./interfaces/IPancakeStableSwapLP.sol";
contract PancakeStableSwapThreePool is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
uint256 public constant N_COINS = 3;
uint256 public constant MAX_DECIMAL = 18;
uint256 public constant FEE_DENOMINATOR = 1e10;
uint256 public constant PRECISION = 1e18;
uint256[N_COINS] public PRECISION_MUL;
uint256[N_COINS] public RATES;
uint256 public constant MAX_ADMIN_FEE = 1e10;
uint256 public constant MAX_FEE = 5e9;
uint256 public constant MAX_A = 1e6;
uint256 public constant MAX_A_CHANGE = 10;
uint256 public constant MIN_BNB_GAS = 2300;
uint256 public constant MAX_BNB_GAS = 23000;
uint256 public constant ADMIN_ACTIONS_DELAY = 3 days;
uint256 public constant MIN_RAMP_TIME = 1 days;
address[N_COINS] public coins;
uint256[N_COINS] public balances;
uint256 public fee; // fee * 1e10.
uint256 public admin_fee; // admin_fee * 1e10.
uint256 public bnb_gas = 4029; // transfer bnb gas.
IPancakeStableSwapLP public token;
address constant BNB_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
bool support_BNB;
uint256 public initial_A;
uint256 public future_A;
uint256 public initial_A_time;
uint256 public future_A_time;
uint256 public admin_actions_deadline;
uint256 public future_fee;
uint256 public future_admin_fee;
uint256 public kill_deadline;
uint256 public constant KILL_DEADLINE_DT = 2 * 30 days;
bool public is_killed;
address public immutable STABLESWAP_FACTORY;
bool public isInitialized;
event TokenExchange(
address indexed buyer,
uint256 sold_id,
uint256 tokens_sold,
uint256 bought_id,
uint256 tokens_bought
);
event AddLiquidity(
address indexed provider,
uint256[N_COINS] token_amounts,
uint256[N_COINS] fees,
uint256 invariant,
uint256 token_supply
);
event RemoveLiquidity(
address indexed provider,
uint256[N_COINS] token_amounts,
uint256[N_COINS] fees,
uint256 token_supply
);
event RemoveLiquidityOne(address indexed provider, uint256 index, uint256 token_amount, uint256 coin_amount);
event RemoveLiquidityImbalance(
address indexed provider,
uint256[N_COINS] token_amounts,
uint256[N_COINS] fees,
uint256 invariant,
uint256 token_supply
);
event CommitNewFee(uint256 indexed deadline, uint256 fee, uint256 admin_fee);
event NewFee(uint256 fee, uint256 admin_fee);
event RampA(uint256 old_A, uint256 new_A, uint256 initial_time, uint256 future_time);
event StopRampA(uint256 A, uint256 t);
event SetBNBGas(uint256 bnb_gas);
event RevertParameters();
event DonateAdminFees();
event Kill();
event Unkill();
/**
* @notice constructor
*/
constructor() {
STABLESWAP_FACTORY = msg.sender;
}
/**
* @notice initialize
* @param _coins: Addresses of ERC20 conracts of coins (c-tokens) involved
* @param _A: Amplification coefficient multiplied by n * (n - 1)
* @param _fee: Fee to charge for exchanges
* @param _admin_fee: Admin fee
* @param _owner: Owner
* @param _LP: LP address
*/
function initialize(
address[N_COINS] memory _coins,
uint256 _A,
uint256 _fee,
uint256 _admin_fee,
address _owner,
address _LP
) external {
require(!isInitialized, "Operations: Already initialized");
require(msg.sender == STABLESWAP_FACTORY, "Operations: Not factory");
require(_A <= MAX_A, "_A exceeds maximum");
require(_fee <= MAX_FEE, "_fee exceeds maximum");
require(_admin_fee <= MAX_ADMIN_FEE, "_admin_fee exceeds maximum");
isInitialized = true;
for (uint256 i = 0; i < N_COINS; i++) {
require(_coins[i] != address(0), "ZERO Address");
uint256 coinDecimal;
if (_coins[i] == BNB_ADDRESS) {
coinDecimal = 18;
support_BNB = true;
} else {
coinDecimal = IERC20Metadata(_coins[i]).decimals();
}
require(coinDecimal <= MAX_DECIMAL, "The maximum decimal cannot exceed 18");
//set PRECISION_MUL and RATES
PRECISION_MUL[i] = 10**(MAX_DECIMAL - coinDecimal);
RATES[i] = PRECISION * PRECISION_MUL[i];
}
coins = _coins;
initial_A = _A;
future_A = _A;
fee = _fee;
admin_fee = _admin_fee;
kill_deadline = block.timestamp + KILL_DEADLINE_DT;
token = IPancakeStableSwapLP(_LP);
transferOwnership(_owner);
}
function get_A() internal view returns (uint256) {
//Handle ramping A up or down
uint256 t1 = future_A_time;
uint256 A1 = future_A;
if (block.timestamp < t1) {
uint256 A0 = initial_A;
uint256 t0 = initial_A_time;
// Expressions in uint256 cannot have negative numbers, thus "if"
if (A1 > A0) {
return A0 + ((A1 - A0) * (block.timestamp - t0)) / (t1 - t0);
} else {
return A0 - ((A0 - A1) * (block.timestamp - t0)) / (t1 - t0);
}
} else {
// when t1 == 0 or block.timestamp >= t1
return A1;
}
}
function A() external view returns (uint256) {
return get_A();
}
function _xp() internal view returns (uint256[N_COINS] memory result) {
result = RATES;
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (result[i] * balances[i]) / PRECISION;
}
}
function _xp_mem(uint256[N_COINS] memory _balances) internal view returns (uint256[N_COINS] memory result) {
result = RATES;
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (result[i] * _balances[i]) / PRECISION;
}
}
function get_D(uint256[N_COINS] memory xp, uint256 amp) internal pure returns (uint256) {
uint256 S;
for (uint256 i = 0; i < N_COINS; i++) {
S += xp[i];
}
if (S == 0) {
return 0;
}
uint256 Dprev;
uint256 D = S;
uint256 Ann = amp * N_COINS;
for (uint256 j = 0; j < 255; j++) {
uint256 D_P = D;
for (uint256 k = 0; k < N_COINS; k++) {
D_P = (D_P * D) / (xp[k] * N_COINS); // If division by 0, this will be borked: only withdrawal will work. And that is good
}
Dprev = D;
D = ((Ann * S + D_P * N_COINS) * D) / ((Ann - 1) * D + (N_COINS + 1) * D_P);
// Equality with the precision of 1
if (D > Dprev) {
if (D - Dprev <= 1) {
break;
}
} else {
if (Dprev - D <= 1) {
break;
}
}
}
return D;
}
function get_D_mem(uint256[N_COINS] memory _balances, uint256 amp) internal view returns (uint256) {
return get_D(_xp_mem(_balances), amp);
}
function get_virtual_price() external view returns (uint256) {
/**
Returns portfolio virtual price (for calculating profit)
scaled up by 1e18
*/
uint256 D = get_D(_xp(), get_A());
/**
D is in the units similar to DAI (e.g. converted to precision 1e18)
When balanced, D = n * x_u - total virtual value of the portfolio
*/
uint256 token_supply = token.totalSupply();
return (D * PRECISION) / token_supply;
}
function calc_token_amount(uint256[N_COINS] memory amounts, bool deposit) external view returns (uint256) {
/**
Simplified method to calculate addition or reduction in token supply at
deposit or withdrawal without taking fees into account (but looking at
slippage).
Needed to prevent front-running, not for precise calculations!
*/
uint256[N_COINS] memory _balances = balances;
uint256 amp = get_A();
uint256 D0 = get_D_mem(_balances, amp);
for (uint256 i = 0; i < N_COINS; i++) {
if (deposit) {
_balances[i] += amounts[i];
} else {
_balances[i] -= amounts[i];
}
}
uint256 D1 = get_D_mem(_balances, amp);
uint256 token_amount = token.totalSupply();
uint256 difference;
if (deposit) {
difference = D1 - D0;
} else {
difference = D0 - D1;
}
return (difference * token_amount) / D0;
}
function add_liquidity(uint256[N_COINS] memory amounts, uint256 min_mint_amount) external payable nonReentrant {
//Amounts is amounts of c-tokens
require(!is_killed, "Killed");
if (!support_BNB) {
require(msg.value == 0, "Inconsistent quantity"); // Avoid sending BNB by mistake.
}
uint256[N_COINS] memory fees;
uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
uint256 _admin_fee = admin_fee;
uint256 amp = get_A();
uint256 token_supply = token.totalSupply();
//Initial invariant
uint256 D0;
uint256[N_COINS] memory old_balances = balances;
if (token_supply > 0) {
D0 = get_D_mem(old_balances, amp);
}
uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1], old_balances[2]];
for (uint256 i = 0; i < N_COINS; i++) {
if (token_supply == 0) {
require(amounts[i] > 0, "Initial deposit requires all coins");
}
// balances store amounts of c-tokens
new_balances[i] = old_balances[i] + amounts[i];
}
// Invariant after change
uint256 D1 = get_D_mem(new_balances, amp);
require(D1 > D0, "D1 must be greater than D0");
// We need to recalculate the invariant accounting for fees
// to calculate fair user's share
uint256 D2 = D1;
if (token_supply > 0) {
// Only account for fees if we are not the first to deposit
for (uint256 i = 0; i < N_COINS; i++) {
uint256 ideal_balance = (D1 * old_balances[i]) / D0;
uint256 difference;
if (ideal_balance > new_balances[i]) {
difference = ideal_balance - new_balances[i];
} else {
difference = new_balances[i] - ideal_balance;
}
fees[i] = (_fee * difference) / FEE_DENOMINATOR;
balances[i] = new_balances[i] - ((fees[i] * _admin_fee) / FEE_DENOMINATOR);
new_balances[i] -= fees[i];
}
D2 = get_D_mem(new_balances, amp);
} else {
balances = new_balances;
}
// Calculate, how much pool tokens to mint
uint256 mint_amount;
if (token_supply == 0) {
mint_amount = D1; // Take the dust if there was any
} else {
mint_amount = (token_supply * (D2 - D0)) / D0;
}
require(mint_amount >= min_mint_amount, "Slippage screwed you");
// Take coins from the sender
for (uint256 i = 0; i < N_COINS; i++) {
uint256 amount = amounts[i];
address coin = coins[i];
transfer_in(coin, amount);
}
// Mint pool tokens
token.mint(msg.sender, mint_amount);
emit AddLiquidity(msg.sender, amounts, fees, D1, token_supply + mint_amount);
}
function get_y(
uint256 i,
uint256 j,
uint256 x,
uint256[N_COINS] memory xp_
) internal view returns (uint256) {
// x in the input is converted to the same price/precision
require((i != j) && (i < N_COINS) && (j < N_COINS), "Illegal parameter");
uint256 amp = get_A();
uint256 D = get_D(xp_, amp);
uint256 c = D;
uint256 S_;
uint256 Ann = amp * N_COINS;
uint256 _x;
for (uint256 k = 0; k < N_COINS; k++) {
if (k == i) {
_x = x;
} else if (k != j) {
_x = xp_[k];
} else {
continue;
}
S_ += _x;
c = (c * D) / (_x * N_COINS);
}
c = (c * D) / (Ann * N_COINS);
uint256 b = S_ + D / Ann; // - D
uint256 y_prev;
uint256 y = D;
for (uint256 m = 0; m < 255; m++) {
y_prev = y;
y = (y * y + c) / (2 * y + b - D);
// Equality with the precision of 1
if (y > y_prev) {
if (y - y_prev <= 1) {
break;
}
} else {
if (y_prev - y <= 1) {
break;
}
}
}
return y;
}
function get_dy(
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256) {
// dx and dy in c-units
uint256[N_COINS] memory rates = RATES;
uint256[N_COINS] memory xp = _xp();
uint256 x = xp[i] + ((dx * rates[i]) / PRECISION);
uint256 y = get_y(i, j, x, xp);
uint256 dy = ((xp[j] - y - 1) * PRECISION) / rates[j];
uint256 _fee = (fee * dy) / FEE_DENOMINATOR;
return dy - _fee;
}
function get_dy_underlying(
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256) {
// dx and dy in underlying units
uint256[N_COINS] memory xp = _xp();
uint256[N_COINS] memory precisions = PRECISION_MUL;
uint256 x = xp[i] + dx * precisions[i];
uint256 y = get_y(i, j, x, xp);
uint256 dy = (xp[j] - y - 1) / precisions[j];
uint256 _fee = (fee * dy) / FEE_DENOMINATOR;
return dy - _fee;
}
function exchange(
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy
) external payable nonReentrant {
require(!is_killed, "Killed");
if (!support_BNB) {
require(msg.value == 0, "Inconsistent quantity"); // Avoid sending BNB by mistake.
}
uint256[N_COINS] memory old_balances = balances;
uint256[N_COINS] memory xp = _xp_mem(old_balances);
uint256 x = xp[i] + (dx * RATES[i]) / PRECISION;
uint256 y = get_y(i, j, x, xp);
uint256 dy = xp[j] - y - 1; // -1 just in case there were some rounding errors
uint256 dy_fee = (dy * fee) / FEE_DENOMINATOR;
// Convert all to real units
dy = ((dy - dy_fee) * PRECISION) / RATES[j];
require(dy >= min_dy, "Exchange resulted in fewer coins than expected");
uint256 dy_admin_fee = (dy_fee * admin_fee) / FEE_DENOMINATOR;
dy_admin_fee = (dy_admin_fee * PRECISION) / RATES[j];
// Change balances exactly in same way as we change actual ERC20 coin amounts
balances[i] = old_balances[i] + dx;
// When rounding errors happen, we undercharge admin fee in favor of LP
balances[j] = old_balances[j] - dy - dy_admin_fee;
address iAddress = coins[i];
if (iAddress == BNB_ADDRESS) {
require(dx == msg.value, "Inconsistent quantity");
} else {
IERC20(iAddress).safeTransferFrom(msg.sender, address(this), dx);
}
address jAddress = coins[j];
transfer_out(jAddress, dy);
emit TokenExchange(msg.sender, i, dx, j, dy);
}
function remove_liquidity(uint256 _amount, uint256[N_COINS] memory min_amounts) external nonReentrant {
uint256 total_supply = token.totalSupply();
uint256[N_COINS] memory amounts;
uint256[N_COINS] memory fees; //Fees are unused but we've got them historically in event
for (uint256 i = 0; i < N_COINS; i++) {
uint256 value = (balances[i] * _amount) / total_supply;
require(value >= min_amounts[i], "Withdrawal resulted in fewer coins than expected");
balances[i] -= value;
amounts[i] = value;
transfer_out(coins[i], value);
}
token.burnFrom(msg.sender, _amount); // dev: insufficient funds
emit RemoveLiquidity(msg.sender, amounts, fees, total_supply - _amount);
}
function remove_liquidity_imbalance(uint256[N_COINS] memory amounts, uint256 max_burn_amount)
external
nonReentrant
{
require(!is_killed, "Killed");
uint256 token_supply = token.totalSupply();
require(token_supply > 0, "dev: zero total supply");
uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
uint256 _admin_fee = admin_fee;
uint256 amp = get_A();
uint256[N_COINS] memory old_balances = balances;
uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1], old_balances[2]];
uint256 D0 = get_D_mem(old_balances, amp);
for (uint256 i = 0; i < N_COINS; i++) {
new_balances[i] -= amounts[i];
}
uint256 D1 = get_D_mem(new_balances, amp);
uint256[N_COINS] memory fees;
for (uint256 i = 0; i < N_COINS; i++) {
uint256 ideal_balance = (D1 * old_balances[i]) / D0;
uint256 difference;
if (ideal_balance > new_balances[i]) {
difference = ideal_balance - new_balances[i];
} else {
difference = new_balances[i] - ideal_balance;
}
fees[i] = (_fee * difference) / FEE_DENOMINATOR;
balances[i] = new_balances[i] - ((fees[i] * _admin_fee) / FEE_DENOMINATOR);
new_balances[i] -= fees[i];
}
uint256 D2 = get_D_mem(new_balances, amp);
uint256 token_amount = ((D0 - D2) * token_supply) / D0;
require(token_amount > 0, "token_amount must be greater than 0");
token_amount += 1; // In case of rounding errors - make it unfavorable for the "attacker"
require(token_amount <= max_burn_amount, "Slippage screwed you");
token.burnFrom(msg.sender, token_amount); // dev: insufficient funds
for (uint256 i = 0; i < N_COINS; i++) {
if (amounts[i] > 0) {
transfer_out(coins[i], amounts[i]);
}
}
token_supply -= token_amount;
emit RemoveLiquidityImbalance(msg.sender, amounts, fees, D1, token_supply);
}
function get_y_D(
uint256 A_,
uint256 i,
uint256[N_COINS] memory xp,
uint256 D
) internal pure returns (uint256) {
/**
Calculate x[i] if one reduces D from being calculated for xp to D
Done by solving quadratic equation iteratively.
x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)
x_1**2 + b*x_1 = c
x_1 = (x_1**2 + c) / (2*x_1 + b)
*/
// x in the input is converted to the same price/precision
require(i < N_COINS, "dev: i above N_COINS");
uint256 c = D;
uint256 S_;
uint256 Ann = A_ * N_COINS;
uint256 _x;
for (uint256 k = 0; k < N_COINS; k++) {
if (k != i) {
_x = xp[k];
} else {
continue;
}
S_ += _x;
c = (c * D) / (_x * N_COINS);
}
c = (c * D) / (Ann * N_COINS);
uint256 b = S_ + D / Ann;
uint256 y_prev;
uint256 y = D;
for (uint256 k = 0; k < 255; k++) {
y_prev = y;
y = (y * y + c) / (2 * y + b - D);
// Equality with the precision of 1
if (y > y_prev) {
if (y - y_prev <= 1) {
break;
}
} else {
if (y_prev - y <= 1) {
break;
}
}
}
return y;
}
function _calc_withdraw_one_coin(uint256 _token_amount, uint256 i) internal view returns (uint256, uint256) {
// First, need to calculate
// * Get current D
// * Solve Eqn against y_i for D - _token_amount
uint256 amp = get_A();
uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
uint256[N_COINS] memory precisions = PRECISION_MUL;
uint256 total_supply = token.totalSupply();
uint256[N_COINS] memory xp = _xp();
uint256 D0 = get_D(xp, amp);
uint256 D1 = D0 - (_token_amount * D0) / total_supply;
uint256[N_COINS] memory xp_reduced = xp;
uint256 new_y = get_y_D(amp, i, xp, D1);
uint256 dy_0 = (xp[i] - new_y) / precisions[i]; // w/o fees
for (uint256 k = 0; k < N_COINS; k++) {
uint256 dx_expected;
if (k == i) {
dx_expected = (xp[k] * D1) / D0 - new_y;
} else {
dx_expected = xp[k] - (xp[k] * D1) / D0;
}
xp_reduced[k] -= (_fee * dx_expected) / FEE_DENOMINATOR;
}
uint256 dy = xp_reduced[i] - get_y_D(amp, i, xp_reduced, D1);
dy = (dy - 1) / precisions[i]; // Withdraw less to account for rounding errors
return (dy, dy_0 - dy);
}
function calc_withdraw_one_coin(uint256 _token_amount, uint256 i) external view returns (uint256) {
(uint256 dy, ) = _calc_withdraw_one_coin(_token_amount, i);
return dy;
}
function remove_liquidity_one_coin(
uint256 _token_amount,
uint256 i,
uint256 min_amount
) external nonReentrant {
// Remove _amount of liquidity all in a form of coin i
require(!is_killed, "Killed");
(uint256 dy, uint256 dy_fee) = _calc_withdraw_one_coin(_token_amount, i);
require(dy >= min_amount, "Not enough coins removed");
balances[i] -= (dy + (dy_fee * admin_fee) / FEE_DENOMINATOR);
token.burnFrom(msg.sender, _token_amount); // dev: insufficient funds
transfer_out(coins[i], dy);
emit RemoveLiquidityOne(msg.sender, i, _token_amount, dy);
}
function transfer_out(address coin_address, uint256 value) internal {
if (coin_address == BNB_ADDRESS) {
_safeTransferBNB(msg.sender, value);
} else {
IERC20(coin_address).safeTransfer(msg.sender, value);
}
}
function transfer_in(address coin_address, uint256 value) internal {
if (coin_address == BNB_ADDRESS) {
require(value == msg.value, "Inconsistent quantity");
} else {
IERC20(coin_address).safeTransferFrom(msg.sender, address(this), value);
}
}
function _safeTransferBNB(address to, uint256 value) internal {
(bool success, ) = to.call{gas: bnb_gas, value: value}("");
require(success, "BNB transfer failed");
}
// Admin functions
function set_bnb_gas(uint256 _bnb_gas) external onlyOwner {
require(_bnb_gas >= MIN_BNB_GAS && _bnb_gas <= MAX_BNB_GAS, "Illegal gas");
bnb_gas = _bnb_gas;
emit SetBNBGas(_bnb_gas);
}
function ramp_A(uint256 _future_A, uint256 _future_time) external onlyOwner {
require(block.timestamp >= initial_A_time + MIN_RAMP_TIME, "dev : too early");
require(_future_time >= block.timestamp + MIN_RAMP_TIME, "dev: insufficient time");
uint256 _initial_A = get_A();
require(_future_A > 0 && _future_A < MAX_A, "_future_A must be between 0 and MAX_A");
require(
(_future_A >= _initial_A && _future_A <= _initial_A * MAX_A_CHANGE) ||
(_future_A < _initial_A && _future_A * MAX_A_CHANGE >= _initial_A),
"Illegal parameter _future_A"
);
initial_A = _initial_A;
future_A = _future_A;
initial_A_time = block.timestamp;
future_A_time = _future_time;
emit RampA(_initial_A, _future_A, block.timestamp, _future_time);
}
function stop_rampget_A() external onlyOwner {
uint256 current_A = get_A();
initial_A = current_A;
future_A = current_A;
initial_A_time = block.timestamp;
future_A_time = block.timestamp;
// now (block.timestamp < t1) is always False, so we return saved A
emit StopRampA(current_A, block.timestamp);
}
function commit_new_fee(uint256 new_fee, uint256 new_admin_fee) external onlyOwner {
require(admin_actions_deadline == 0, "admin_actions_deadline must be 0"); // dev: active action
require(new_fee <= MAX_FEE, "dev: fee exceeds maximum");
require(new_admin_fee <= MAX_ADMIN_FEE, "dev: admin fee exceeds maximum");
admin_actions_deadline = block.timestamp + ADMIN_ACTIONS_DELAY;
future_fee = new_fee;
future_admin_fee = new_admin_fee;
emit CommitNewFee(admin_actions_deadline, new_fee, new_admin_fee);
}
function apply_new_fee() external onlyOwner {
require(block.timestamp >= admin_actions_deadline, "dev: insufficient time");
require(admin_actions_deadline != 0, "admin_actions_deadline should not be 0");
admin_actions_deadline = 0;
fee = future_fee;
admin_fee = future_admin_fee;
emit NewFee(fee, admin_fee);
}
function revert_new_parameters() external onlyOwner {
admin_actions_deadline = 0;
emit RevertParameters();
}
function admin_balances(uint256 i) external view returns (uint256) {
if (coins[i] == BNB_ADDRESS) {
return address(this).balance - balances[i];
} else {
return IERC20(coins[i]).balanceOf(address(this)) - balances[i];
}
}
function withdraw_admin_fees() external onlyOwner {
for (uint256 i = 0; i < N_COINS; i++) {
uint256 value;
if (coins[i] == BNB_ADDRESS) {
value = address(this).balance - balances[i];
} else {
value = IERC20(coins[i]).balanceOf(address(this)) - balances[i];
}
if (value > 0) {
transfer_out(coins[i], value);
}
}
}
function donate_admin_fees() external onlyOwner {
for (uint256 i = 0; i < N_COINS; i++) {
if (coins[i] == BNB_ADDRESS) {
balances[i] = address(this).balance;
} else {
balances[i] = IERC20(coins[i]).balanceOf(address(this));
}
}
emit DonateAdminFees();
}
function kill_me() external onlyOwner {
require(kill_deadline > block.timestamp, "Exceeded deadline");
is_killed = true;
emit Kill();
}
function unkill_me() external onlyOwner {
is_killed = false;
emit Unkill();
}
}
PancakeStableSwapThreePoolDeployer.sol 84 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "./PancakeStableSwapThreePool.sol";
contract PancakeStableSwapThreePoolDeployer is Ownable {
uint256 public constant N_COINS = 3;
/**
* @notice constructor
*/
constructor() {}
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(
address tokenA,
address tokenB,
address tokenC
)
internal
pure
returns (
address,
address,
address
)
{
require(tokenA != tokenB && tokenA != tokenC && tokenB != tokenC, "IDENTICAL_ADDRESSES");
address tmp;
if (tokenA > tokenB) {
tmp = tokenA;
tokenA = tokenB;
tokenB = tmp;
}
if (tokenB > tokenC) {
tmp = tokenB;
tokenB = tokenC;
tokenC = tmp;
if (tokenA > tokenB) {
tmp = tokenA;
tokenA = tokenB;
tokenB = tmp;
}
}
return (tokenA, tokenB, tokenC);
}
/**
* @notice createSwapPair
* @param _tokenA: Addresses of ERC20 conracts .
* @param _tokenB: Addresses of ERC20 conracts .
* @param _tokenC: Addresses of ERC20 conracts .
* @param _A: Amplification coefficient multiplied by n * (n - 1)
* @param _fee: Fee to charge for exchanges
* @param _admin_fee: Admin fee
* @param _admin: Admin
* @param _LP: LP
*/
function createSwapPair(
address _tokenA,
address _tokenB,
address _tokenC,
uint256 _A,
uint256 _fee,
uint256 _admin_fee,
address _admin,
address _LP
) external onlyOwner returns (address) {
require(_tokenA != address(0) && _tokenB != address(0) && _tokenA != _tokenB, "Illegal token");
(address t0, address t1, address t2) = sortTokens(_tokenA, _tokenB, _tokenC);
address[N_COINS] memory coins = [t0, t1, t2];
// create swap contract
bytes memory bytecode = type(PancakeStableSwapThreePool).creationCode;
bytes32 salt = keccak256(abi.encodePacked(t0, t1, t2, msg.sender, block.timestamp, block.chainid));
address swapContract;
assembly {
swapContract := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
PancakeStableSwapThreePool(swapContract).initialize(coins, _A, _fee, _admin_fee, _admin, _LP);
return swapContract;
}
}
PancakeStableSwapTwoPoolInfo.sol 435 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IPancakeStableSwap.sol";
contract PancakeStableSwapTwoPoolInfo {
uint256 public constant N_COINS = 2;
uint256 public constant FEE_DENOMINATOR = 1e10;
uint256 public constant PRECISION = 1e18;
function token(address _swap) public view returns (IERC20) {
return IERC20(IPancakeStableSwap(_swap).token());
}
function balances(address _swap) public view returns (uint256[N_COINS] memory swapBalances) {
for (uint256 i = 0; i < N_COINS; i++) {
swapBalances[i] = IPancakeStableSwap(_swap).balances(i);
}
}
function RATES(address _swap) public view returns (uint256[N_COINS] memory swapRATES) {
for (uint256 i = 0; i < N_COINS; i++) {
swapRATES[i] = IPancakeStableSwap(_swap).RATES(i);
}
}
function PRECISION_MUL(address _swap) public view returns (uint256[N_COINS] memory swapPRECISION_MUL) {
for (uint256 i = 0; i < N_COINS; i++) {
swapPRECISION_MUL[i] = IPancakeStableSwap(_swap).PRECISION_MUL(i);
}
}
function calc_coins_amount(address _swap, uint256 _amount) external view returns (uint256[N_COINS] memory) {
uint256 total_supply = token(_swap).totalSupply();
uint256[N_COINS] memory amounts;
for (uint256 i = 0; i < N_COINS; i++) {
uint256 value = (IPancakeStableSwap(_swap).balances(i) * _amount) / total_supply;
amounts[i] = value;
}
return amounts;
}
function get_D_mem(
address _swap,
uint256[N_COINS] memory _balances,
uint256 amp
) public view returns (uint256) {
return get_D(_xp_mem(_swap, _balances), amp);
}
function get_add_liquidity_mint_amount(address _swap, uint256[N_COINS] memory amounts)
external
view
returns (uint256)
{
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
uint256[N_COINS] memory fees;
uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
uint256 amp = swap.A();
uint256 token_supply = token(_swap).totalSupply();
//Initial invariant
uint256 D0;
uint256[N_COINS] memory old_balances = balances(_swap);
if (token_supply > 0) {
D0 = get_D_mem(_swap, old_balances, amp);
}
uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1]];
for (uint256 i = 0; i < N_COINS; i++) {
if (token_supply == 0) {
require(amounts[i] > 0, "Initial deposit requires all coins");
}
// balances store amounts of c-tokens
new_balances[i] = old_balances[i] + amounts[i];
}
// Invariant after change
uint256 D1 = get_D_mem(_swap, new_balances, amp);
require(D1 > D0, "D1 must be greater than D0");
// We need to recalculate the invariant accounting for fees
// to calculate fair user's share
uint256 D2 = D1;
if (token_supply > 0) {
// Only account for fees if we are not the first to deposit
for (uint256 i = 0; i < N_COINS; i++) {
uint256 ideal_balance = (D1 * old_balances[i]) / D0;
uint256 difference;
if (ideal_balance > new_balances[i]) {
difference = ideal_balance - new_balances[i];
} else {
difference = new_balances[i] - ideal_balance;
}
fees[i] = (_fee * difference) / FEE_DENOMINATOR;
new_balances[i] -= fees[i];
}
D2 = get_D_mem(_swap, new_balances, amp);
}
// Calculate, how much pool tokens to mint
uint256 mint_amount;
if (token_supply == 0) {
mint_amount = D1; // Take the dust if there was any
} else {
mint_amount = (token_supply * (D2 - D0)) / D0;
}
return mint_amount;
}
function get_add_liquidity_fee(address _swap, uint256[N_COINS] memory amounts)
external
view
returns (uint256[N_COINS] memory liquidityFee)
{
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
uint256 _admin_fee = swap.admin_fee();
uint256 amp = swap.A();
uint256 token_supply = token(_swap).totalSupply();
//Initial invariant
uint256 D0;
uint256[N_COINS] memory old_balances = balances(_swap);
if (token_supply > 0) {
D0 = get_D_mem(_swap, old_balances, amp);
}
uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1]];
for (uint256 i = 0; i < N_COINS; i++) {
if (token_supply == 0) {
require(amounts[i] > 0, "Initial deposit requires all coins");
}
new_balances[i] = old_balances[i] + amounts[i];
}
// Invariant after change
uint256 D1 = get_D_mem(_swap, new_balances, amp);
require(D1 > D0, "D1 must be greater than D0");
if (token_supply > 0) {
// Only account for fees if we are not the first to deposit
for (uint256 i = 0; i < N_COINS; i++) {
uint256 ideal_balance = (D1 * old_balances[i]) / D0;
uint256 difference;
if (ideal_balance > new_balances[i]) {
difference = ideal_balance - new_balances[i];
} else {
difference = new_balances[i] - ideal_balance;
}
uint256 coinFee;
coinFee = (_fee * difference) / FEE_DENOMINATOR;
liquidityFee[i] = ((coinFee * _admin_fee) / FEE_DENOMINATOR);
}
}
}
function get_remove_liquidity_imbalance_fee(address _swap, uint256[N_COINS] memory amounts)
external
view
returns (uint256[N_COINS] memory liquidityFee)
{
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
uint256 _admin_fee = swap.admin_fee();
uint256 amp = swap.A();
uint256[N_COINS] memory old_balances = balances(_swap);
uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1]];
uint256 D0 = get_D_mem(_swap, old_balances, amp);
for (uint256 i = 0; i < N_COINS; i++) {
new_balances[i] -= amounts[i];
}
uint256 D1 = get_D_mem(_swap, new_balances, amp);
for (uint256 i = 0; i < N_COINS; i++) {
uint256 ideal_balance = (D1 * old_balances[i]) / D0;
uint256 difference;
if (ideal_balance > new_balances[i]) {
difference = ideal_balance - new_balances[i];
} else {
difference = new_balances[i] - ideal_balance;
}
uint256 coinFee;
coinFee = (_fee * difference) / FEE_DENOMINATOR;
liquidityFee[i] = ((coinFee * _admin_fee) / FEE_DENOMINATOR);
}
}
function _xp_mem(address _swap, uint256[N_COINS] memory _balances)
public
view
returns (uint256[N_COINS] memory result)
{
result = RATES(_swap);
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (result[i] * _balances[i]) / PRECISION;
}
}
function get_D(uint256[N_COINS] memory xp, uint256 amp) internal pure returns (uint256) {
uint256 S;
for (uint256 i = 0; i < N_COINS; i++) {
S += xp[i];
}
if (S == 0) {
return 0;
}
uint256 Dprev;
uint256 D = S;
uint256 Ann = amp * N_COINS;
for (uint256 j = 0; j < 255; j++) {
uint256 D_P = D;
for (uint256 k = 0; k < N_COINS; k++) {
D_P = (D_P * D) / (xp[k] * N_COINS); // If division by 0, this will be borked: only withdrawal will work. And that is good
}
Dprev = D;
D = ((Ann * S + D_P * N_COINS) * D) / ((Ann - 1) * D + (N_COINS + 1) * D_P);
// Equality with the precision of 1
if (D > Dprev) {
if (D - Dprev <= 1) {
break;
}
} else {
if (Dprev - D <= 1) {
break;
}
}
}
return D;
}
function get_y(
address _swap,
uint256 i,
uint256 j,
uint256 x,
uint256[N_COINS] memory xp_
) internal view returns (uint256) {
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
uint256 amp = swap.A();
uint256 D = get_D(xp_, amp);
uint256 c = D;
uint256 S_;
uint256 Ann = amp * N_COINS;
uint256 _x;
for (uint256 k = 0; k < N_COINS; k++) {
if (k == i) {
_x = x;
} else if (k != j) {
_x = xp_[k];
} else {
continue;
}
S_ += _x;
c = (c * D) / (_x * N_COINS);
}
c = (c * D) / (Ann * N_COINS);
uint256 b = S_ + D / Ann; // - D
uint256 y_prev;
uint256 y = D;
for (uint256 m = 0; m < 255; m++) {
y_prev = y;
y = (y * y + c) / (2 * y + b - D);
// Equality with the precision of 1
if (y > y_prev) {
if (y - y_prev <= 1) {
break;
}
} else {
if (y_prev - y <= 1) {
break;
}
}
}
return y;
}
function get_exchange_fee(
address _swap,
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256 exFee, uint256 exAdminFee) {
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
uint256[N_COINS] memory old_balances = balances(_swap);
uint256[N_COINS] memory xp = _xp_mem(_swap, old_balances);
uint256[N_COINS] memory rates = RATES(_swap);
uint256 x = xp[i] + (dx * rates[i]) / PRECISION;
uint256 y = get_y(_swap, i, j, x, xp);
uint256 dy = xp[j] - y - 1; // -1 just in case there were some rounding errors
uint256 dy_fee = (dy * swap.fee()) / FEE_DENOMINATOR;
uint256 dy_admin_fee = (dy_fee * swap.admin_fee()) / FEE_DENOMINATOR;
dy_fee = (dy_fee * PRECISION) / rates[j];
dy_admin_fee = (dy_admin_fee * PRECISION) / rates[j];
exFee = dy_fee;
exAdminFee = dy_admin_fee;
}
function _xp(address _swap) internal view returns (uint256[N_COINS] memory result) {
result = RATES(_swap);
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (result[i] * IPancakeStableSwap(_swap).balances(i)) / PRECISION;
}
}
function get_y_D(
uint256 A_,
uint256 i,
uint256[N_COINS] memory xp,
uint256 D
) internal pure returns (uint256) {
/**
Calculate x[i] if one reduces D from being calculated for xp to D
Done by solving quadratic equation iteratively.
x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)
x_1**2 + b*x_1 = c
x_1 = (x_1**2 + c) / (2*x_1 + b)
*/
// x in the input is converted to the same price/precision
require(i < N_COINS, "dev: i above N_COINS");
uint256 c = D;
uint256 S_;
uint256 Ann = A_ * N_COINS;
uint256 _x;
for (uint256 k = 0; k < N_COINS; k++) {
if (k != i) {
_x = xp[k];
} else {
continue;
}
S_ += _x;
c = (c * D) / (_x * N_COINS);
}
c = (c * D) / (Ann * N_COINS);
uint256 b = S_ + D / Ann;
uint256 y_prev;
uint256 y = D;
for (uint256 k = 0; k < 255; k++) {
y_prev = y;
y = (y * y + c) / (2 * y + b - D);
// Equality with the precision of 1
if (y > y_prev) {
if (y - y_prev <= 1) {
break;
}
} else {
if (y_prev - y <= 1) {
break;
}
}
}
return y;
}
function _calc_withdraw_one_coin(
address _swap,
uint256 _token_amount,
uint256 i
) internal view returns (uint256, uint256) {
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
uint256 amp = swap.A();
uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
uint256[N_COINS] memory precisions = PRECISION_MUL(_swap);
uint256[N_COINS] memory xp = _xp(_swap);
uint256 D0 = get_D(xp, amp);
uint256 D1 = D0 - (_token_amount * D0) / (token(_swap).totalSupply());
uint256[N_COINS] memory xp_reduced = xp;
uint256 new_y = get_y_D(amp, i, xp, D1);
uint256 dy_0 = (xp[i] - new_y) / precisions[i]; // w/o fees
for (uint256 k = 0; k < N_COINS; k++) {
uint256 dx_expected;
if (k == i) {
dx_expected = (xp[k] * D1) / D0 - new_y;
} else {
dx_expected = xp[k] - (xp[k] * D1) / D0;
}
xp_reduced[k] -= (_fee * dx_expected) / FEE_DENOMINATOR;
}
uint256 dy = xp_reduced[i] - get_y_D(amp, i, xp_reduced, D1);
dy = (dy - 1) / precisions[i]; // Withdraw less to account for rounding errors
return (dy, dy_0 - dy);
}
function get_remove_liquidity_one_coin_fee(
address _swap,
uint256 _token_amount,
uint256 i
) external view returns (uint256 adminFee) {
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
(, uint256 dy_fee) = _calc_withdraw_one_coin(_swap, _token_amount, i);
adminFee = (dy_fee * swap.admin_fee()) / FEE_DENOMINATOR;
}
function get_dx(
address _swap,
uint256 i,
uint256 j,
uint256 dy,
uint256 max_dx
) external view returns (uint256) {
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
uint256[N_COINS] memory old_balances = balances(_swap);
uint256[N_COINS] memory xp = _xp_mem(_swap, old_balances);
uint256 dy_with_fee = (dy * FEE_DENOMINATOR) / (FEE_DENOMINATOR - swap.fee());
require(dy_with_fee < old_balances[j], "Excess balance");
uint256[N_COINS] memory rates = RATES(_swap);
uint256 y = xp[j] - (dy_with_fee * rates[j]) / PRECISION;
uint256 x = get_y(_swap, j, i, y, xp);
uint256 dx = x - xp[i];
// Convert all to real units
dx = (dx * PRECISION) / rates[i] + 1; // +1 for round lose.
require(dx <= max_dx, "Exchange resulted in fewer coins than expected");
return dx;
}
}
PancakeStableSwapThreePoolInfo.sol 434 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IPancakeStableSwap.sol";
contract PancakeStableSwapThreePoolInfo {
uint256 public constant N_COINS = 3;
uint256 public constant FEE_DENOMINATOR = 1e10;
uint256 public constant PRECISION = 1e18;
function token(address _swap) public view returns (IERC20) {
return IERC20(IPancakeStableSwap(_swap).token());
}
function balances(address _swap) public view returns (uint256[N_COINS] memory swapBalances) {
for (uint256 i = 0; i < N_COINS; i++) {
swapBalances[i] = IPancakeStableSwap(_swap).balances(i);
}
}
function RATES(address _swap) public view returns (uint256[N_COINS] memory swapRATES) {
for (uint256 i = 0; i < N_COINS; i++) {
swapRATES[i] = IPancakeStableSwap(_swap).RATES(i);
}
}
function PRECISION_MUL(address _swap) public view returns (uint256[N_COINS] memory swapPRECISION_MUL) {
for (uint256 i = 0; i < N_COINS; i++) {
swapPRECISION_MUL[i] = IPancakeStableSwap(_swap).PRECISION_MUL(i);
}
}
function calc_coins_amount(address _swap, uint256 _amount) external view returns (uint256[N_COINS] memory) {
uint256 total_supply = token(_swap).totalSupply();
uint256[N_COINS] memory amounts;
for (uint256 i = 0; i < N_COINS; i++) {
uint256 value = (IPancakeStableSwap(_swap).balances(i) * _amount) / total_supply;
amounts[i] = value;
}
return amounts;
}
function get_D_mem(
address _swap,
uint256[N_COINS] memory _balances,
uint256 amp
) public view returns (uint256) {
return get_D(_xp_mem(_swap, _balances), amp);
}
function get_add_liquidity_mint_amount(address _swap, uint256[N_COINS] memory amounts)
external
view
returns (uint256)
{
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
uint256[N_COINS] memory fees;
uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
uint256 amp = swap.A();
uint256 token_supply = token(_swap).totalSupply();
//Initial invariant
uint256 D0;
uint256[N_COINS] memory old_balances = balances(_swap);
if (token_supply > 0) {
D0 = get_D_mem(_swap, old_balances, amp);
}
uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1], old_balances[2]];
for (uint256 i = 0; i < N_COINS; i++) {
if (token_supply == 0) {
require(amounts[i] > 0, "Initial deposit requires all coins");
}
// balances store amounts of c-tokens
new_balances[i] = old_balances[i] + amounts[i];
}
// Invariant after change
uint256 D1 = get_D_mem(_swap, new_balances, amp);
require(D1 > D0, "D1 must be greater than D0");
// We need to recalculate the invariant accounting for fees
// to calculate fair user's share
uint256 D2 = D1;
if (token_supply > 0) {
// Only account for fees if we are not the first to deposit
for (uint256 i = 0; i < N_COINS; i++) {
uint256 ideal_balance = (D1 * old_balances[i]) / D0;
uint256 difference;
if (ideal_balance > new_balances[i]) {
difference = ideal_balance - new_balances[i];
} else {
difference = new_balances[i] - ideal_balance;
}
fees[i] = (_fee * difference) / FEE_DENOMINATOR;
new_balances[i] -= fees[i];
}
D2 = get_D_mem(_swap, new_balances, amp);
}
// Calculate, how much pool tokens to mint
uint256 mint_amount;
if (token_supply == 0) {
mint_amount = D1; // Take the dust if there was any
} else {
mint_amount = (token_supply * (D2 - D0)) / D0;
}
return mint_amount;
}
function get_add_liquidity_fee(address _swap, uint256[N_COINS] memory amounts)
external
view
returns (uint256[N_COINS] memory liquidityFee)
{
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
uint256 _admin_fee = swap.admin_fee();
uint256 amp = swap.A();
uint256 token_supply = token(_swap).totalSupply();
//Initial invariant
uint256 D0;
uint256[N_COINS] memory old_balances = balances(_swap);
if (token_supply > 0) {
D0 = get_D_mem(_swap, old_balances, amp);
}
uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1], old_balances[2]];
for (uint256 i = 0; i < N_COINS; i++) {
if (token_supply == 0) {
require(amounts[i] > 0, "Initial deposit requires all coins");
}
new_balances[i] = old_balances[i] + amounts[i];
}
// Invariant after change
uint256 D1 = get_D_mem(_swap, new_balances, amp);
require(D1 > D0, "D1 must be greater than D0");
if (token_supply > 0) {
// Only account for fees if we are not the first to deposit
for (uint256 i = 0; i < N_COINS; i++) {
uint256 ideal_balance = (D1 * old_balances[i]) / D0;
uint256 difference;
if (ideal_balance > new_balances[i]) {
difference = ideal_balance - new_balances[i];
} else {
difference = new_balances[i] - ideal_balance;
}
uint256 coinFee;
coinFee = (_fee * difference) / FEE_DENOMINATOR;
liquidityFee[i] = ((coinFee * _admin_fee) / FEE_DENOMINATOR);
}
}
}
function get_remove_liquidity_imbalance_fee(address _swap, uint256[N_COINS] memory amounts)
external
view
returns (uint256[N_COINS] memory liquidityFee)
{
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
uint256 _admin_fee = swap.admin_fee();
uint256 amp = swap.A();
uint256[N_COINS] memory old_balances = balances(_swap);
uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1], old_balances[2]];
uint256 D0 = get_D_mem(_swap, old_balances, amp);
for (uint256 i = 0; i < N_COINS; i++) {
new_balances[i] -= amounts[i];
}
uint256 D1 = get_D_mem(_swap, new_balances, amp);
for (uint256 i = 0; i < N_COINS; i++) {
uint256 ideal_balance = (D1 * old_balances[i]) / D0;
uint256 difference;
if (ideal_balance > new_balances[i]) {
difference = ideal_balance - new_balances[i];
} else {
difference = new_balances[i] - ideal_balance;
}
uint256 coinFee;
coinFee = (_fee * difference) / FEE_DENOMINATOR;
liquidityFee[i] = ((coinFee * _admin_fee) / FEE_DENOMINATOR);
}
}
function _xp_mem(address _swap, uint256[N_COINS] memory _balances)
public
view
returns (uint256[N_COINS] memory result)
{
result = RATES(_swap);
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (result[i] * _balances[i]) / PRECISION;
}
}
function get_D(uint256[N_COINS] memory xp, uint256 amp) internal pure returns (uint256) {
uint256 S;
for (uint256 i = 0; i < N_COINS; i++) {
S += xp[i];
}
if (S == 0) {
return 0;
}
uint256 Dprev;
uint256 D = S;
uint256 Ann = amp * N_COINS;
for (uint256 j = 0; j < 255; j++) {
uint256 D_P = D;
for (uint256 k = 0; k < N_COINS; k++) {
D_P = (D_P * D) / (xp[k] * N_COINS); // If division by 0, this will be borked: only withdrawal will work. And that is good
}
Dprev = D;
D = ((Ann * S + D_P * N_COINS) * D) / ((Ann - 1) * D + (N_COINS + 1) * D_P);
// Equality with the precision of 1
if (D > Dprev) {
if (D - Dprev <= 1) {
break;
}
} else {
if (Dprev - D <= 1) {
break;
}
}
}
return D;
}
function get_y(
address _swap,
uint256 i,
uint256 j,
uint256 x,
uint256[N_COINS] memory xp_
) internal view returns (uint256) {
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
uint256 amp = swap.A();
uint256 D = get_D(xp_, amp);
uint256 c = D;
uint256 S_;
uint256 Ann = amp * N_COINS;
uint256 _x;
for (uint256 k = 0; k < N_COINS; k++) {
if (k == i) {
_x = x;
} else if (k != j) {
_x = xp_[k];
} else {
continue;
}
S_ += _x;
c = (c * D) / (_x * N_COINS);
}
c = (c * D) / (Ann * N_COINS);
uint256 b = S_ + D / Ann; // - D
uint256 y_prev;
uint256 y = D;
for (uint256 m = 0; m < 255; m++) {
y_prev = y;
y = (y * y + c) / (2 * y + b - D);
// Equality with the precision of 1
if (y > y_prev) {
if (y - y_prev <= 1) {
break;
}
} else {
if (y_prev - y <= 1) {
break;
}
}
}
return y;
}
function get_exchange_fee(
address _swap,
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256 exFee, uint256 exAdminFee) {
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
uint256[N_COINS] memory old_balances = balances(_swap);
uint256[N_COINS] memory xp = _xp_mem(_swap, old_balances);
uint256[N_COINS] memory rates = RATES(_swap);
uint256 x = xp[i] + (dx * rates[i]) / PRECISION;
uint256 y = get_y(_swap, i, j, x, xp);
uint256 dy = xp[j] - y - 1; // -1 just in case there were some rounding errors
uint256 dy_fee = (dy * swap.fee()) / FEE_DENOMINATOR;
uint256 dy_admin_fee = (dy_fee * swap.admin_fee()) / FEE_DENOMINATOR;
dy_fee = (dy_fee * PRECISION) / rates[j];
dy_admin_fee = (dy_admin_fee * PRECISION) / rates[j];
exFee = dy_fee;
exAdminFee = dy_admin_fee;
}
function _xp(address _swap) internal view returns (uint256[N_COINS] memory result) {
result = RATES(_swap);
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (result[i] * IPancakeStableSwap(_swap).balances(i)) / PRECISION;
}
}
function get_y_D(
uint256 A_,
uint256 i,
uint256[N_COINS] memory xp,
uint256 D
) internal pure returns (uint256) {
/**
Calculate x[i] if one reduces D from being calculated for xp to D
Done by solving quadratic equation iteratively.
x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)
x_1**2 + b*x_1 = c
x_1 = (x_1**2 + c) / (2*x_1 + b)
*/
// x in the input is converted to the same price/precision
require(i < N_COINS, "dev: i above N_COINS");
uint256 c = D;
uint256 S_;
uint256 Ann = A_ * N_COINS;
uint256 _x;
for (uint256 k = 0; k < N_COINS; k++) {
if (k != i) {
_x = xp[k];
} else {
continue;
}
S_ += _x;
c = (c * D) / (_x * N_COINS);
}
c = (c * D) / (Ann * N_COINS);
uint256 b = S_ + D / Ann;
uint256 y_prev;
uint256 y = D;
for (uint256 k = 0; k < 255; k++) {
y_prev = y;
y = (y * y + c) / (2 * y + b - D);
// Equality with the precision of 1
if (y > y_prev) {
if (y - y_prev <= 1) {
break;
}
} else {
if (y_prev - y <= 1) {
break;
}
}
}
return y;
}
function _calc_withdraw_one_coin(
address _swap,
uint256 _token_amount,
uint256 i
) internal view returns (uint256, uint256) {
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
uint256 amp = swap.A();
uint256 _fee = (swap.fee() * N_COINS) / (4 * (N_COINS - 1));
uint256[N_COINS] memory precisions = PRECISION_MUL(_swap);
uint256[N_COINS] memory xp = _xp(_swap);
uint256 D0 = get_D(xp, amp);
uint256 D1 = D0 - (_token_amount * D0) / (token(_swap).totalSupply());
uint256[N_COINS] memory xp_reduced = xp;
uint256 new_y = get_y_D(amp, i, xp, D1);
uint256 dy_0 = (xp[i] - new_y) / precisions[i]; // w/o fees
for (uint256 k = 0; k < N_COINS; k++) {
uint256 dx_expected;
if (k == i) {
dx_expected = (xp[k] * D1) / D0 - new_y;
} else {
dx_expected = xp[k] - (xp[k] * D1) / D0;
}
xp_reduced[k] -= (_fee * dx_expected) / FEE_DENOMINATOR;
}
uint256 dy = xp_reduced[i] - get_y_D(amp, i, xp_reduced, D1);
dy = (dy - 1) / precisions[i]; // Withdraw less to account for rounding errors
return (dy, dy_0 - dy);
}
function get_remove_liquidity_one_coin_fee(
address _swap,
uint256 _token_amount,
uint256 i
) external view returns (uint256 adminFee) {
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
(, uint256 dy_fee) = _calc_withdraw_one_coin(_swap, _token_amount, i);
adminFee = (dy_fee * swap.admin_fee()) / FEE_DENOMINATOR;
}
function get_dx(
address _swap,
uint256 i,
uint256 j,
uint256 dy,
uint256 max_dx
) external view returns (uint256) {
IPancakeStableSwap swap = IPancakeStableSwap(_swap);
uint256[N_COINS] memory old_balances = balances(_swap);
uint256[N_COINS] memory xp = _xp_mem(_swap, old_balances);
uint256 dy_with_fee = (dy * FEE_DENOMINATOR) / (FEE_DENOMINATOR - swap.fee());
require(dy_with_fee < old_balances[j], "Excess balance");
uint256[N_COINS] memory rates = RATES(_swap);
uint256 y = xp[j] - (dy_with_fee * rates[j]) / PRECISION;
uint256 x = get_y(_swap, j, i, y, xp);
uint256 dx = x - xp[i];
// Convert all to real units
dx = (dx * PRECISION) / rates[i] + 1; // +1 for round lose.
require(dx <= max_dx, "Exchange resulted in fewer coins than expected");
return dx;
}
}
PancakeStableSwapInfo.sol 30 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IPancakeStableSwapInfo.sol";
import "../interfaces/IPancakeStableSwap.sol";
contract PancakeStableSwapInfo {
IPancakeStableSwapInfo public immutable twoPoolInfo;
IPancakeStableSwapInfo public immutable threePoolInfo;
constructor(IPancakeStableSwapInfo _twoPoolInfo, IPancakeStableSwapInfo _threePoolInfo) {
twoPoolInfo = _twoPoolInfo;
threePoolInfo = _threePoolInfo;
}
function get_dx(
address _swap,
uint256 i,
uint256 j,
uint256 dy,
uint256 max_dx
) external view returns (uint256 dx) {
uint256 N_COINS = IPancakeStableSwap(_swap).N_COINS();
if (N_COINS == 2) {
dx = twoPoolInfo.get_dx(_swap, i, j, dy, max_dx);
} else if (N_COINS == 3) {
dx = threePoolInfo.get_dx(_swap, i, j, dy, max_dx);
}
}
}
IPancakeStableSwapInfo.sol 12 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IPancakeStableSwapInfo {
function get_dx(
address _swap,
uint256 i,
uint256 j,
uint256 dy,
uint256 max_dx
) external view returns (uint256);
}
ERC20.sol 383 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
Token.sol 28 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/token/ERC20/ERC20.sol";
contract Token is ERC20 {
uint8 private immutable newDecimal;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimal
) ERC20(_name, _symbol) {
newDecimal = _decimal;
}
function decimals() public view override returns (uint8) {
return newDecimal;
}
function mint(address _to, uint256 _amount) external {
_mint(_to, _amount);
}
function burnFrom(address _to, uint256 _amount) external {
_burn(_to, _amount);
}
}
PancakeStableSwapLP.sol 32 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/token/ERC20/ERC20.sol";
contract PancakeStableSwapLP is ERC20 {
address public minter;
constructor() ERC20("Pancake StableSwap LPs", "Stable-LP") {
minter = msg.sender;
}
/**
* @notice Checks if the msg.sender is the minter address.
*/
modifier onlyMinter() {
require(msg.sender == minter, "Not minter");
_;
}
function setMinter(address _newMinter) external onlyMinter {
minter = _newMinter;
}
function mint(address _to, uint256 _amount) external onlyMinter {
_mint(_to, _amount);
}
function burnFrom(address _to, uint256 _amount) external onlyMinter {
_burn(_to, _amount);
}
}
PancakeStableSwapLPFactory.sol 38 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "./PancakeStableSwapLP.sol";
contract PancakeStableSwapLPFactory is Ownable {
event NewStableSwapLP(address indexed swapLPContract, address tokenA, address tokenB, address tokenC);
constructor() {}
/**
* @notice createSwapLP
* @param _tokenA: Addresses of ERC20 conracts .
* @param _tokenB: Addresses of ERC20 conracts .
* @param _tokenC: Addresses of ERC20 conracts .
* @param _minter: Minter address
*/
function createSwapLP(
address _tokenA,
address _tokenB,
address _tokenC,
address _minter
) external onlyOwner returns (address) {
// create LP token
bytes memory bytecode = type(PancakeStableSwapLP).creationCode;
bytes32 salt = keccak256(
abi.encodePacked(_tokenA, _tokenB, _tokenC, msg.sender, block.timestamp, block.chainid)
);
address lpToken;
assembly {
lpToken := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
PancakeStableSwapLP(lpToken).setMinter(_minter);
emit NewStableSwapLP(lpToken, _tokenA, _tokenB, _tokenC);
return lpToken;
}
}
IPancakeStableSwapDeployer.sol 25 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IPancakeStableSwapDeployer {
function createSwapPair(
address _tokenA,
address _tokenB,
uint256 _A,
uint256 _fee,
uint256 _admin_fee,
address _admin,
address _LP
) external returns (address);
function createSwapPair(
address _tokenA,
address _tokenB,
address _tokenC,
uint256 _A,
uint256 _fee,
uint256 _admin_fee,
address _admin,
address _LP
) external returns (address);
}
IPancakeStableSwapLPFactory.sol 11 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IPancakeStableSwapLPFactory {
function createSwapLP(
address _tokenA,
address _tokenB,
address _tokenC,
address _minter
) external returns (address);
}
PancakeStableSwapFactoryOwner.sol 138 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin-4.5.0/contracts/access/Ownable.sol";
import "./interfaces/IPancakeStableSwapFactory.sol";
import "./interfaces/IPancakeStableSwap.sol";
contract PancakeStableSwapFactoryOwner is Ownable {
IPancakeStableSwapFactory public immutable PancakeStableSwapFactory;
// user can deploy new stable swap pair with permission.
mapping(address => bool) public deployPermission;
event UpdatePermission(address indexed user, bool permission);
event NewStableSwapPair(address indexed user, address swapContract, address lpContract);
error ZeroAddress();
error NoPermission();
error PairAlreadyExist(address swapContract);
modifier onlyPermission() {
if (!deployPermission[msg.sender]) {
revert NoPermission();
}
_;
}
/**
* @notice constructor
* _factory : PancakeStableSwapFactory
*/
constructor(IPancakeStableSwapFactory _factory) {
PancakeStableSwapFactory = _factory;
}
struct PermissionConfig {
address user;
bool permission;
}
/**
* @notice setPermission
* @param _permissions : PermissionConfig array.
*/
function setPermission(PermissionConfig[] calldata _permissions) external onlyOwner {
for (uint256 i = 0; i < _permissions.length; i++) {
PermissionConfig memory currentPermissionConfig = _permissions[i];
if (currentPermissionConfig.user == address(0)) {
revert ZeroAddress();
}
deployPermission[currentPermissionConfig.user] = currentPermissionConfig.permission;
emit UpdatePermission(currentPermissionConfig.user, currentPermissionConfig.permission);
}
}
/**
* @notice createSwapPairWithPermission
* @dev Create a new stable swap pair with permission.
* @dev Can only create pair which does not exist.
* @param _tokenA : Addresses of ERC20 conracts .
* @param _tokenB : Addresses of ERC20 conracts .
* @param _A : Amplification coefficient multiplied by n * (n - 1)
* @param _fee : Fee to charge for exchanges
* @param _admin_fee : Admin fee
*/
function createSwapPairWithPermission(
address _tokenA,
address _tokenB,
uint256 _A,
uint256 _fee,
uint256 _admin_fee
) external onlyPermission {
_checkExistPair(_tokenA, _tokenB);
_createSwapPair(_tokenA, _tokenB, _A, _fee, _admin_fee);
}
/**
* @notice createSwapPair
* @dev Create a new stable swap pair by owner.
* @dev Can create pair which exists.
* @dev It will update the stableSwapPairInfo in PancakeStableSwapFactory when deploying existing pair, and there is no effect on existing pairs.
* @param _tokenA : Addresses of ERC20 conracts .
* @param _tokenB : Addresses of ERC20 conracts .
* @param _A : Amplification coefficient multiplied by n * (n - 1)
* @param _fee : Fee to charge for exchanges
* @param _admin_fee : Admin fee
*/
function createSwapPair(
address _tokenA,
address _tokenB,
uint256 _A,
uint256 _fee,
uint256 _admin_fee
) external onlyOwner {
_createSwapPair(_tokenA, _tokenB, _A, _fee, _admin_fee);
}
/**
* @notice setFactoryOwner
* @dev Transfer ownership of PancakeStableSwapFactory.
* @param _newOwner : New owner.
*/
function setFactoryOwner(address _newOwner) external onlyOwner {
PancakeStableSwapFactory.transferOwnership(_newOwner);
}
/**
* @notice addPairInfo
* @dev Add pair info to PancakeStableSwapFactory when we deploy a new factory.
* @dev It will update the stableSwapPairInfo in PancakeStableSwapFactory, and there is no effect on existing pairs.
* @param _swapContract : Swap contract.
*/
function addPairInfo(address _swapContract) external onlyOwner {
PancakeStableSwapFactory.addPairInfo(_swapContract);
}
function _createSwapPair(
address _tokenA,
address _tokenB,
uint256 _A,
uint256 _fee,
uint256 _admin_fee
) internal {
PancakeStableSwapFactory.createSwapPair(_tokenA, _tokenB, _A, _fee, _admin_fee);
(address swapContract, , , address LPContract) = PancakeStableSwapFactory.getPairInfo(_tokenA, _tokenB);
// transfer stable swap pool ownership to owner
IPancakeStableSwap(swapContract).transferOwnership(owner());
emit NewStableSwapPair(msg.sender, swapContract, LPContract);
}
function _checkExistPair(address _tokenA, address _tokenB) internal view {
(address swapContract, , , ) = PancakeStableSwapFactory.getPairInfo(_tokenA, _tokenB);
if (swapContract != address(0)) {
revert PairAlreadyExist(swapContract);
}
}
}
IPancakeStableSwapFactory.sol 66 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
interface IPancakeStableSwapFactory {
function stableSwapPairInfo(
address,
address,
address
)
external
view
returns (
address swapContract,
address token0,
address token1,
address LPContract
);
/**
* @notice createSwapPair
* @param _tokenA: Addresses of ERC20 conracts .
* @param _tokenB: Addresses of ERC20 conracts .
* @param _A: Amplification coefficient multiplied by n * (n - 1)
* @param _fee: Fee to charge for exchanges
* @param _admin_fee: Admin fee
*/
function createSwapPair(
address _tokenA,
address _tokenB,
uint256 _A,
uint256 _fee,
uint256 _admin_fee
) external;
/**
* @notice createThreePoolPair
* @param _tokenA: Addresses of ERC20 conracts .
* @param _tokenB: Addresses of ERC20 conracts .
* @param _tokenC: Addresses of ERC20 conracts .
* @param _A: Amplification coefficient multiplied by n * (n - 1)
* @param _fee: Fee to charge for exchanges
* @param _admin_fee: Admin fee
*/
function createThreePoolPair(
address _tokenA,
address _tokenB,
address _tokenC,
uint256 _A,
uint256 _fee,
uint256 _admin_fee
) external;
function addPairInfo(address _swapContract) external;
function transferOwnership(address _newOwner) external;
function getPairInfo(address _tokenA, address _tokenB)
external
view
returns (
address,
address,
address,
address
);
}
Read Contract
A 0xf446c1d0 → uint256
ADMIN_ACTIONS_DELAY 0xe5d9e903 → uint256
FEE_DENOMINATOR 0xd73792a9 → uint256
KILL_DEADLINE_DT 0xedfb7801 → uint256
MAX_A 0x39698415 → uint256
MAX_ADMIN_FEE 0xf3de0362 → uint256
MAX_A_CHANGE 0xab5ac061 → uint256
MAX_BNB_GAS 0x25d2edf0 → uint256
MAX_DECIMAL 0x6d4366b7 → uint256
MAX_FEE 0xbc063e1a → uint256
MIN_BNB_GAS 0x9a1d6ed3 → uint256
MIN_RAMP_TIME 0x06e9481c → uint256
N_COINS 0x29357750 → uint256
PRECISION 0xaaf5eb68 → uint256
PRECISION_MUL 0x7dafa364 → uint256
RATES 0x62203d74 → uint256
STABLESWAP_FACTORY 0xa6b0a718 → address
admin_actions_deadline 0x405e28f8 → uint256
admin_balances 0xe2e7d264 → uint256
admin_fee 0xfee3f7f9 → uint256
balances 0x4903b0d1 → uint256
bnb_gas 0x4488ddf0 → uint256
calc_token_amount 0xed8e84f3 → uint256
calc_withdraw_one_coin 0x4fb08c5e → uint256
coins 0xc6610657 → address
fee 0xddca3f43 → uint256
future_A 0xb4b577ad → uint256
future_A_time 0x14052288 → uint256
future_admin_fee 0xe3824462 → uint256
future_fee 0x58680d0b → uint256
get_dy 0x556d6e9f → uint256
get_dy_underlying 0x85f11d1e → uint256
get_virtual_price 0xbb7b8b80 → uint256
initial_A 0x5409491a → uint256
initial_A_time 0x2081066c → uint256
isInitialized 0x392e53cd → bool
is_killed 0x9c868ac0 → bool
kill_deadline 0x2a426896 → uint256
owner 0x8da5cb5b → address
token 0xfc0c546a → address
Write Contract 18 functions
These functions modify contract state and require a wallet transaction to execute.
add_liquidity 0x0b4c7e4d
uint256[2] amounts
uint256 min_mint_amount
apply_new_fee 0x4f12fe97
No parameters
commit_new_fee 0x5b5a1467
uint256 new_fee
uint256 new_admin_fee
donate_admin_fees 0x524c3901
No parameters
exchange 0x5b41b908
uint256 i
uint256 j
uint256 dx
uint256 min_dy
initialize 0x4239b1c1
address[2] _coins
uint256 _A
uint256 _fee
uint256 _admin_fee
address _owner
address _LP
kill_me 0xe3698853
No parameters
ramp_A 0x3c157e64
uint256 _future_A
uint256 _future_time
remove_liquidity 0x5b36389c
uint256 _amount
uint256[2] min_amounts
remove_liquidity_imbalance 0xe3103273
uint256[2] amounts
uint256 max_burn_amount
remove_liquidity_one_coin 0xf1dc3cc9
uint256 _token_amount
uint256 i
uint256 min_amount
renounceOwnership 0x715018a6
No parameters
revert_new_parameters 0x226840fb
No parameters
set_bnb_gas 0xa139c370
uint256 _bnb_gas
stop_rampget_A 0xca8ca154
No parameters
transferOwnership 0xf2fde38b
address newOwner
unkill_me 0x3046f972
No parameters
withdraw_admin_fees 0x30c54085
No parameters
Token Balances (1)
View Transfers →Recent Transactions
No transactions found for this address