diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..a1c7c5444 --- /dev/null +++ b/.gitignore @@ -0,0 +1,332 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +**/Properties/launchSettings.json + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# SmartContracts +!**/SmartContracts/src/bin diff --git a/labs/algo-erc20-token/AdvancedAlgos.AlgoErc20Token.sln b/labs/algo-erc20-token/AdvancedAlgos.AlgoErc20Token.sln new file mode 100644 index 000000000..d496c206e --- /dev/null +++ b/labs/algo-erc20-token/AdvancedAlgos.AlgoErc20Token.sln @@ -0,0 +1,37 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28010.2048 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdvancedAlgos.AlgoErc20Token", "src\AdvancedAlgos.AlgoErc20Token\AdvancedAlgos.AlgoErc20Token.csproj", "{6916F713-4B7F-4B20-9205-BAEF417A0316}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdvancedAlgos.AlgoErc20Token.IntegrationTests", "test\AdvancedAlgos.AlgoErc20Token.IntegrationTests\AdvancedAlgos.AlgoErc20Token.IntegrationTests.csproj", "{4587034D-7844-4A36-9F49-FBA9702382E6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdvancedAlgos.AlgoErc20Token.EthClientExtensions", "src\AdvancedAlgos.AlgoErc20Token.EthClientExtensions\AdvancedAlgos.AlgoErc20Token.EthClientExtensions.csproj", "{A392DD77-CB11-464F-A0D6-77F4AC5BC79F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6916F713-4B7F-4B20-9205-BAEF417A0316}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6916F713-4B7F-4B20-9205-BAEF417A0316}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6916F713-4B7F-4B20-9205-BAEF417A0316}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6916F713-4B7F-4B20-9205-BAEF417A0316}.Release|Any CPU.Build.0 = Release|Any CPU + {4587034D-7844-4A36-9F49-FBA9702382E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4587034D-7844-4A36-9F49-FBA9702382E6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4587034D-7844-4A36-9F49-FBA9702382E6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4587034D-7844-4A36-9F49-FBA9702382E6}.Release|Any CPU.Build.0 = Release|Any CPU + {A392DD77-CB11-464F-A0D6-77F4AC5BC79F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A392DD77-CB11-464F-A0D6-77F4AC5BC79F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A392DD77-CB11-464F-A0D6-77F4AC5BC79F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A392DD77-CB11-464F-A0D6-77F4AC5BC79F}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {7273BF71-A9AA-472B-84A8-7658BB88D497} + EndGlobalSection +EndGlobal diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/AdvancedAlgos.AlgoErc20Token.EthClientExtensions.csproj b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/AdvancedAlgos.AlgoErc20Token.EthClientExtensions.csproj new file mode 100644 index 000000000..daa61afdf --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/AdvancedAlgos.AlgoErc20Token.EthClientExtensions.csproj @@ -0,0 +1,12 @@ + + + + netcoreapp2.1 + latest + + + + + + + diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/EthAccountFactory.cs b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/EthAccountFactory.cs new file mode 100644 index 000000000..6e022fdde --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/EthAccountFactory.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Nethereum.Hex.HexConvertors.Extensions; +using Nethereum.Signer; +using Nethereum.Web3.Accounts; + +namespace AdvancedAlgos.AlgoErc20Token.EthClientExtensions +{ + public static class EthAccountFactory + { + public static Account Create() + { + var accountEcKey = EthECKey.GenerateKey(); + var accountPrivateKey = accountEcKey.GetPrivateKeyAsBytes().ToHex(); + return new Account(accountPrivateKey); + } + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/Exceptions/TransactionRejectedException.cs b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/Exceptions/TransactionRejectedException.cs new file mode 100644 index 000000000..c18a8c0bf --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/Exceptions/TransactionRejectedException.cs @@ -0,0 +1,24 @@ +#pragma warning disable RCS1194 // Implement exception constructors. + +using System; +using System.Collections.Generic; +using System.Text; +using Nethereum.RPC.Eth.DTOs; + +namespace AdvancedAlgos.AlgoErc20Token.EthClientExtensions.Exceptions +{ + public class TransactionRejectedException : Exception + { + private const string ERROR_MESSAGE = "Failed to execute the transaction."; + + public TransactionRejectedException(TransactionReceipt transactionReceipt) + : base(ERROR_MESSAGE) + { + TransactionReceipt = transactionReceipt; + } + + public TransactionReceipt TransactionReceipt { get; } + + public static void Throw(TransactionReceipt transactionReceipt) => throw new TransactionRejectedException(transactionReceipt); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/Extensions/TransactionReceiptExtensions.cs b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/Extensions/TransactionReceiptExtensions.cs new file mode 100644 index 000000000..2ce8dec83 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/Extensions/TransactionReceiptExtensions.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Nethereum.RPC.Eth.DTOs; +using AdvancedAlgos.AlgoErc20Token.EthClientExtensions.Exceptions; + +namespace AdvancedAlgos.AlgoErc20Token.EthClientExtensions.Extensions +{ + public static class TransactionReceiptExtensions + { + public static void EnsureSucceededStatus(this TransactionReceipt transactionReceipt) + { + if (transactionReceipt.Status.Value != 1) TransactionRejectedException.Throw(transactionReceipt); + } + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/Reflection/AssemblyExtensions.cs b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/Reflection/AssemblyExtensions.cs new file mode 100644 index 000000000..219d7160b --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/Reflection/AssemblyExtensions.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Text; + +namespace AdvancedAlgos.AlgoErc20Token.EthClientExtensions.Reflection +{ + public static class AssemblyExtensions + { + public static string GetResourceString(this Assembly assembly, string resourceName, Encoding encoding = null) + { + using (var stream = assembly.GetManifestResourceStream(assembly.GetName().Name + "." + resourceName)) + using (var reader = new StreamReader(stream, encoding ?? Encoding.UTF8)) + { + return reader.ReadToEnd(); + } + } + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/SmartContract.cs b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/SmartContract.cs new file mode 100644 index 000000000..a2bebbef4 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token.EthClientExtensions/SmartContract.cs @@ -0,0 +1,97 @@ +using System; +using System.Numerics; +using System.Threading.Tasks; +using AdvancedAlgos.AlgoErc20Token.EthClientExtensions.Extensions; +using AdvancedAlgos.AlgoErc20Token.EthClientExtensions.Reflection; +using Nethereum.Contracts; +using Nethereum.Hex.HexTypes; +using Nethereum.RPC.Eth.DTOs; +using Nethereum.Web3; + +namespace AdvancedAlgos.AlgoErc20Token.EthClientExtensions +{ + public abstract class SmartContract where TContract : SmartContract, new() + { + private static readonly object _syncForResourceLoader = new object(); + + private static string _abi; + private static string _bin; + + public Web3 Web3 { get; private set; } + public string ContractAddress { get; private set; } + + protected abstract string AbiResourceName { get; } + protected abstract string BinResourceName { get; } + protected abstract BigInteger DeploymentGasUnits { get; } + + protected virtual void Initialize(Contract contractDescriptor) { } + + public static TContract Get(Web3 web3, string contractAddress) + { + var contractInstance = new TContract(); + + contractInstance.LoadAbiAndBin(); + + contractInstance.Web3 = web3; + contractInstance.ContractAddress = contractAddress; + + var contractDescriptor = web3.Eth.GetContract(_abi, contractAddress); + + contractInstance.Initialize(contractDescriptor); + + return contractInstance; + } + + public async Task DeployAsync(Web3 web3, BigInteger gasPrice, params object[] constructorParameters) + { + LoadAbiAndBin(); + + var transactionReceipt = await web3.Eth.DeployContract.SendRequestAndWaitForReceiptAsync( + _abi, + _bin, + web3.TransactionManager.Account.Address, + new HexBigInteger(DeploymentGasUnits), + new HexBigInteger(gasPrice), + null, + null, + constructorParameters); + + transactionReceipt.EnsureSucceededStatus(); + + var contractDescriptor = web3.Eth.GetContract(_abi, transactionReceipt.ContractAddress); + + Initialize(contractDescriptor); + + Web3 = web3; + ContractAddress = transactionReceipt.ContractAddress; + + return transactionReceipt; + } + + protected async Task InvokeAsync(Function function, BigInteger gasUnits, BigInteger gasPrice, params object[] parameters) + { + var transactionReceipt = await function.SendTransactionAndWaitForReceiptAsync( + Web3.TransactionManager.Account.Address, + new HexBigInteger(gasUnits), + new HexBigInteger(gasPrice), + null, + null, + parameters); + + transactionReceipt.EnsureSucceededStatus(); + + return transactionReceipt; + } + + private void LoadAbiAndBin() + { + lock (_syncForResourceLoader) + { + if (_abi != null) return; + + _abi = GetType().Assembly.GetResourceString(AbiResourceName); + _bin = GetType().Assembly.GetResourceString(BinResourceName); + } + } + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/AdvancedAlgos.AlgoErc20Token.csproj b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/AdvancedAlgos.AlgoErc20Token.csproj new file mode 100644 index 000000000..bc5df3e67 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/AdvancedAlgos.AlgoErc20Token.csproj @@ -0,0 +1,23 @@ + + + + netcoreapp2.1 + latest + + + + + + + + + + + + + + + + + + diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/AlgoIntegralConverterExtensions.cs b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/AlgoIntegralConverterExtensions.cs new file mode 100644 index 000000000..b870cddaf --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/AlgoIntegralConverterExtensions.cs @@ -0,0 +1,25 @@ +#pragma warning disable EPS02 // Non-readonly struct used as in-parameter + +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Text; + +namespace AdvancedAlgos.AlgoErc20Token +{ + public static class AlgoIntegralConverterExtensions + { + public const byte TOKEN_DECIMALS = 18; + + public static readonly BigInteger TokenFactor = BigInteger.Pow(10, TOKEN_DECIMALS); + + public static BigInteger Algo(this in byte value) => value * TokenFactor; + public static BigInteger Algo(this in sbyte value) => value * TokenFactor; + public static BigInteger Algo(this in short value) => value * TokenFactor; + public static BigInteger Algo(this in ushort value) => value * TokenFactor; + public static BigInteger Algo(this in int value) => value * TokenFactor; + public static BigInteger Algo(this in uint value) => value * TokenFactor; + public static BigInteger Algo(this in long value) => value * TokenFactor; + public static BigInteger Algo(this in ulong value) => value * TokenFactor; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/AlgoTokenV1.cs b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/AlgoTokenV1.cs new file mode 100644 index 000000000..1f30aa237 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/AlgoTokenV1.cs @@ -0,0 +1,16 @@ +using System; +using System.Numerics; +using System.Threading.Tasks; +using AdvancedAlgos.AlgoErc20Token.EthClientExtensions; +using Nethereum.Contracts; +using Nethereum.RPC.Eth.DTOs; + +namespace AdvancedAlgos.AlgoErc20Token +{ + public class AlgoTokenV1 : Erc20Token + { + protected override string AbiResourceName => $"SmartContracts.src.bin.{nameof(AlgoTokenV1)}.abi"; + protected override string BinResourceName => $"SmartContracts.src.bin.{nameof(AlgoTokenV1)}.bin"; + protected override BigInteger DeploymentGasUnits => 1200000; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/Erc20Token.cs b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/Erc20Token.cs new file mode 100644 index 000000000..5cb42bf9d --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/Erc20Token.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Text; +using System.Threading.Tasks; +using AdvancedAlgos.AlgoErc20Token.EthClientExtensions; +using Nethereum.Contracts; +using Nethereum.RPC.Eth.DTOs; + +namespace AdvancedAlgos.AlgoErc20Token +{ + public abstract class Erc20Token : SmartContract + where TContract : SmartContract, new() + { + private Function _transfer; + private Function _balanceOf; + private Function _pause; + private Function _unpause; + + protected override void Initialize(Contract contractDescriptor) + { + _transfer = contractDescriptor.GetFunction("transfer"); + _balanceOf = contractDescriptor.GetFunction("balanceOf"); + _pause = contractDescriptor.GetFunction("pause"); + _unpause = contractDescriptor.GetFunction("unpause"); + } + + public Task TransferAsync(BigInteger gasPrice, string to, BigInteger value) => + InvokeAsync(_transfer, 900000, gasPrice, to, value); + + public Task BalanceOfAsync(string owner) => + _balanceOf.CallAsync(owner); + + public Task PauseAsync(BigInteger gasPrice) => + InvokeAsync(_pause, 900000, gasPrice); + + public Task UnpauseAsync(BigInteger gasPrice) => + InvokeAsync(_unpause, 900000, gasPrice); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/AlgoTokenV1.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/AlgoTokenV1.sol new file mode 100644 index 000000000..0563b6d40 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/AlgoTokenV1.sol @@ -0,0 +1,17 @@ +pragma solidity ^0.4.24; + +import "./openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; +import "./openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol"; + +contract AlgoTokenV1 is ERC20, ERC20Detailed, ERC20Pausable { + + uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(18)); + + constructor() + ERC20Pausable() + ERC20Detailed("Algos", "ALGO", 18) + public + { + _mint(msg.sender, INITIAL_SUPPLY); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/bin/AlgoTokenV1.abi b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/bin/AlgoTokenV1.abi new file mode 100644 index 000000000..2b88afa15 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/bin/AlgoTokenV1.abi @@ -0,0 +1 @@ +[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"from","type":"address"},{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"INITIAL_SUPPLY","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"account","type":"address"}],"name":"isPauser","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"renouncePauser","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"account","type":"address"}],"name":"addPauser","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"owner","type":"address"},{"name":"spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"account","type":"address"}],"name":"PauserAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"account","type":"address"}],"name":"PauserRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"}] \ No newline at end of file diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/bin/AlgoTokenV1.bin b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/bin/AlgoTokenV1.bin new file mode 100644 index 000000000..12c6b6a7a --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/bin/AlgoTokenV1.bin @@ -0,0 +1 @@ +60806040523480156200001157600080fd5b50604080518082018252600581527f416c676f7300000000000000000000000000000000000000000000000000000060208083019182528351808501909452600484527f414c474f00000000000000000000000000000000000000000000000000000000908401528151919291601291620000909160039190620002c1565b508151620000a6906004906020850190620002c1565b506005805460ff191660ff9290921691909117905550620000d290503364010000000062000103810204565b6007805460ff19169055620000fd336b033b2e3c9fd0803ce800000064010000000062000155810204565b62000366565b6200011e60068264010000000062000b226200021482021704565b604051600160a060020a038216907f6719d08c1888103bea251a4ed56406bd0c3e69723c8a1686e017e7bbe159b6f890600090a250565b600160a060020a03821615156200016b57600080fd5b60025462000188908264010000000062000ac46200026f82021704565b600255600160a060020a038216600090815260208190526040902054620001be908264010000000062000ac46200026f82021704565b600160a060020a0383166000818152602081815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b600160a060020a03811615156200022a57600080fd5b6200023f828264010000000062000289810204565b156200024a57600080fd5b600160a060020a0316600090815260209190915260409020805460ff19166001179055565b6000828201838110156200028257600080fd5b9392505050565b6000600160a060020a0382161515620002a157600080fd5b50600160a060020a03166000908152602091909152604090205460ff1690565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200030457805160ff191683800117855562000334565b8280016001018555821562000334579182015b828111156200033457825182559160200191906001019062000317565b506200034292915062000346565b5090565b6200036391905b808211156200034257600081556001016200034d565b90565b610b9c80620003766000396000f3006080604052600436106100fb5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde038114610100578063095ea7b31461018a57806318160ddd146101c257806323b872dd146101e95780632ff2e9dc14610213578063313ce5671461022857806339509351146102535780633f4ba83a1461027757806346fbf68e1461028e5780635c975abb146102af5780636ef8d66d146102c457806370a08231146102d957806382dc1ec4146102fa5780638456cb591461031b57806395d89b4114610330578063a457c2d714610345578063a9059cbb14610369578063dd62ed3e1461038d575b600080fd5b34801561010c57600080fd5b506101156103b4565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561014f578181015183820152602001610137565b50505050905090810190601f16801561017c5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561019657600080fd5b506101ae600160a060020a036004351660243561044a565b604080519115158252519081900360200190f35b3480156101ce57600080fd5b506101d761046e565b60408051918252519081900360200190f35b3480156101f557600080fd5b506101ae600160a060020a0360043581169060243516604435610474565b34801561021f57600080fd5b506101d761049a565b34801561023457600080fd5b5061023d6104aa565b6040805160ff9092168252519081900360200190f35b34801561025f57600080fd5b506101ae600160a060020a03600435166024356104b3565b34801561028357600080fd5b5061028c6104d0565b005b34801561029a57600080fd5b506101ae600160a060020a0360043516610534565b3480156102bb57600080fd5b506101ae61054d565b3480156102d057600080fd5b5061028c610556565b3480156102e557600080fd5b506101d7600160a060020a0360043516610561565b34801561030657600080fd5b5061028c600160a060020a036004351661057c565b34801561032757600080fd5b5061028c61059c565b34801561033c57600080fd5b50610115610602565b34801561035157600080fd5b506101ae600160a060020a0360043516602435610663565b34801561037557600080fd5b506101ae600160a060020a0360043516602435610680565b34801561039957600080fd5b506101d7600160a060020a036004358116906024351661069d565b60038054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104405780601f1061041557610100808354040283529160200191610440565b820191906000526020600020905b81548152906001019060200180831161042357829003601f168201915b5050505050905090565b60075460009060ff161561045d57600080fd5b61046783836106c8565b9392505050565b60025490565b60075460009060ff161561048757600080fd5b610492848484610746565b949350505050565b6b033b2e3c9fd0803ce800000081565b60055460ff1690565b60075460009060ff16156104c657600080fd5b61046783836107e3565b6104d933610534565b15156104e457600080fd5b60075460ff1615156104f557600080fd5b6007805460ff191690556040805133815290517f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa9181900360200190a1565b600061054760068363ffffffff61089316565b92915050565b60075460ff1690565b61055f336108ca565b565b600160a060020a031660009081526020819052604090205490565b61058533610534565b151561059057600080fd5b61059981610912565b50565b6105a533610534565b15156105b057600080fd5b60075460ff16156105c057600080fd5b6007805460ff191660011790556040805133815290517f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2589181900360200190a1565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104405780601f1061041557610100808354040283529160200191610440565b60075460009060ff161561067657600080fd5b610467838361095a565b60075460009060ff161561069357600080fd5b61046783836109a5565b600160a060020a03918216600090815260016020908152604080832093909416825291909152205490565b6000600160a060020a03831615156106df57600080fd5b336000818152600160209081526040808320600160a060020a03881680855290835292819020869055805186815290519293927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a350600192915050565b600160a060020a038316600090815260016020908152604080832033845290915281205482111561077657600080fd5b600160a060020a03841660009081526001602090815260408083203384529091529020546107aa908363ffffffff6109bb16565b600160a060020a03851660009081526001602090815260408083203384529091529020556107d98484846109d2565b5060019392505050565b6000600160a060020a03831615156107fa57600080fd5b336000908152600160209081526040808320600160a060020a038716845290915290205461082e908363ffffffff610ac416565b336000818152600160209081526040808320600160a060020a0389168085529083529281902085905580519485525191937f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929081900390910190a350600192915050565b6000600160a060020a03821615156108aa57600080fd5b50600160a060020a03166000908152602091909152604090205460ff1690565b6108db60068263ffffffff610ad616565b604051600160a060020a038216907fcd265ebaf09df2871cc7bd4133404a235ba12eff2041bb89d9c714a2621c7c7e90600090a250565b61092360068263ffffffff610b2216565b604051600160a060020a038216907f6719d08c1888103bea251a4ed56406bd0c3e69723c8a1686e017e7bbe159b6f890600090a250565b6000600160a060020a038316151561097157600080fd5b336000908152600160209081526040808320600160a060020a038716845290915290205461082e908363ffffffff6109bb16565b60006109b23384846109d2565b50600192915050565b600080838311156109cb57600080fd5b5050900390565b600160a060020a0383166000908152602081905260409020548111156109f757600080fd5b600160a060020a0382161515610a0c57600080fd5b600160a060020a038316600090815260208190526040902054610a35908263ffffffff6109bb16565b600160a060020a038085166000908152602081905260408082209390935590841681522054610a6a908263ffffffff610ac416565b600160a060020a038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b60008282018381101561046757600080fd5b600160a060020a0381161515610aeb57600080fd5b610af58282610893565b1515610b0057600080fd5b600160a060020a0316600090815260209190915260409020805460ff19169055565b600160a060020a0381161515610b3757600080fd5b610b418282610893565b15610b4b57600080fd5b600160a060020a0316600090815260209190915260409020805460ff191660011790555600a165627a7a723058202dd18facb88fce52397143655484bd6bb04ca8578eb8c0779511f9e8d97c55f20029 \ No newline at end of file diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/bin/AlgoTokenV1.json b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/bin/AlgoTokenV1.json new file mode 100644 index 000000000..e0b102ac5 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/bin/AlgoTokenV1.json @@ -0,0 +1,52 @@ +{ + "abi": "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"spender\",\"type\":\"address\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"from\",\"type\":\"address\"},{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"INITIAL_SUPPLY\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"spender\",\"type\":\"address\"},{\"name\":\"addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseAllowance\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"unpause\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"account\",\"type\":\"address\"}],\"name\":\"isPauser\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"renouncePauser\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"account\",\"type\":\"address\"}],\"name\":\"addPauser\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"spender\",\"type\":\"address\"},{\"name\":\"subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseAllowance\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"owner\",\"type\":\"address\"},{\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Paused\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Unpaused\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"account\",\"type\":\"address\"}],\"name\":\"PauserAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"account\",\"type\":\"address\"}],\"name\":\"PauserRemoved\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"}]", + "bytecode": "60806040523480156200001157600080fd5b50604080518082018252600581527f416c676f7300000000000000000000000000000000000000000000000000000060208083019182528351808501909452600484527f414c474f00000000000000000000000000000000000000000000000000000000908401528151919291601291620000909160039190620002c1565b508151620000a6906004906020850190620002c1565b506005805460ff191660ff9290921691909117905550620000d290503364010000000062000103810204565b6007805460ff19169055620000fd336b033b2e3c9fd0803ce800000064010000000062000155810204565b62000366565b6200011e60068264010000000062000b226200021482021704565b604051600160a060020a038216907f6719d08c1888103bea251a4ed56406bd0c3e69723c8a1686e017e7bbe159b6f890600090a250565b600160a060020a03821615156200016b57600080fd5b60025462000188908264010000000062000ac46200026f82021704565b600255600160a060020a038216600090815260208190526040902054620001be908264010000000062000ac46200026f82021704565b600160a060020a0383166000818152602081815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b600160a060020a03811615156200022a57600080fd5b6200023f828264010000000062000289810204565b156200024a57600080fd5b600160a060020a0316600090815260209190915260409020805460ff19166001179055565b6000828201838110156200028257600080fd5b9392505050565b6000600160a060020a0382161515620002a157600080fd5b50600160a060020a03166000908152602091909152604090205460ff1690565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200030457805160ff191683800117855562000334565b8280016001018555821562000334579182015b828111156200033457825182559160200191906001019062000317565b506200034292915062000346565b5090565b6200036391905b808211156200034257600081556001016200034d565b90565b610b9c80620003766000396000f3006080604052600436106100fb5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde038114610100578063095ea7b31461018a57806318160ddd146101c257806323b872dd146101e95780632ff2e9dc14610213578063313ce5671461022857806339509351146102535780633f4ba83a1461027757806346fbf68e1461028e5780635c975abb146102af5780636ef8d66d146102c457806370a08231146102d957806382dc1ec4146102fa5780638456cb591461031b57806395d89b4114610330578063a457c2d714610345578063a9059cbb14610369578063dd62ed3e1461038d575b600080fd5b34801561010c57600080fd5b506101156103b4565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561014f578181015183820152602001610137565b50505050905090810190601f16801561017c5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561019657600080fd5b506101ae600160a060020a036004351660243561044a565b604080519115158252519081900360200190f35b3480156101ce57600080fd5b506101d761046e565b60408051918252519081900360200190f35b3480156101f557600080fd5b506101ae600160a060020a0360043581169060243516604435610474565b34801561021f57600080fd5b506101d761049a565b34801561023457600080fd5b5061023d6104aa565b6040805160ff9092168252519081900360200190f35b34801561025f57600080fd5b506101ae600160a060020a03600435166024356104b3565b34801561028357600080fd5b5061028c6104d0565b005b34801561029a57600080fd5b506101ae600160a060020a0360043516610534565b3480156102bb57600080fd5b506101ae61054d565b3480156102d057600080fd5b5061028c610556565b3480156102e557600080fd5b506101d7600160a060020a0360043516610561565b34801561030657600080fd5b5061028c600160a060020a036004351661057c565b34801561032757600080fd5b5061028c61059c565b34801561033c57600080fd5b50610115610602565b34801561035157600080fd5b506101ae600160a060020a0360043516602435610663565b34801561037557600080fd5b506101ae600160a060020a0360043516602435610680565b34801561039957600080fd5b506101d7600160a060020a036004358116906024351661069d565b60038054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104405780601f1061041557610100808354040283529160200191610440565b820191906000526020600020905b81548152906001019060200180831161042357829003601f168201915b5050505050905090565b60075460009060ff161561045d57600080fd5b61046783836106c8565b9392505050565b60025490565b60075460009060ff161561048757600080fd5b610492848484610746565b949350505050565b6b033b2e3c9fd0803ce800000081565b60055460ff1690565b60075460009060ff16156104c657600080fd5b61046783836107e3565b6104d933610534565b15156104e457600080fd5b60075460ff1615156104f557600080fd5b6007805460ff191690556040805133815290517f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa9181900360200190a1565b600061054760068363ffffffff61089316565b92915050565b60075460ff1690565b61055f336108ca565b565b600160a060020a031660009081526020819052604090205490565b61058533610534565b151561059057600080fd5b61059981610912565b50565b6105a533610534565b15156105b057600080fd5b60075460ff16156105c057600080fd5b6007805460ff191660011790556040805133815290517f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2589181900360200190a1565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104405780601f1061041557610100808354040283529160200191610440565b60075460009060ff161561067657600080fd5b610467838361095a565b60075460009060ff161561069357600080fd5b61046783836109a5565b600160a060020a03918216600090815260016020908152604080832093909416825291909152205490565b6000600160a060020a03831615156106df57600080fd5b336000818152600160209081526040808320600160a060020a03881680855290835292819020869055805186815290519293927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a350600192915050565b600160a060020a038316600090815260016020908152604080832033845290915281205482111561077657600080fd5b600160a060020a03841660009081526001602090815260408083203384529091529020546107aa908363ffffffff6109bb16565b600160a060020a03851660009081526001602090815260408083203384529091529020556107d98484846109d2565b5060019392505050565b6000600160a060020a03831615156107fa57600080fd5b336000908152600160209081526040808320600160a060020a038716845290915290205461082e908363ffffffff610ac416565b336000818152600160209081526040808320600160a060020a0389168085529083529281902085905580519485525191937f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929081900390910190a350600192915050565b6000600160a060020a03821615156108aa57600080fd5b50600160a060020a03166000908152602091909152604090205460ff1690565b6108db60068263ffffffff610ad616565b604051600160a060020a038216907fcd265ebaf09df2871cc7bd4133404a235ba12eff2041bb89d9c714a2621c7c7e90600090a250565b61092360068263ffffffff610b2216565b604051600160a060020a038216907f6719d08c1888103bea251a4ed56406bd0c3e69723c8a1686e017e7bbe159b6f890600090a250565b6000600160a060020a038316151561097157600080fd5b336000908152600160209081526040808320600160a060020a038716845290915290205461082e908363ffffffff6109bb16565b60006109b23384846109d2565b50600192915050565b600080838311156109cb57600080fd5b5050900390565b600160a060020a0383166000908152602081905260409020548111156109f757600080fd5b600160a060020a0382161515610a0c57600080fd5b600160a060020a038316600090815260208190526040902054610a35908263ffffffff6109bb16565b600160a060020a038085166000908152602081905260408082209390935590841681522054610a6a908263ffffffff610ac416565b600160a060020a038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b60008282018381101561046757600080fd5b600160a060020a0381161515610aeb57600080fd5b610af58282610893565b1515610b0057600080fd5b600160a060020a0316600090815260209190915260409020805460ff19169055565b600160a060020a0381161515610b3757600080fd5b610b418282610893565b15610b4b57600080fd5b600160a060020a0316600090815260209190915260409020805460ff191660011790555600a165627a7a723058202dd18facb88fce52397143655484bd6bb04ca8578eb8c0779511f9e8d97c55f20029", + "functionHashes": { + "INITIAL_SUPPLY()": "2ff2e9dc", + "addPauser(address)": "82dc1ec4", + "allowance(address,address)": "dd62ed3e", + "approve(address,uint256)": "095ea7b3", + "balanceOf(address)": "70a08231", + "decimals()": "313ce567", + "decreaseAllowance(address,uint256)": "a457c2d7", + "increaseAllowance(address,uint256)": "39509351", + "isPauser(address)": "46fbf68e", + "name()": "06fdde03", + "pause()": "8456cb59", + "paused()": "5c975abb", + "renouncePauser()": "6ef8d66d", + "symbol()": "95d89b41", + "totalSupply()": "18160ddd", + "transfer(address,uint256)": "a9059cbb", + "transferFrom(address,address,uint256)": "23b872dd", + "unpause()": "3f4ba83a" + }, + "gasEstimates": { + "creation": [ + null, + 594400 + ], + "external": { + "INITIAL_SUPPLY()": 272, + "addPauser(address)": null, + "allowance(address,address)": 1082, + "approve(address,uint256)": 22732, + "balanceOf(address)": 851, + "decimals()": 509, + "decreaseAllowance(address,uint256)": null, + "increaseAllowance(address,uint256)": null, + "isPauser(address)": null, + "name()": null, + "pause()": null, + "paused()": 594, + "renouncePauser()": null, + "symbol()": null, + "totalSupply()": 428, + "transfer(address,uint256)": null, + "transferFrom(address,address,uint256)": null, + "unpause()": null + }, + "internal": {} + }, + "runtimeBytecode": "6080604052600436106100fb5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde038114610100578063095ea7b31461018a57806318160ddd146101c257806323b872dd146101e95780632ff2e9dc14610213578063313ce5671461022857806339509351146102535780633f4ba83a1461027757806346fbf68e1461028e5780635c975abb146102af5780636ef8d66d146102c457806370a08231146102d957806382dc1ec4146102fa5780638456cb591461031b57806395d89b4114610330578063a457c2d714610345578063a9059cbb14610369578063dd62ed3e1461038d575b600080fd5b34801561010c57600080fd5b506101156103b4565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561014f578181015183820152602001610137565b50505050905090810190601f16801561017c5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561019657600080fd5b506101ae600160a060020a036004351660243561044a565b604080519115158252519081900360200190f35b3480156101ce57600080fd5b506101d761046e565b60408051918252519081900360200190f35b3480156101f557600080fd5b506101ae600160a060020a0360043581169060243516604435610474565b34801561021f57600080fd5b506101d761049a565b34801561023457600080fd5b5061023d6104aa565b6040805160ff9092168252519081900360200190f35b34801561025f57600080fd5b506101ae600160a060020a03600435166024356104b3565b34801561028357600080fd5b5061028c6104d0565b005b34801561029a57600080fd5b506101ae600160a060020a0360043516610534565b3480156102bb57600080fd5b506101ae61054d565b3480156102d057600080fd5b5061028c610556565b3480156102e557600080fd5b506101d7600160a060020a0360043516610561565b34801561030657600080fd5b5061028c600160a060020a036004351661057c565b34801561032757600080fd5b5061028c61059c565b34801561033c57600080fd5b50610115610602565b34801561035157600080fd5b506101ae600160a060020a0360043516602435610663565b34801561037557600080fd5b506101ae600160a060020a0360043516602435610680565b34801561039957600080fd5b506101d7600160a060020a036004358116906024351661069d565b60038054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104405780601f1061041557610100808354040283529160200191610440565b820191906000526020600020905b81548152906001019060200180831161042357829003601f168201915b5050505050905090565b60075460009060ff161561045d57600080fd5b61046783836106c8565b9392505050565b60025490565b60075460009060ff161561048757600080fd5b610492848484610746565b949350505050565b6b033b2e3c9fd0803ce800000081565b60055460ff1690565b60075460009060ff16156104c657600080fd5b61046783836107e3565b6104d933610534565b15156104e457600080fd5b60075460ff1615156104f557600080fd5b6007805460ff191690556040805133815290517f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa9181900360200190a1565b600061054760068363ffffffff61089316565b92915050565b60075460ff1690565b61055f336108ca565b565b600160a060020a031660009081526020819052604090205490565b61058533610534565b151561059057600080fd5b61059981610912565b50565b6105a533610534565b15156105b057600080fd5b60075460ff16156105c057600080fd5b6007805460ff191660011790556040805133815290517f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2589181900360200190a1565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104405780601f1061041557610100808354040283529160200191610440565b60075460009060ff161561067657600080fd5b610467838361095a565b60075460009060ff161561069357600080fd5b61046783836109a5565b600160a060020a03918216600090815260016020908152604080832093909416825291909152205490565b6000600160a060020a03831615156106df57600080fd5b336000818152600160209081526040808320600160a060020a03881680855290835292819020869055805186815290519293927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a350600192915050565b600160a060020a038316600090815260016020908152604080832033845290915281205482111561077657600080fd5b600160a060020a03841660009081526001602090815260408083203384529091529020546107aa908363ffffffff6109bb16565b600160a060020a03851660009081526001602090815260408083203384529091529020556107d98484846109d2565b5060019392505050565b6000600160a060020a03831615156107fa57600080fd5b336000908152600160209081526040808320600160a060020a038716845290915290205461082e908363ffffffff610ac416565b336000818152600160209081526040808320600160a060020a0389168085529083529281902085905580519485525191937f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929081900390910190a350600192915050565b6000600160a060020a03821615156108aa57600080fd5b50600160a060020a03166000908152602091909152604090205460ff1690565b6108db60068263ffffffff610ad616565b604051600160a060020a038216907fcd265ebaf09df2871cc7bd4133404a235ba12eff2041bb89d9c714a2621c7c7e90600090a250565b61092360068263ffffffff610b2216565b604051600160a060020a038216907f6719d08c1888103bea251a4ed56406bd0c3e69723c8a1686e017e7bbe159b6f890600090a250565b6000600160a060020a038316151561097157600080fd5b336000908152600160209081526040808320600160a060020a038716845290915290205461082e908363ffffffff6109bb16565b60006109b23384846109d2565b50600192915050565b600080838311156109cb57600080fd5b5050900390565b600160a060020a0383166000908152602081905260409020548111156109f757600080fd5b600160a060020a0382161515610a0c57600080fd5b600160a060020a038316600090815260208190526040902054610a35908263ffffffff6109bb16565b600160a060020a038085166000908152602081905260408082209390935590841681522054610a6a908263ffffffff610ac416565b600160a060020a038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b60008282018381101561046757600080fd5b600160a060020a0381161515610aeb57600080fd5b610af58282610893565b1515610b0057600080fd5b600160a060020a0316600090815260209190915260409020805460ff19169055565b600160a060020a0381161515610b3757600080fd5b610b418282610893565b15610b4b57600080fd5b600160a060020a0316600090815260209190915260409020805460ff191660011790555600a165627a7a723058202dd18facb88fce52397143655484bd6bb04ca8578eb8c0779511f9e8d97c55f20029" +} \ No newline at end of file diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/.npmignore b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/.npmignore new file mode 100644 index 000000000..e792d8bc6 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/.npmignore @@ -0,0 +1,2 @@ +mocks +examples diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/ARCHITECTURE.md b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/ARCHITECTURE.md new file mode 100644 index 000000000..bfb6cff8d --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/ARCHITECTURE.md @@ -0,0 +1,27 @@ +## Architecture + +The following provides visibility into how OpenZeppelin's contracts are organized: + +- **access** - Smart contracts that enable functionality that can be used for selective restrictions and basic authorization control functions. +- **crowdsale** - A collection of smart contracts used to manage token crowdsales that allow investors to purchase tokens with ETH. Includes a base contract which implements fundamental crowdsale functionality in its simplest form. The base contract can be extended in order to satisfy your crowdsale’s specific requirements. + - **distribution** - Includes extensions of the base crowdsale contract which can be used to customize the completion of a crowdsale. + - **emission** - Includes extensions of the base crowdsale contract which can be used to mint and manage how tokens are issued to purchasers. + - **price** - Includes extensions of the crowdsale contract that can be used to manage changes in token prices. + - **validation** - Includes extensions of the crowdsale contract that can be used to enforce restraints and limit access to token purchases. +- **examples** - A collection of simple smart contracts that demonstrate how to add new features to base contracts through multiple inheritance. +- **introspection** - An interface that can be used to make a contract comply with the ERC-165 standard as well as a contract that implements ERC-165 using a lookup table. +- **lifecycle** - A collection of base contracts used to manage the existence and behavior of your contracts and their funds. +- **math** - Libraries with safety checks on operations that throw on errors. +- **mocks** - A collection of abstract contracts that are primarily used for unit testing. They also serve as good usage examples and demonstrate how to combine contracts with inheritance when developing your own custom applications. +- **ownership** - A collection of smart contracts that can be used to manage contract and token ownership +- **payment** - A collection of smart contracts that can be used to manage payments through escrow arrangements, withdrawals, and claims. Includes support for both single payees and multiple payees. +- **proposals** - A collection of smart contracts that reflect community Ethereum Improvement Proposals (EIPs). These contracts are under development and standardization. They are not recommended for production, but they are useful for experimentation with pending EIP standards. Go [here](https://github.com/OpenZeppelin/openzeppelin-solidity/wiki/ERC-Process) for more information. + +- **token** - A collection of approved ERC standard tokens -- their interfaces and implementations. + - **ERC20** - A standard interface for fungible tokens: + - *Interfaces* - Includes the ERC-20 token standard basic interface. I.e., what the contract’s ABI can represent. + - *Implementations* - Includes ERC-20 token implementations that include all required and some optional ERC-20 functionality. + - **ERC721** - A standard interface for non-fungible tokens + - *Interfaces* - Includes the ERC-721 token standard basic interface. I.e., what the contract’s ABI can represent. + - *Implementations* - Includes ERC-721 token implementations that include all required and some optional ERC-721 functionality. + diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/Roles.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/Roles.sol new file mode 100644 index 000000000..e3b97ddb7 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/Roles.sol @@ -0,0 +1,44 @@ +pragma solidity ^0.4.24; + +/** + * @title Roles + * @dev Library for managing addresses assigned to a Role. + */ +library Roles { + struct Role { + mapping (address => bool) bearer; + } + + /** + * @dev give an account access to this role + */ + function add(Role storage role, address account) internal { + require(account != address(0)); + require(!has(role, account)); + + role.bearer[account] = true; + } + + /** + * @dev remove an account's access to this role + */ + function remove(Role storage role, address account) internal { + require(account != address(0)); + require(has(role, account)); + + role.bearer[account] = false; + } + + /** + * @dev check if an account has this role + * @return bool + */ + function has(Role storage role, address account) + internal + view + returns (bool) + { + require(account != address(0)); + return role.bearer[account]; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/roles/CapperRole.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/roles/CapperRole.sol new file mode 100644 index 000000000..d6b2ba066 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/roles/CapperRole.sol @@ -0,0 +1,43 @@ +pragma solidity ^0.4.24; + +import "../Roles.sol"; + +contract CapperRole { + using Roles for Roles.Role; + + event CapperAdded(address indexed account); + event CapperRemoved(address indexed account); + + Roles.Role private cappers; + + constructor() internal { + _addCapper(msg.sender); + } + + modifier onlyCapper() { + require(isCapper(msg.sender)); + _; + } + + function isCapper(address account) public view returns (bool) { + return cappers.has(account); + } + + function addCapper(address account) public onlyCapper { + _addCapper(account); + } + + function renounceCapper() public { + _removeCapper(msg.sender); + } + + function _addCapper(address account) internal { + cappers.add(account); + emit CapperAdded(account); + } + + function _removeCapper(address account) internal { + cappers.remove(account); + emit CapperRemoved(account); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/roles/MinterRole.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/roles/MinterRole.sol new file mode 100644 index 000000000..57f4a5a80 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/roles/MinterRole.sol @@ -0,0 +1,43 @@ +pragma solidity ^0.4.24; + +import "../Roles.sol"; + +contract MinterRole { + using Roles for Roles.Role; + + event MinterAdded(address indexed account); + event MinterRemoved(address indexed account); + + Roles.Role private minters; + + constructor() internal { + _addMinter(msg.sender); + } + + modifier onlyMinter() { + require(isMinter(msg.sender)); + _; + } + + function isMinter(address account) public view returns (bool) { + return minters.has(account); + } + + function addMinter(address account) public onlyMinter { + _addMinter(account); + } + + function renounceMinter() public { + _removeMinter(msg.sender); + } + + function _addMinter(address account) internal { + minters.add(account); + emit MinterAdded(account); + } + + function _removeMinter(address account) internal { + minters.remove(account); + emit MinterRemoved(account); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/roles/PauserRole.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/roles/PauserRole.sol new file mode 100644 index 000000000..58bb6a313 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/roles/PauserRole.sol @@ -0,0 +1,43 @@ +pragma solidity ^0.4.24; + +import "../Roles.sol"; + +contract PauserRole { + using Roles for Roles.Role; + + event PauserAdded(address indexed account); + event PauserRemoved(address indexed account); + + Roles.Role private pausers; + + constructor() internal { + _addPauser(msg.sender); + } + + modifier onlyPauser() { + require(isPauser(msg.sender)); + _; + } + + function isPauser(address account) public view returns (bool) { + return pausers.has(account); + } + + function addPauser(address account) public onlyPauser { + _addPauser(account); + } + + function renouncePauser() public { + _removePauser(msg.sender); + } + + function _addPauser(address account) internal { + pausers.add(account); + emit PauserAdded(account); + } + + function _removePauser(address account) internal { + pausers.remove(account); + emit PauserRemoved(account); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/roles/SignerRole.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/roles/SignerRole.sol new file mode 100644 index 000000000..6a2bc602d --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/access/roles/SignerRole.sol @@ -0,0 +1,43 @@ +pragma solidity ^0.4.24; + +import "../Roles.sol"; + +contract SignerRole { + using Roles for Roles.Role; + + event SignerAdded(address indexed account); + event SignerRemoved(address indexed account); + + Roles.Role private signers; + + constructor() internal { + _addSigner(msg.sender); + } + + modifier onlySigner() { + require(isSigner(msg.sender)); + _; + } + + function isSigner(address account) public view returns (bool) { + return signers.has(account); + } + + function addSigner(address account) public onlySigner { + _addSigner(account); + } + + function renounceSigner() public { + _removeSigner(msg.sender); + } + + function _addSigner(address account) internal { + signers.add(account); + emit SignerAdded(account); + } + + function _removeSigner(address account) internal { + signers.remove(account); + emit SignerRemoved(account); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol new file mode 100644 index 000000000..a0c227607 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol @@ -0,0 +1,241 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/IERC20.sol"; +import "../math/SafeMath.sol"; +import "../token/ERC20/SafeERC20.sol"; +import "../utils/ReentrancyGuard.sol"; + +/** + * @title Crowdsale + * @dev Crowdsale is a base contract for managing a token crowdsale, + * allowing investors to purchase tokens with ether. This contract implements + * such functionality in its most fundamental form and can be extended to provide additional + * functionality and/or custom behavior. + * The external interface represents the basic interface for purchasing tokens, and conform + * the base architecture for crowdsales. They are *not* intended to be modified / overridden. + * The internal interface conforms the extensible and modifiable surface of crowdsales. Override + * the methods to add functionality. Consider using 'super' where appropriate to concatenate + * behavior. + */ +contract Crowdsale is ReentrancyGuard { + using SafeMath for uint256; + using SafeERC20 for IERC20; + + // The token being sold + IERC20 private _token; + + // Address where funds are collected + address private _wallet; + + // How many token units a buyer gets per wei. + // The rate is the conversion between wei and the smallest and indivisible token unit. + // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK + // 1 wei will give you 1 unit, or 0.001 TOK. + uint256 private _rate; + + // Amount of wei raised + uint256 private _weiRaised; + + /** + * Event for token purchase logging + * @param purchaser who paid for the tokens + * @param beneficiary who got the tokens + * @param value weis paid for purchase + * @param amount amount of tokens purchased + */ + event TokensPurchased( + address indexed purchaser, + address indexed beneficiary, + uint256 value, + uint256 amount + ); + + /** + * @param rate Number of token units a buyer gets per wei + * @dev The rate is the conversion between wei and the smallest and indivisible + * token unit. So, if you are using a rate of 1 with a ERC20Detailed token + * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. + * @param wallet Address where collected funds will be forwarded to + * @param token Address of the token being sold + */ + constructor(uint256 rate, address wallet, IERC20 token) internal { + require(rate > 0); + require(wallet != address(0)); + require(token != address(0)); + + _rate = rate; + _wallet = wallet; + _token = token; + } + + // ----------------------------------------- + // Crowdsale external interface + // ----------------------------------------- + + /** + * @dev fallback function ***DO NOT OVERRIDE*** + * Note that other contracts will transfer fund with a base gas stipend + * of 2300, which is not enough to call buyTokens. Consider calling + * buyTokens directly when purchasing tokens from a contract. + */ + function () external payable { + buyTokens(msg.sender); + } + + /** + * @return the token being sold. + */ + function token() public view returns(IERC20) { + return _token; + } + + /** + * @return the address where funds are collected. + */ + function wallet() public view returns(address) { + return _wallet; + } + + /** + * @return the number of token units a buyer gets per wei. + */ + function rate() public view returns(uint256) { + return _rate; + } + + /** + * @return the amount of wei raised. + */ + function weiRaised() public view returns (uint256) { + return _weiRaised; + } + + /** + * @dev low level token purchase ***DO NOT OVERRIDE*** + * This function has a non-reentrancy guard, so it shouldn't be called by + * another `nonReentrant` function. + * @param beneficiary Recipient of the token purchase + */ + function buyTokens(address beneficiary) public nonReentrant payable { + + uint256 weiAmount = msg.value; + _preValidatePurchase(beneficiary, weiAmount); + + // calculate token amount to be created + uint256 tokens = _getTokenAmount(weiAmount); + + // update state + _weiRaised = _weiRaised.add(weiAmount); + + _processPurchase(beneficiary, tokens); + emit TokensPurchased( + msg.sender, + beneficiary, + weiAmount, + tokens + ); + + _updatePurchasingState(beneficiary, weiAmount); + + _forwardFunds(); + _postValidatePurchase(beneficiary, weiAmount); + } + + // ----------------------------------------- + // Internal interface (extensible) + // ----------------------------------------- + + /** + * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. + * Example from CappedCrowdsale.sol's _preValidatePurchase method: + * super._preValidatePurchase(beneficiary, weiAmount); + * require(weiRaised().add(weiAmount) <= cap); + * @param beneficiary Address performing the token purchase + * @param weiAmount Value in wei involved in the purchase + */ + function _preValidatePurchase( + address beneficiary, + uint256 weiAmount + ) + internal + view + { + require(beneficiary != address(0)); + require(weiAmount != 0); + } + + /** + * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. + * @param beneficiary Address performing the token purchase + * @param weiAmount Value in wei involved in the purchase + */ + function _postValidatePurchase( + address beneficiary, + uint256 weiAmount + ) + internal + view + { + // optional override + } + + /** + * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. + * @param beneficiary Address performing the token purchase + * @param tokenAmount Number of tokens to be emitted + */ + function _deliverTokens( + address beneficiary, + uint256 tokenAmount + ) + internal + { + _token.safeTransfer(beneficiary, tokenAmount); + } + + /** + * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send tokens. + * @param beneficiary Address receiving the tokens + * @param tokenAmount Number of tokens to be purchased + */ + function _processPurchase( + address beneficiary, + uint256 tokenAmount + ) + internal + { + _deliverTokens(beneficiary, tokenAmount); + } + + /** + * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) + * @param beneficiary Address receiving the tokens + * @param weiAmount Value in wei involved in the purchase + */ + function _updatePurchasingState( + address beneficiary, + uint256 weiAmount + ) + internal + { + // optional override + } + + /** + * @dev Override to extend the way in which ether is converted to tokens. + * @param weiAmount Value in wei to be converted into tokens + * @return Number of tokens that can be purchased with the specified _weiAmount + */ + function _getTokenAmount(uint256 weiAmount) + internal view returns (uint256) + { + return weiAmount.mul(_rate); + } + + /** + * @dev Determines how ETH is stored/forwarded on purchases. + */ + function _forwardFunds() internal { + _wallet.transfer(msg.value); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol new file mode 100644 index 000000000..8add165da --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol @@ -0,0 +1,50 @@ +pragma solidity ^0.4.24; + +import "../../math/SafeMath.sol"; +import "../validation/TimedCrowdsale.sol"; + +/** + * @title FinalizableCrowdsale + * @dev Extension of Crowdsale with a one-off finalization action, where one + * can do extra work after finishing. + */ +contract FinalizableCrowdsale is TimedCrowdsale { + using SafeMath for uint256; + + bool private _finalized; + + event CrowdsaleFinalized(); + + constructor() internal { + _finalized = false; + } + + /** + * @return true if the crowdsale is finalized, false otherwise. + */ + function finalized() public view returns (bool) { + return _finalized; + } + + /** + * @dev Must be called after crowdsale ends, to do some extra finalization + * work. Calls the contract's finalization function. + */ + function finalize() public { + require(!_finalized); + require(hasClosed()); + + _finalized = true; + + _finalization(); + emit CrowdsaleFinalized(); + } + + /** + * @dev Can be overridden to add finalization logic. The overriding function + * should call super._finalization() to ensure the chain of finalization is + * executed entirely. + */ + function _finalization() internal { + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol new file mode 100644 index 000000000..b8c9ede77 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol @@ -0,0 +1,50 @@ +pragma solidity ^0.4.24; + +import "../validation/TimedCrowdsale.sol"; +import "../../math/SafeMath.sol"; + +/** + * @title PostDeliveryCrowdsale + * @dev Crowdsale that locks tokens from withdrawal until it ends. + */ +contract PostDeliveryCrowdsale is TimedCrowdsale { + using SafeMath for uint256; + + mapping(address => uint256) private _balances; + + constructor() internal {} + + /** + * @dev Withdraw tokens only after crowdsale ends. + * @param beneficiary Whose tokens will be withdrawn. + */ + function withdrawTokens(address beneficiary) public { + require(hasClosed()); + uint256 amount = _balances[beneficiary]; + require(amount > 0); + _balances[beneficiary] = 0; + _deliverTokens(beneficiary, amount); + } + + /** + * @return the balance of an account. + */ + function balanceOf(address account) public view returns(uint256) { + return _balances[account]; + } + + /** + * @dev Overrides parent by storing balances instead of issuing tokens right away. + * @param beneficiary Token purchaser + * @param tokenAmount Amount of tokens purchased + */ + function _processPurchase( + address beneficiary, + uint256 tokenAmount + ) + internal + { + _balances[beneficiary] = _balances[beneficiary].add(tokenAmount); + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/distribution/RefundableCrowdsale.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/distribution/RefundableCrowdsale.sol new file mode 100644 index 000000000..9b814cd7d --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/distribution/RefundableCrowdsale.sol @@ -0,0 +1,91 @@ +pragma solidity ^0.4.24; + +import "../../math/SafeMath.sol"; +import "./FinalizableCrowdsale.sol"; +import "../../payment/escrow/RefundEscrow.sol"; + +/** + * @title RefundableCrowdsale + * @dev Extension of Crowdsale contract that adds a funding goal, and + * the possibility of users getting a refund if goal is not met. + * WARNING: note that if you allow tokens to be traded before the goal + * is met, then an attack is possible in which the attacker purchases + * tokens from the crowdsale and when they sees that the goal is + * unlikely to be met, they sell their tokens (possibly at a discount). + * The attacker will be refunded when the crowdsale is finalized, and + * the users that purchased from them will be left with worthless + * tokens. There are many possible ways to avoid this, like making the + * the crowdsale inherit from PostDeliveryCrowdsale, or imposing + * restrictions on token trading until the crowdsale is finalized. + * This is being discussed in + * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/877 + * This contract will be updated when we agree on a general solution + * for this problem. + */ +contract RefundableCrowdsale is FinalizableCrowdsale { + using SafeMath for uint256; + + // minimum amount of funds to be raised in weis + uint256 private _goal; + + // refund escrow used to hold funds while crowdsale is running + RefundEscrow private _escrow; + + /** + * @dev Constructor, creates RefundEscrow. + * @param goal Funding goal + */ + constructor(uint256 goal) internal { + require(goal > 0); + _escrow = new RefundEscrow(wallet()); + _goal = goal; + } + + /** + * @return minimum amount of funds to be raised in wei. + */ + function goal() public view returns(uint256) { + return _goal; + } + + /** + * @dev Investors can claim refunds here if crowdsale is unsuccessful + * @param beneficiary Whose refund will be claimed. + */ + function claimRefund(address beneficiary) public { + require(finalized()); + require(!goalReached()); + + _escrow.withdraw(beneficiary); + } + + /** + * @dev Checks whether funding goal was reached. + * @return Whether funding goal was reached + */ + function goalReached() public view returns (bool) { + return weiRaised() >= _goal; + } + + /** + * @dev escrow finalization task, called when finalize() is called + */ + function _finalization() internal { + if (goalReached()) { + _escrow.close(); + _escrow.beneficiaryWithdraw(); + } else { + _escrow.enableRefunds(); + } + + super._finalization(); + } + + /** + * @dev Overrides Crowdsale fund forwarding, sending funds to escrow. + */ + function _forwardFunds() internal { + _escrow.deposit.value(msg.value)(msg.sender); + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/emission/AllowanceCrowdsale.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/emission/AllowanceCrowdsale.sol new file mode 100644 index 000000000..346275c7d --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/emission/AllowanceCrowdsale.sol @@ -0,0 +1,59 @@ +pragma solidity ^0.4.24; + +import "../Crowdsale.sol"; +import "../../token/ERC20/IERC20.sol"; +import "../../token/ERC20/SafeERC20.sol"; +import "../../math/SafeMath.sol"; +import "../../math/Math.sol"; + +/** + * @title AllowanceCrowdsale + * @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale. + */ +contract AllowanceCrowdsale is Crowdsale { + using SafeMath for uint256; + using SafeERC20 for IERC20; + + address private _tokenWallet; + + /** + * @dev Constructor, takes token wallet address. + * @param tokenWallet Address holding the tokens, which has approved allowance to the crowdsale + */ + constructor(address tokenWallet) internal { + require(tokenWallet != address(0)); + _tokenWallet = tokenWallet; + } + + /** + * @return the address of the wallet that will hold the tokens. + */ + function tokenWallet() public view returns(address) { + return _tokenWallet; + } + + /** + * @dev Checks the amount of tokens left in the allowance. + * @return Amount of tokens left in the allowance + */ + function remainingTokens() public view returns (uint256) { + return Math.min( + token().balanceOf(_tokenWallet), + token().allowance(_tokenWallet, this) + ); + } + + /** + * @dev Overrides parent behavior by transferring tokens from wallet. + * @param beneficiary Token purchaser + * @param tokenAmount Amount of tokens purchased + */ + function _deliverTokens( + address beneficiary, + uint256 tokenAmount + ) + internal + { + token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol new file mode 100644 index 000000000..3ebea857d --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol @@ -0,0 +1,29 @@ +pragma solidity ^0.4.24; + +import "../Crowdsale.sol"; +import "../../token/ERC20/ERC20Mintable.sol"; + +/** + * @title MintedCrowdsale + * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. + * Token ownership should be transferred to MintedCrowdsale for minting. + */ +contract MintedCrowdsale is Crowdsale { + constructor() internal {} + + /** + * @dev Overrides delivery by minting tokens upon purchase. + * @param beneficiary Token purchaser + * @param tokenAmount Number of tokens to be minted + */ + function _deliverTokens( + address beneficiary, + uint256 tokenAmount + ) + internal + { + // Potentially dangerous assumption about the type of the token. + require( + ERC20Mintable(address(token())).mint(beneficiary, tokenAmount)); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/price/IncreasingPriceCrowdsale.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/price/IncreasingPriceCrowdsale.sol new file mode 100644 index 000000000..c86353c0f --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/price/IncreasingPriceCrowdsale.sol @@ -0,0 +1,81 @@ +pragma solidity ^0.4.24; + +import "../validation/TimedCrowdsale.sol"; +import "../../math/SafeMath.sol"; + +/** + * @title IncreasingPriceCrowdsale + * @dev Extension of Crowdsale contract that increases the price of tokens linearly in time. + * Note that what should be provided to the constructor is the initial and final _rates_, that is, + * the amount of tokens per wei contributed. Thus, the initial rate must be greater than the final rate. + */ +contract IncreasingPriceCrowdsale is TimedCrowdsale { + using SafeMath for uint256; + + uint256 private _initialRate; + uint256 private _finalRate; + + /** + * @dev Constructor, takes initial and final rates of tokens received per wei contributed. + * @param initialRate Number of tokens a buyer gets per wei at the start of the crowdsale + * @param finalRate Number of tokens a buyer gets per wei at the end of the crowdsale + */ + constructor(uint256 initialRate, uint256 finalRate) internal { + require(finalRate > 0); + require(initialRate > finalRate); + _initialRate = initialRate; + _finalRate = finalRate; + } + + /** + * The base rate function is overridden to revert, since this crowdsale doens't use it, and + * all calls to it are a mistake. + */ + function rate() public view returns(uint256) { + revert(); + } + + /** + * @return the initial rate of the crowdsale. + */ + function initialRate() public view returns(uint256) { + return _initialRate; + } + + /** + * @return the final rate of the crowdsale. + */ + function finalRate() public view returns (uint256) { + return _finalRate; + } + + /** + * @dev Returns the rate of tokens per wei at the present time. + * Note that, as price _increases_ with time, the rate _decreases_. + * @return The number of tokens a buyer gets per wei at a given time + */ + function getCurrentRate() public view returns (uint256) { + if (!isOpen()) { + return 0; + } + + // solium-disable-next-line security/no-block-members + uint256 elapsedTime = block.timestamp.sub(openingTime()); + uint256 timeRange = closingTime().sub(openingTime()); + uint256 rateRange = _initialRate.sub(_finalRate); + return _initialRate.sub(elapsedTime.mul(rateRange).div(timeRange)); + } + + /** + * @dev Overrides parent method taking into account variable rate. + * @param weiAmount The value in wei to be converted into tokens + * @return The number of tokens _weiAmount wei will buy at present time + */ + function _getTokenAmount(uint256 weiAmount) + internal view returns (uint256) + { + uint256 currentRate = getCurrentRate(); + return currentRate.mul(weiAmount); + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol new file mode 100644 index 000000000..4d9eb604d --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol @@ -0,0 +1,55 @@ +pragma solidity ^0.4.24; + +import "../../math/SafeMath.sol"; +import "../Crowdsale.sol"; + +/** + * @title CappedCrowdsale + * @dev Crowdsale with a limit for total contributions. + */ +contract CappedCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 private _cap; + + /** + * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. + * @param cap Max amount of wei to be contributed + */ + constructor(uint256 cap) internal { + require(cap > 0); + _cap = cap; + } + + /** + * @return the cap of the crowdsale. + */ + function cap() public view returns(uint256) { + return _cap; + } + + /** + * @dev Checks whether the cap has been reached. + * @return Whether the cap was reached + */ + function capReached() public view returns (bool) { + return weiRaised() >= _cap; + } + + /** + * @dev Extend parent behavior requiring purchase to respect the funding cap. + * @param beneficiary Token purchaser + * @param weiAmount Amount of wei contributed + */ + function _preValidatePurchase( + address beneficiary, + uint256 weiAmount + ) + internal + view + { + super._preValidatePurchase(beneficiary, weiAmount); + require(weiRaised().add(weiAmount) <= _cap); + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/validation/IndividuallyCappedCrowdsale.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/validation/IndividuallyCappedCrowdsale.sol new file mode 100644 index 000000000..5a5d4e317 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/validation/IndividuallyCappedCrowdsale.sol @@ -0,0 +1,81 @@ +pragma solidity ^0.4.24; + +import "../../math/SafeMath.sol"; +import "../Crowdsale.sol"; +import "../../access/roles/CapperRole.sol"; + +/** + * @title IndividuallyCappedCrowdsale + * @dev Crowdsale with per-beneficiary caps. + */ +contract IndividuallyCappedCrowdsale is Crowdsale, CapperRole { + using SafeMath for uint256; + + mapping(address => uint256) private _contributions; + mapping(address => uint256) private _caps; + + constructor() internal {} + + /** + * @dev Sets a specific beneficiary's maximum contribution. + * @param beneficiary Address to be capped + * @param cap Wei limit for individual contribution + */ + function setCap(address beneficiary, uint256 cap) external onlyCapper { + _caps[beneficiary] = cap; + } + + /** + * @dev Returns the cap of a specific beneficiary. + * @param beneficiary Address whose cap is to be checked + * @return Current cap for individual beneficiary + */ + function getCap(address beneficiary) public view returns (uint256) { + return _caps[beneficiary]; + } + + /** + * @dev Returns the amount contributed so far by a specific beneficiary. + * @param beneficiary Address of contributor + * @return Beneficiary contribution so far + */ + function getContribution(address beneficiary) + public view returns (uint256) + { + return _contributions[beneficiary]; + } + + /** + * @dev Extend parent behavior requiring purchase to respect the beneficiary's funding cap. + * @param beneficiary Token purchaser + * @param weiAmount Amount of wei contributed + */ + function _preValidatePurchase( + address beneficiary, + uint256 weiAmount + ) + internal + view + { + super._preValidatePurchase(beneficiary, weiAmount); + require( + _contributions[beneficiary].add(weiAmount) <= _caps[beneficiary]); + } + + /** + * @dev Extend parent behavior to update beneficiary contributions + * @param beneficiary Token purchaser + * @param weiAmount Amount of wei contributed + */ + function _updatePurchasingState( + address beneficiary, + uint256 weiAmount + ) + internal + { + super._updatePurchasingState(beneficiary, weiAmount); + _contributions[beneficiary] = _contributions[beneficiary].add( + weiAmount); + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol new file mode 100644 index 000000000..73d6a5c0f --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol @@ -0,0 +1,85 @@ +pragma solidity ^0.4.24; + +import "../../math/SafeMath.sol"; +import "../Crowdsale.sol"; + +/** + * @title TimedCrowdsale + * @dev Crowdsale accepting contributions only within a time frame. + */ +contract TimedCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 private _openingTime; + uint256 private _closingTime; + + /** + * @dev Reverts if not in crowdsale time range. + */ + modifier onlyWhileOpen { + require(isOpen()); + _; + } + + /** + * @dev Constructor, takes crowdsale opening and closing times. + * @param openingTime Crowdsale opening time + * @param closingTime Crowdsale closing time + */ + constructor(uint256 openingTime, uint256 closingTime) internal { + // solium-disable-next-line security/no-block-members + require(openingTime >= block.timestamp); + require(closingTime > openingTime); + + _openingTime = openingTime; + _closingTime = closingTime; + } + + /** + * @return the crowdsale opening time. + */ + function openingTime() public view returns(uint256) { + return _openingTime; + } + + /** + * @return the crowdsale closing time. + */ + function closingTime() public view returns(uint256) { + return _closingTime; + } + + /** + * @return true if the crowdsale is open, false otherwise. + */ + function isOpen() public view returns (bool) { + // solium-disable-next-line security/no-block-members + return block.timestamp >= _openingTime && block.timestamp <= _closingTime; + } + + /** + * @dev Checks whether the period in which the crowdsale is open has already elapsed. + * @return Whether crowdsale period has elapsed + */ + function hasClosed() public view returns (bool) { + // solium-disable-next-line security/no-block-members + return block.timestamp > _closingTime; + } + + /** + * @dev Extend parent behavior requiring to be within contributing period + * @param beneficiary Token purchaser + * @param weiAmount Amount of wei contributed + */ + function _preValidatePurchase( + address beneficiary, + uint256 weiAmount + ) + internal + onlyWhileOpen + view + { + super._preValidatePurchase(beneficiary, weiAmount); + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/cryptography/ECDSA.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/cryptography/ECDSA.sol new file mode 100644 index 000000000..71c0e41ed --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/cryptography/ECDSA.sol @@ -0,0 +1,71 @@ +pragma solidity ^0.4.24; + +/** + * @title Elliptic curve signature operations + * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d + * TODO Remove this library once solidity supports passing a signature to ecrecover. + * See https://github.com/ethereum/solidity/issues/864 + */ + +library ECDSA { + + /** + * @dev Recover signer address from a message by using their signature + * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. + * @param signature bytes signature, the signature is generated using web3.eth.sign() + */ + function recover(bytes32 hash, bytes signature) + internal + pure + returns (address) + { + bytes32 r; + bytes32 s; + uint8 v; + + // Check the signature length + if (signature.length != 65) { + return (address(0)); + } + + // Divide the signature in r, s and v variables + // ecrecover takes the signature parameters, and the only way to get them + // currently is to use assembly. + // solium-disable-next-line security/no-inline-assembly + assembly { + r := mload(add(signature, 0x20)) + s := mload(add(signature, 0x40)) + v := byte(0, mload(add(signature, 0x60))) + } + + // Version of signature should be 27 or 28, but 0 and 1 are also possible versions + if (v < 27) { + v += 27; + } + + // If the version is correct return the signer address + if (v != 27 && v != 28) { + return (address(0)); + } else { + // solium-disable-next-line arg-overflow + return ecrecover(hash, v, r, s); + } + } + + /** + * toEthSignedMessageHash + * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" + * and hash the result + */ + function toEthSignedMessageHash(bytes32 hash) + internal + pure + returns (bytes32) + { + // 32 is the length in bytes of hash, + // enforced by the type signature above + return keccak256( + abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) + ); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/cryptography/MerkleProof.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/cryptography/MerkleProof.sol new file mode 100644 index 000000000..a0c304c57 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/cryptography/MerkleProof.sol @@ -0,0 +1,42 @@ +pragma solidity ^0.4.24; + +/** + * @title MerkleProof + * @dev Merkle proof verification based on + * https://github.com/ameensol/merkle-tree-solidity/blob/master/src/MerkleProof.sol + */ +library MerkleProof { + /** + * @dev Verifies a Merkle proof proving the existence of a leaf in a Merkle tree. Assumes that each pair of leaves + * and each pair of pre-images are sorted. + * @param proof Merkle proof containing sibling hashes on the branch from the leaf to the root of the Merkle tree + * @param root Merkle root + * @param leaf Leaf of Merkle tree + */ + function verify( + bytes32[] proof, + bytes32 root, + bytes32 leaf + ) + internal + pure + returns (bool) + { + bytes32 computedHash = leaf; + + for (uint256 i = 0; i < proof.length; i++) { + bytes32 proofElement = proof[i]; + + if (computedHash < proofElement) { + // Hash(current computed hash + current element of the proof) + computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); + } else { + // Hash(current element of the proof + current computed hash) + computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); + } + } + + // Check if the computed hash (root) is equal to the provided root + return computedHash == root; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/.gitkeep b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/Counter.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/Counter.sol new file mode 100644 index 000000000..3557bd744 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/Counter.sol @@ -0,0 +1,28 @@ +pragma solidity ^0.4.24; + +/** + * @title Counter + * @author Matt Condon (@shrugs) + * @dev Provides an incrementing uint256 id acquired by the `Counter#next` getter. + * Use this for issuing ERC721 ids or keeping track of request ids, anything you want, really. + * + * Include with `using Counter for Counter.Counter;` + * @notice Does not allow an Id of 0, which is popularly used to signify a null state in solidity. + * Does not protect from overflows, but if you have 2^256 ids, you have other problems. + * (But actually, it's generally impossible to increment a counter this many times, energy wise + * so it's not something you have to worry about.) + */ +library Counter { + + struct Counter { + uint256 current; // default: 0 + } + + function next(Counter storage index) + internal + returns (uint256) + { + index.current += 1; + return index.current; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/ERC1046/TokenMetadata.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/ERC1046/TokenMetadata.sol new file mode 100644 index 000000000..9057711d9 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/ERC1046/TokenMetadata.sol @@ -0,0 +1,27 @@ +pragma solidity ^0.4.24; + +import "../../token/ERC20/IERC20.sol"; + +/** + * @title ERC-1047 Token Metadata + * @dev See https://eips.ethereum.org/EIPS/eip-1046 + * @dev tokenURI must respond with a URI that implements https://eips.ethereum.org/EIPS/eip-1047 + * @dev TODO - update https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC721/IERC721.sol#L17 when 1046 is finalized + */ +contract ERC20TokenMetadata is IERC20 { + function tokenURI() external view returns (string); +} + +contract ERC20WithMetadata is ERC20TokenMetadata { + string private _tokenURI; + + constructor(string tokenURI) + public + { + _tokenURI = tokenURI; + } + + function tokenURI() external view returns (string) { + return _tokenURI; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/ERC20Migrator.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/ERC20Migrator.sol new file mode 100644 index 000000000..44ed16423 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/ERC20Migrator.sol @@ -0,0 +1,100 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/IERC20.sol"; +import "../token/ERC20/ERC20Mintable.sol"; +import "../token/ERC20/SafeERC20.sol"; +import "../math/Math.sol"; + +/** + * @title ERC20Migrator + * @dev This contract can be used to migrate an ERC20 token from one + * contract to another, where each token holder has to opt-in to the migration. + * To opt-in, users must approve for this contract the number of tokens they + * want to migrate. Once the allowance is set up, anyone can trigger the + * migration to the new token contract. In this way, token holders "turn in" + * their old balance and will be minted an equal amount in the new token. + * The new token contract must be mintable. For the precise interface refer to + * OpenZeppelin's ERC20Mintable, but the only functions that are needed are + * `isMinter(address)` and `mint(address, amount)`. The migrator will check + * that it is a minter for the token. + * The balance from the legacy token will be transfered to the migrator, as it + * is migrated, and remain there forever. + * Although this contract can be used in many different scenarios, the main + * motivation was to provide a way to migrate ERC20 tokens into an upgradeable + * version of it using ZeppelinOS. To read more about how this can be done + * using this implementation, please follow the official documentation site of + * ZeppelinOS: https://docs.zeppelinos.org/docs/erc20_onboarding.html + * Example of usage: + * ``` + * const migrator = await ERC20Migrator.new(legacyToken.address); + * await newToken.addMinter(migrator.address); + * await migrator.beginMigration(newToken.address); + * ``` + */ +contract ERC20Migrator { + using SafeERC20 for IERC20; + + /// Address of the old token contract + IERC20 private _legacyToken; + + /// Address of the new token contract + ERC20Mintable private _newToken; + + /** + * @param legacyToken address of the old token contract + */ + constructor(IERC20 legacyToken) public { + require(legacyToken != address(0)); + _legacyToken = legacyToken; + } + + /** + * @dev Returns the legacy token that is being migrated. + */ + function legacyToken() public view returns (IERC20) { + return _legacyToken; + } + + /** + * @dev Returns the new token to which we are migrating. + */ + function newToken() public view returns (IERC20) { + return _newToken; + } + + /** + * @dev Begins the migration by setting which is the new token that will be + * minted. This contract must be a minter for the new token. + * @param newToken the token that will be minted + */ + function beginMigration(ERC20Mintable newToken) public { + require(_newToken == address(0)); + require(newToken != address(0)); + require(newToken.isMinter(this)); + + _newToken = newToken; + } + + /** + * @dev Transfers part of an account's balance in the old token to this + * contract, and mints the same amount of new tokens for that account. + * @param account whose tokens will be migrated + * @param amount amount of tokens to be migrated + */ + function migrate(address account, uint256 amount) public { + _legacyToken.safeTransferFrom(account, this, amount); + _newToken.mint(account, amount); + } + + /** + * @dev Transfers all of an account's allowed balance in the old token to + * this contract, and mints the same amount of new tokens for that account. + * @param account whose tokens will be migrated + */ + function migrateAll(address account) public { + uint256 balance = _legacyToken.balanceOf(account); + uint256 allowance = _legacyToken.allowance(account, this); + uint256 amount = Math.min(balance, allowance); + migrate(account, amount); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/SignatureBouncer.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/SignatureBouncer.sol new file mode 100644 index 000000000..2cd600b35 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/SignatureBouncer.sol @@ -0,0 +1,146 @@ +pragma solidity ^0.4.24; + +import "../access/roles/SignerRole.sol"; +import "../cryptography/ECDSA.sol"; + +/** + * @title SignatureBouncer + * @author PhABC, Shrugs and aflesher + * @dev SignatureBouncer allows users to submit a signature as a permission to + * do an action. + * If the signature is from one of the authorized signer addresses, the + * signature is valid. + * Note that SignatureBouncer offers no protection against replay attacks, users + * must add this themselves! + * + * Signer addresses can be individual servers signing grants or different + * users within a decentralized club that have permission to invite other + * members. This technique is useful for whitelists and airdrops; instead of + * putting all valid addresses on-chain, simply sign a grant of the form + * keccak256(abi.encodePacked(`:contractAddress` + `:granteeAddress`)) using a + * valid signer address. + * Then restrict access to your crowdsale/whitelist/airdrop using the + * `onlyValidSignature` modifier (or implement your own using _isValidSignature). + * In addition to `onlyValidSignature`, `onlyValidSignatureAndMethod` and + * `onlyValidSignatureAndData` can be used to restrict access to only a given + * method or a given method with given parameters respectively. + * See the tests in SignatureBouncer.test.js for specific usage examples. + * + * @notice A method that uses the `onlyValidSignatureAndData` modifier must make + * the _signature parameter the "last" parameter. You cannot sign a message that + * has its own signature in it so the last 128 bytes of msg.data (which + * represents the length of the _signature data and the _signaature data itself) + * is ignored when validating. Also non fixed sized parameters make constructing + * the data in the signature much more complex. + * See https://ethereum.stackexchange.com/a/50616 for more details. + */ +contract SignatureBouncer is SignerRole { + using ECDSA for bytes32; + + // Function selectors are 4 bytes long, as documented in + // https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector + uint256 private constant _METHOD_ID_SIZE = 4; + // Signature size is 65 bytes (tightly packed v + r + s), but gets padded to 96 bytes + uint256 private constant _SIGNATURE_SIZE = 96; + + constructor() internal {} + + /** + * @dev requires that a valid signature of a signer was provided + */ + modifier onlyValidSignature(bytes signature) + { + require(_isValidSignature(msg.sender, signature)); + _; + } + + /** + * @dev requires that a valid signature with a specifed method of a signer was provided + */ + modifier onlyValidSignatureAndMethod(bytes signature) + { + require(_isValidSignatureAndMethod(msg.sender, signature)); + _; + } + + /** + * @dev requires that a valid signature with a specifed method and params of a signer was provided + */ + modifier onlyValidSignatureAndData(bytes signature) + { + require(_isValidSignatureAndData(msg.sender, signature)); + _; + } + + /** + * @dev is the signature of `this + sender` from a signer? + * @return bool + */ + function _isValidSignature(address account, bytes signature) + internal + view + returns (bool) + { + return _isValidDataHash( + keccak256(abi.encodePacked(address(this), account)), + signature + ); + } + + /** + * @dev is the signature of `this + sender + methodId` from a signer? + * @return bool + */ + function _isValidSignatureAndMethod(address account, bytes signature) + internal + view + returns (bool) + { + bytes memory data = new bytes(_METHOD_ID_SIZE); + for (uint i = 0; i < data.length; i++) { + data[i] = msg.data[i]; + } + return _isValidDataHash( + keccak256(abi.encodePacked(address(this), account, data)), + signature + ); + } + + /** + * @dev is the signature of `this + sender + methodId + params(s)` from a signer? + * @notice the signature parameter of the method being validated must be the "last" parameter + * @return bool + */ + function _isValidSignatureAndData(address account, bytes signature) + internal + view + returns (bool) + { + require(msg.data.length > _SIGNATURE_SIZE); + bytes memory data = new bytes(msg.data.length - _SIGNATURE_SIZE); + for (uint i = 0; i < data.length; i++) { + data[i] = msg.data[i]; + } + return _isValidDataHash( + keccak256(abi.encodePacked(address(this), account, data)), + signature + ); + } + + /** + * @dev internal function to convert a hash to an eth signed message + * and then recover the signature and check it against the signer role + * @return bool + */ + function _isValidDataHash(bytes32 hash, bytes signature) + internal + view + returns (bool) + { + address signer = hash + .toEthSignedMessageHash() + .recover(signature); + + return signer != address(0) && isSigner(signer); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/TokenVesting.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/TokenVesting.sol new file mode 100644 index 000000000..2f5fd2fdc --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/drafts/TokenVesting.sol @@ -0,0 +1,175 @@ +/* solium-disable security/no-block-members */ + +pragma solidity ^0.4.24; + +import "../token/ERC20/SafeERC20.sol"; +import "../ownership/Ownable.sol"; +import "../math/SafeMath.sol"; + +/** + * @title TokenVesting + * @dev A token holder contract that can release its token balance gradually like a + * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the + * owner. + */ +contract TokenVesting is Ownable { + using SafeMath for uint256; + using SafeERC20 for IERC20; + + event TokensReleased(address token, uint256 amount); + event TokenVestingRevoked(address token); + + // beneficiary of tokens after they are released + address private _beneficiary; + + uint256 private _cliff; + uint256 private _start; + uint256 private _duration; + + bool private _revocable; + + mapping (address => uint256) private _released; + mapping (address => bool) private _revoked; + + /** + * @dev Creates a vesting contract that vests its balance of any ERC20 token to the + * beneficiary, gradually in a linear fashion until start + duration. By then all + * of the balance will have vested. + * @param beneficiary address of the beneficiary to whom vested tokens are transferred + * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest + * @param start the time (as Unix time) at which point vesting starts + * @param duration duration in seconds of the period in which the tokens will vest + * @param revocable whether the vesting is revocable or not + */ + constructor( + address beneficiary, + uint256 start, + uint256 cliffDuration, + uint256 duration, + bool revocable + ) + public + { + require(beneficiary != address(0)); + require(cliffDuration <= duration); + require(duration > 0); + require(start.add(duration) > block.timestamp); + + _beneficiary = beneficiary; + _revocable = revocable; + _duration = duration; + _cliff = start.add(cliffDuration); + _start = start; + } + + /** + * @return the beneficiary of the tokens. + */ + function beneficiary() public view returns(address) { + return _beneficiary; + } + + /** + * @return the cliff time of the token vesting. + */ + function cliff() public view returns(uint256) { + return _cliff; + } + + /** + * @return the start time of the token vesting. + */ + function start() public view returns(uint256) { + return _start; + } + + /** + * @return the duration of the token vesting. + */ + function duration() public view returns(uint256) { + return _duration; + } + + /** + * @return true if the vesting is revocable. + */ + function revocable() public view returns(bool) { + return _revocable; + } + + /** + * @return the amount of the token released. + */ + function released(address token) public view returns(uint256) { + return _released[token]; + } + + /** + * @return true if the token is revoked. + */ + function revoked(address token) public view returns(bool) { + return _revoked[token]; + } + + /** + * @notice Transfers vested tokens to beneficiary. + * @param token ERC20 token which is being vested + */ + function release(IERC20 token) public { + uint256 unreleased = _releasableAmount(token); + + require(unreleased > 0); + + _released[token] = _released[token].add(unreleased); + + token.safeTransfer(_beneficiary, unreleased); + + emit TokensReleased(token, unreleased); + } + + /** + * @notice Allows the owner to revoke the vesting. Tokens already vested + * remain in the contract, the rest are returned to the owner. + * @param token ERC20 token which is being vested + */ + function revoke(IERC20 token) public onlyOwner { + require(_revocable); + require(!_revoked[token]); + + uint256 balance = token.balanceOf(address(this)); + + uint256 unreleased = _releasableAmount(token); + uint256 refund = balance.sub(unreleased); + + _revoked[token] = true; + + token.safeTransfer(owner(), refund); + + emit TokenVestingRevoked(token); + } + + /** + * @dev Calculates the amount that has already vested but hasn't been released yet. + * @param token ERC20 token which is being vested + */ + function _releasableAmount(IERC20 token) private view returns (uint256) { + return _vestedAmount(token).sub(_released[token]); + } + + /** + * @dev Calculates the amount that has already vested. + * @param token ERC20 token which is being vested + */ + function _vestedAmount(IERC20 token) private view returns (uint256) { + uint256 currentBalance = token.balanceOf(this); + uint256 totalBalance = currentBalance.add(_released[token]); + + if (block.timestamp < _cliff) { + return 0; + } else if (block.timestamp >= _start.add(_duration) || _revoked[token]) { + return totalBalance; + } else { + return totalBalance.mul(block.timestamp.sub(_start)).div(_duration); + } + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/examples/SampleCrowdsale.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/examples/SampleCrowdsale.sol new file mode 100644 index 000000000..d22598092 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/examples/SampleCrowdsale.sol @@ -0,0 +1,57 @@ +pragma solidity ^0.4.24; + +import "../crowdsale/validation/CappedCrowdsale.sol"; +import "../crowdsale/distribution/RefundableCrowdsale.sol"; +import "../crowdsale/emission/MintedCrowdsale.sol"; +import "../token/ERC20/ERC20Mintable.sol"; +import "../token/ERC20/ERC20Detailed.sol"; + +/** + * @title SampleCrowdsaleToken + * @dev Very simple ERC20 Token that can be minted. + * It is meant to be used in a crowdsale contract. + */ +contract SampleCrowdsaleToken is ERC20Mintable, ERC20Detailed { + constructor() public ERC20Detailed("Sample Crowdsale Token", "SCT", 18) {} +} + +/** + * @title SampleCrowdsale + * @dev This is an example of a fully fledged crowdsale. + * The way to add new features to a base crowdsale is by multiple inheritance. + * In this example we are providing following extensions: + * CappedCrowdsale - sets a max boundary for raised funds + * RefundableCrowdsale - set a min goal to be reached and returns funds if it's not met + * MintedCrowdsale - assumes the token can be minted by the crowdsale, which does so + * when receiving purchases. + * + * After adding multiple features it's good practice to run integration tests + * to ensure that subcontracts works together as intended. + */ +// XXX There doesn't seem to be a way to split this line that keeps solium +// happy. See: +// https://github.com/duaraghav8/Solium/issues/205 +// --elopio - 2018-05-10 +// solium-disable-next-line max-len +contract SampleCrowdsale is CappedCrowdsale, RefundableCrowdsale, MintedCrowdsale { + + constructor( + uint256 openingTime, + uint256 closingTime, + uint256 rate, + address wallet, + uint256 cap, + ERC20Mintable token, + uint256 goal + ) + public + Crowdsale(rate, wallet, token) + CappedCrowdsale(cap) + TimedCrowdsale(openingTime, closingTime) + RefundableCrowdsale(goal) + { + //As goal needs to be met for a successful crowdsale + //the value needs to less or equal than a cap which is limit for accepted funds + require(goal <= cap); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/examples/SimpleToken.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/examples/SimpleToken.sol new file mode 100644 index 000000000..8c63fdd98 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/examples/SimpleToken.sol @@ -0,0 +1,26 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/ERC20.sol"; + +/** + * @title SimpleToken + * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. + * Note they can later distribute these tokens as they wish using `transfer` and other + * `ERC20` functions. + */ +contract SimpleToken is ERC20 { + + string public constant name = "SimpleToken"; + string public constant symbol = "SIM"; + uint8 public constant decimals = 18; + + uint256 public constant INITIAL_SUPPLY = 10000 * (10 ** uint256(decimals)); + + /** + * @dev Constructor that gives msg.sender all of existing tokens. + */ + constructor() public { + _mint(msg.sender, INITIAL_SUPPLY); + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/introspection/ERC165.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/introspection/ERC165.sol new file mode 100644 index 000000000..5d083acdf --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/introspection/ERC165.sol @@ -0,0 +1,53 @@ +pragma solidity ^0.4.24; + +import "./IERC165.sol"; + +/** + * @title ERC165 + * @author Matt Condon (@shrugs) + * @dev Implements ERC165 using a lookup table. + */ +contract ERC165 is IERC165 { + + bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; + /** + * 0x01ffc9a7 === + * bytes4(keccak256('supportsInterface(bytes4)')) + */ + + /** + * @dev a mapping of interface id to whether or not it's supported + */ + mapping(bytes4 => bool) private _supportedInterfaces; + + /** + * @dev A contract implementing SupportsInterfaceWithLookup + * implement ERC165 itself + */ + constructor() + internal + { + _registerInterface(_InterfaceId_ERC165); + } + + /** + * @dev implement supportsInterface(bytes4) using a lookup table + */ + function supportsInterface(bytes4 interfaceId) + external + view + returns (bool) + { + return _supportedInterfaces[interfaceId]; + } + + /** + * @dev internal method for registering an interface + */ + function _registerInterface(bytes4 interfaceId) + internal + { + require(interfaceId != 0xffffffff); + _supportedInterfaces[interfaceId] = true; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/introspection/ERC165Checker.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/introspection/ERC165Checker.sol new file mode 100644 index 000000000..2490b191e --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/introspection/ERC165Checker.sol @@ -0,0 +1,146 @@ +pragma solidity ^0.4.24; + +/** + * @title ERC165Checker + * @dev Use `using ERC165Checker for address`; to include this library + * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md + */ +library ERC165Checker { + // As per the EIP-165 spec, no interface should ever match 0xffffffff + bytes4 private constant _InterfaceId_Invalid = 0xffffffff; + + bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; + /** + * 0x01ffc9a7 === + * bytes4(keccak256('supportsInterface(bytes4)')) + */ + + /** + * @notice Query if a contract supports ERC165 + * @param account The address of the contract to query for support of ERC165 + * @return true if the contract at account implements ERC165 + */ + function _supportsERC165(address account) + internal + view + returns (bool) + { + // Any contract that implements ERC165 must explicitly indicate support of + // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid + return _supportsERC165Interface(account, _InterfaceId_ERC165) && + !_supportsERC165Interface(account, _InterfaceId_Invalid); + } + + /** + * @notice Query if a contract implements an interface, also checks support of ERC165 + * @param account The address of the contract to query for support of an interface + * @param interfaceId The interface identifier, as specified in ERC-165 + * @return true if the contract at account indicates support of the interface with + * identifier interfaceId, false otherwise + * @dev Interface identification is specified in ERC-165. + */ + function _supportsInterface(address account, bytes4 interfaceId) + internal + view + returns (bool) + { + // query support of both ERC165 as per the spec and support of _interfaceId + return _supportsERC165(account) && + _supportsERC165Interface(account, interfaceId); + } + + /** + * @notice Query if a contract implements interfaces, also checks support of ERC165 + * @param account The address of the contract to query for support of an interface + * @param interfaceIds A list of interface identifiers, as specified in ERC-165 + * @return true if the contract at account indicates support all interfaces in the + * interfaceIds list, false otherwise + * @dev Interface identification is specified in ERC-165. + */ + function _supportsAllInterfaces(address account, bytes4[] interfaceIds) + internal + view + returns (bool) + { + // query support of ERC165 itself + if (!_supportsERC165(account)) { + return false; + } + + // query support of each interface in _interfaceIds + for (uint256 i = 0; i < interfaceIds.length; i++) { + if (!_supportsERC165Interface(account, interfaceIds[i])) { + return false; + } + } + + // all interfaces supported + return true; + } + + /** + * @notice Query if a contract implements an interface, does not check ERC165 support + * @param account The address of the contract to query for support of an interface + * @param interfaceId The interface identifier, as specified in ERC-165 + * @return true if the contract at account indicates support of the interface with + * identifier interfaceId, false otherwise + * @dev Assumes that account contains a contract that supports ERC165, otherwise + * the behavior of this method is undefined. This precondition can be checked + * with the `supportsERC165` method in this library. + * Interface identification is specified in ERC-165. + */ + function _supportsERC165Interface(address account, bytes4 interfaceId) + private + view + returns (bool) + { + // success determines whether the staticcall succeeded and result determines + // whether the contract at account indicates support of _interfaceId + (bool success, bool result) = _callERC165SupportsInterface( + account, interfaceId); + + return (success && result); + } + + /** + * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw + * @param account The address of the contract to query for support of an interface + * @param interfaceId The interface identifier, as specified in ERC-165 + * @return success true if the STATICCALL succeeded, false otherwise + * @return result true if the STATICCALL succeeded and the contract at account + * indicates support of the interface with identifier interfaceId, false otherwise + */ + function _callERC165SupportsInterface( + address account, + bytes4 interfaceId + ) + private + view + returns (bool success, bool result) + { + bytes memory encodedParams = abi.encodeWithSelector( + _InterfaceId_ERC165, + interfaceId + ); + + // solium-disable-next-line security/no-inline-assembly + assembly { + let encodedParams_data := add(0x20, encodedParams) + let encodedParams_size := mload(encodedParams) + + let output := mload(0x40) // Find empty storage location using "free memory pointer" + mstore(output, 0x0) + + success := staticcall( + 30000, // 30k gas + account, // To addr + encodedParams_data, + encodedParams_size, + output, + 0x20 // Outputs are 32 bytes long + ) + + result := mload(output) // Load the result + } + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/introspection/IERC165.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/introspection/IERC165.sol new file mode 100644 index 000000000..4e4b7bbf6 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/introspection/IERC165.sol @@ -0,0 +1,19 @@ +pragma solidity ^0.4.24; + +/** + * @title IERC165 + * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md + */ +interface IERC165 { + + /** + * @notice Query if a contract implements an interface + * @param interfaceId The interface identifier, as specified in ERC-165 + * @dev Interface identification is specified in ERC-165. This function + * uses less than 30,000 gas. + */ + function supportsInterface(bytes4 interfaceId) + external + view + returns (bool); +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/lifecycle/Pausable.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/lifecycle/Pausable.sol new file mode 100644 index 000000000..3703fed4b --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/lifecycle/Pausable.sol @@ -0,0 +1,57 @@ +pragma solidity ^0.4.24; + +import "../access/roles/PauserRole.sol"; + +/** + * @title Pausable + * @dev Base contract which allows children to implement an emergency stop mechanism. + */ +contract Pausable is PauserRole { + event Paused(address account); + event Unpaused(address account); + + bool private _paused; + + constructor() internal { + _paused = false; + } + + /** + * @return true if the contract is paused, false otherwise. + */ + function paused() public view returns(bool) { + return _paused; + } + + /** + * @dev Modifier to make a function callable only when the contract is not paused. + */ + modifier whenNotPaused() { + require(!_paused); + _; + } + + /** + * @dev Modifier to make a function callable only when the contract is paused. + */ + modifier whenPaused() { + require(_paused); + _; + } + + /** + * @dev called by the owner to pause, triggers stopped state + */ + function pause() public onlyPauser whenNotPaused { + _paused = true; + emit Paused(msg.sender); + } + + /** + * @dev called by the owner to unpause, returns to normal state + */ + function unpause() public onlyPauser whenPaused { + _paused = false; + emit Unpaused(msg.sender); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/math/Math.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/math/Math.sol new file mode 100644 index 000000000..ffff83961 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/math/Math.sol @@ -0,0 +1,31 @@ +pragma solidity ^0.4.24; + +/** + * @title Math + * @dev Assorted math operations + */ +library Math { + /** + * @dev Returns the largest of two numbers. + */ + function max(uint256 a, uint256 b) internal pure returns (uint256) { + return a >= b ? a : b; + } + + /** + * @dev Returns the smallest of two numbers. + */ + function min(uint256 a, uint256 b) internal pure returns (uint256) { + return a < b ? a : b; + } + + /** + * @dev Calculates the average of two numbers. Since these are integers, + * averages of an even and odd number cannot be represented, and will be + * rounded down. + */ + function average(uint256 a, uint256 b) internal pure returns (uint256) { + // (a + b) / 2 can overflow, so we distribute + return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/math/SafeMath.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/math/SafeMath.sol new file mode 100644 index 000000000..97494e1f1 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/math/SafeMath.sol @@ -0,0 +1,65 @@ +pragma solidity ^0.4.24; + +/** + * @title SafeMath + * @dev Math operations with safety checks that revert on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, reverts on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + // Gas optimization: this is cheaper than requiring 'a' not being zero, but the + // benefit is lost if 'b' is also tested. + // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 + if (a == 0) { + return 0; + } + + uint256 c = a * b; + require(c / a == b); + + return c; + } + + /** + * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + require(b > 0); // Solidity only automatically asserts when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + + return c; + } + + /** + * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a); + uint256 c = a - b; + + return c; + } + + /** + * @dev Adds two numbers, reverts on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a); + + return c; + } + + /** + * @dev Divides two numbers and returns the remainder (unsigned integer modulo), + * reverts when dividing by zero. + */ + function mod(uint256 a, uint256 b) internal pure returns (uint256) { + require(b != 0); + return a % b; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/AddressImpl.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/AddressImpl.sol new file mode 100644 index 000000000..e29396056 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/AddressImpl.sol @@ -0,0 +1,14 @@ +pragma solidity ^0.4.24; + +import "../utils/Address.sol"; + +contract AddressImpl { + function isContract(address account) + external + view + returns (bool) + { + return Address.isContract(account); + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/AllowanceCrowdsaleImpl.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/AllowanceCrowdsaleImpl.sol new file mode 100644 index 000000000..5b2104e38 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/AllowanceCrowdsaleImpl.sol @@ -0,0 +1,20 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/IERC20.sol"; +import "../crowdsale/emission/AllowanceCrowdsale.sol"; + +contract AllowanceCrowdsaleImpl is AllowanceCrowdsale { + + constructor ( + uint256 rate, + address wallet, + IERC20 token, + address tokenWallet + ) + public + Crowdsale(rate, wallet, token) + AllowanceCrowdsale(tokenWallet) + { + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ArraysImpl.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ArraysImpl.sol new file mode 100644 index 000000000..8a2b9ec51 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ArraysImpl.sol @@ -0,0 +1,18 @@ +pragma solidity ^0.4.24; + +import "../utils/Arrays.sol"; + +contract ArraysImpl { + + using Arrays for uint256[]; + + uint256[] private array; + + constructor(uint256[] _array) public { + array = _array; + } + + function findUpperBound(uint256 _element) external view returns (uint256) { + return array.findUpperBound(_element); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/CappedCrowdsaleImpl.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/CappedCrowdsaleImpl.sol new file mode 100644 index 000000000..176033b7f --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/CappedCrowdsaleImpl.sol @@ -0,0 +1,20 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/IERC20.sol"; +import "../crowdsale/validation/CappedCrowdsale.sol"; + +contract CappedCrowdsaleImpl is CappedCrowdsale { + + constructor ( + uint256 rate, + address wallet, + IERC20 token, + uint256 cap + ) + public + Crowdsale(rate, wallet, token) + CappedCrowdsale(cap) + { + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/CapperRoleMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/CapperRoleMock.sol new file mode 100644 index 000000000..118058f39 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/CapperRoleMock.sol @@ -0,0 +1,17 @@ +pragma solidity ^0.4.24; + +import "../access/roles/CapperRole.sol"; + +contract CapperRoleMock is CapperRole { + function removeCapper(address account) public { + _removeCapper(account); + } + + function onlyCapperMock() public view onlyCapper { + } + + // Causes a compilation error if super._removeCapper is not internal + function _removeCapper(address account) internal { + super._removeCapper(account); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ConditionalEscrowMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ConditionalEscrowMock.sol new file mode 100644 index 000000000..3e30c21a2 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ConditionalEscrowMock.sol @@ -0,0 +1,16 @@ +pragma solidity ^0.4.24; + +import "../payment/escrow/ConditionalEscrow.sol"; + +// mock class using ConditionalEscrow +contract ConditionalEscrowMock is ConditionalEscrow { + mapping(address => bool) private _allowed; + + function setAllowed(address payee, bool allowed) public { + _allowed[payee] = allowed; + } + + function withdrawalAllowed(address payee) public view returns (bool) { + return _allowed[payee]; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/CounterImpl.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/CounterImpl.sol new file mode 100644 index 000000000..3c958ba97 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/CounterImpl.sol @@ -0,0 +1,20 @@ +pragma solidity ^0.4.24; + +import "../drafts/Counter.sol"; + +contract CounterImpl { + using Counter for Counter.Counter; + + uint256 public theId; + + // use whatever key you want to track your counters + mapping(string => Counter.Counter) private _counters; + + function doThing(string key) + public + returns (uint256) + { + theId = _counters[key].next(); + return theId; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/CrowdsaleMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/CrowdsaleMock.sol new file mode 100644 index 000000000..834105e6a --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/CrowdsaleMock.sol @@ -0,0 +1,9 @@ +pragma solidity ^0.4.24; + +import "../crowdsale/Crowdsale.sol"; + +contract CrowdsaleMock is Crowdsale { + constructor(uint256 rate, address wallet, IERC20 token) public + Crowdsale(rate, wallet, token) { + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/DetailedERC20Mock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/DetailedERC20Mock.sol new file mode 100644 index 000000000..eea706326 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/DetailedERC20Mock.sol @@ -0,0 +1,15 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/ERC20.sol"; +import "../token/ERC20/ERC20Detailed.sol"; + +contract ERC20DetailedMock is ERC20, ERC20Detailed { + constructor( + string name, + string symbol, + uint8 decimals + ) + ERC20Detailed(name, symbol, decimals) + public + {} +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ECDSAMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ECDSAMock.sol new file mode 100644 index 000000000..9f489069f --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ECDSAMock.sol @@ -0,0 +1,23 @@ +pragma solidity ^0.4.24; + +import "../cryptography/ECDSA.sol"; + +contract ECDSAMock { + using ECDSA for bytes32; + + function recover(bytes32 hash, bytes signature) + public + pure + returns (address) + { + return hash.recover(signature); + } + + function toEthSignedMessageHash(bytes32 hash) + public + pure + returns (bytes32) + { + return hash.toEthSignedMessageHash(); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC165/ERC165InterfacesSupported.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC165/ERC165InterfacesSupported.sol new file mode 100644 index 000000000..e41901a32 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC165/ERC165InterfacesSupported.sol @@ -0,0 +1,66 @@ +pragma solidity ^0.4.24; + +import "../../introspection/IERC165.sol"; + +/** + * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-214.md#specification + * > Any attempts to make state-changing operations inside an execution instance with STATIC set to true will instead throw an exception. + * > These operations include [...], LOG0, LOG1, LOG2, [...] + * + * therefore, because this contract is staticcall'd we need to not emit events (which is how solidity-coverage works) + * solidity-coverage ignores the /mocks folder, so we duplicate its implementation here to avoid instrumenting it + */ +contract SupportsInterfaceWithLookupMock is IERC165 { + + bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; + /** + * 0x01ffc9a7 === + * bytes4(keccak256('supportsInterface(bytes4)')) + */ + + /** + * @dev a mapping of interface id to whether or not it's supported + */ + mapping(bytes4 => bool) private _supportedInterfaces; + + /** + * @dev A contract implementing SupportsInterfaceWithLookup + * implement ERC165 itself + */ + constructor() + public + { + _registerInterface(InterfaceId_ERC165); + } + + /** + * @dev implement supportsInterface(bytes4) using a lookup table + */ + function supportsInterface(bytes4 interfaceId) + external + view + returns (bool) + { + return _supportedInterfaces[interfaceId]; + } + + /** + * @dev private method for registering an interface + */ + function _registerInterface(bytes4 interfaceId) + internal + { + require(interfaceId != 0xffffffff); + _supportedInterfaces[interfaceId] = true; + } +} + +contract ERC165InterfacesSupported is SupportsInterfaceWithLookupMock { + constructor (bytes4[] interfaceIds) + public + { + for (uint256 i = 0; i < interfaceIds.length; i++) { + _registerInterface(interfaceIds[i]); + } + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC165/ERC165NotSupported.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC165/ERC165NotSupported.sol new file mode 100644 index 000000000..156ef8e8b --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC165/ERC165NotSupported.sol @@ -0,0 +1,5 @@ +pragma solidity ^0.4.24; + +contract ERC165NotSupported { + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC165CheckerMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC165CheckerMock.sol new file mode 100644 index 000000000..559cea0d7 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC165CheckerMock.sol @@ -0,0 +1,31 @@ +pragma solidity ^0.4.24; + +import "../introspection/ERC165Checker.sol"; + +contract ERC165CheckerMock { + using ERC165Checker for address; + + function supportsERC165(address account) + public + view + returns (bool) + { + return account._supportsERC165(); + } + + function supportsInterface(address account, bytes4 interfaceId) + public + view + returns (bool) + { + return account._supportsInterface(interfaceId); + } + + function supportsAllInterfaces(address account, bytes4[] interfaceIds) + public + view + returns (bool) + { + return account._supportsAllInterfaces(interfaceIds); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC165Mock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC165Mock.sol new file mode 100644 index 000000000..c42ba62f2 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC165Mock.sol @@ -0,0 +1,11 @@ +pragma solidity ^0.4.24; + +import "../introspection/ERC165.sol"; + +contract ERC165Mock is ERC165 { + function registerInterface(bytes4 interfaceId) + public + { + _registerInterface(interfaceId); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20BurnableMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20BurnableMock.sol new file mode 100644 index 000000000..2c8b3b54a --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20BurnableMock.sol @@ -0,0 +1,11 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/ERC20Burnable.sol"; + +contract ERC20BurnableMock is ERC20Burnable { + + constructor(address initialAccount, uint256 initialBalance) public { + _mint(initialAccount, initialBalance); + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20MintableMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20MintableMock.sol new file mode 100644 index 000000000..31384c790 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20MintableMock.sol @@ -0,0 +1,7 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/ERC20Mintable.sol"; +import "./MinterRoleMock.sol"; + +contract ERC20MintableMock is ERC20Mintable, MinterRoleMock { +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20Mock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20Mock.sol new file mode 100644 index 000000000..ab0877653 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20Mock.sol @@ -0,0 +1,24 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/ERC20.sol"; + +// mock class using ERC20 +contract ERC20Mock is ERC20 { + + constructor(address initialAccount, uint256 initialBalance) public { + _mint(initialAccount, initialBalance); + } + + function mint(address account, uint256 amount) public { + _mint(account, amount); + } + + function burn(address account, uint256 amount) public { + _burn(account, amount); + } + + function burnFrom(address account, uint256 amount) public { + _burnFrom(account, amount); + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20PausableMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20PausableMock.sol new file mode 100644 index 000000000..c6c0fd5ed --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20PausableMock.sol @@ -0,0 +1,13 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/ERC20Pausable.sol"; +import "./PauserRoleMock.sol"; + +// mock class using ERC20Pausable +contract ERC20PausableMock is ERC20Pausable, PauserRoleMock { + + constructor(address initialAccount, uint initialBalance) public { + _mint(initialAccount, initialBalance); + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20WithMetadataMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20WithMetadataMock.sol new file mode 100644 index 000000000..ec2d122a1 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC20WithMetadataMock.sol @@ -0,0 +1,11 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/ERC20.sol"; +import "../drafts/ERC1046/TokenMetadata.sol"; + +contract ERC20WithMetadataMock is ERC20, ERC20WithMetadata { + constructor(string tokenURI) public + ERC20WithMetadata(tokenURI) + { + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721FullMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721FullMock.sol new file mode 100644 index 000000000..2d85e7372 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721FullMock.sol @@ -0,0 +1,32 @@ +pragma solidity ^0.4.24; + +import "../token/ERC721/ERC721Full.sol"; +import "../token/ERC721/ERC721Mintable.sol"; +import "../token/ERC721/ERC721MetadataMintable.sol"; +import "../token/ERC721/ERC721Burnable.sol"; + +/** + * @title ERC721FullMock + * This mock just provides a public mint and burn functions for testing purposes, + * and a public setter for metadata URI + */ +contract ERC721FullMock + is ERC721Full, ERC721Mintable, ERC721MetadataMintable, ERC721Burnable { + + constructor(string name, string symbol) public + ERC721Mintable() + ERC721Full(name, symbol) + {} + + function exists(uint256 tokenId) public view returns (bool) { + return _exists(tokenId); + } + + function setTokenURI(uint256 tokenId, string uri) public { + _setTokenURI(tokenId, uri); + } + + function removeTokenFrom(address from, uint256 tokenId) public { + _removeTokenFrom(from, tokenId); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721MintableBurnableImpl.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721MintableBurnableImpl.sol new file mode 100644 index 000000000..51d3ff4f6 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721MintableBurnableImpl.sol @@ -0,0 +1,20 @@ +pragma solidity ^0.4.24; + +import "../token/ERC721/ERC721Full.sol"; +import "../token/ERC721/ERC721Mintable.sol"; +import "../token/ERC721/ERC721MetadataMintable.sol"; +import "../token/ERC721/ERC721Burnable.sol"; + +/** + * @title ERC721MintableBurnableImpl + */ +contract ERC721MintableBurnableImpl + is ERC721Full, ERC721Mintable, ERC721MetadataMintable, ERC721Burnable { + + constructor() + ERC721Mintable() + ERC721Full("Test", "TEST") + public + { + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721Mock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721Mock.sol new file mode 100644 index 000000000..514d3bdbe --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721Mock.sol @@ -0,0 +1,17 @@ +pragma solidity ^0.4.24; + +import "../token/ERC721/ERC721.sol"; + +/** + * @title ERC721Mock + * This mock just provides a public mint and burn functions for testing purposes + */ +contract ERC721Mock is ERC721 { + function mint(address to, uint256 tokenId) public { + _mint(to, tokenId); + } + + function burn(uint256 tokenId) public { + _burn(ownerOf(tokenId), tokenId); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721PausableMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721PausableMock.sol new file mode 100644 index 000000000..9751d04cb --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721PausableMock.sol @@ -0,0 +1,22 @@ +pragma solidity ^0.4.24; + +import "../token/ERC721/ERC721Pausable.sol"; +import "./PauserRoleMock.sol"; + +/** + * @title ERC721PausableMock + * This mock just provides a public mint, burn and exists functions for testing purposes + */ +contract ERC721PausableMock is ERC721Pausable, PauserRoleMock { + function mint(address to, uint256 tokenId) public { + super._mint(to, tokenId); + } + + function burn(uint256 tokenId) public { + super._burn(ownerOf(tokenId), tokenId); + } + + function exists(uint256 tokenId) public view returns (bool) { + return super._exists(tokenId); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721ReceiverMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721ReceiverMock.sol new file mode 100644 index 000000000..57fb04e3a --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ERC721ReceiverMock.sol @@ -0,0 +1,41 @@ +pragma solidity ^0.4.24; + +import "../token/ERC721/IERC721Receiver.sol"; + +contract ERC721ReceiverMock is IERC721Receiver { + bytes4 private _retval; + bool private _reverts; + + event Received( + address operator, + address from, + uint256 tokenId, + bytes data, + uint256 gas + ); + + constructor(bytes4 retval, bool reverts) public { + _retval = retval; + _reverts = reverts; + } + + function onERC721Received( + address operator, + address from, + uint256 tokenId, + bytes data + ) + public + returns(bytes4) + { + require(!_reverts); + emit Received( + operator, + from, + tokenId, + data, + gasleft() // msg.gas was deprecated in solidityv0.4.21 + ); + return _retval; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/EventEmitter.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/EventEmitter.sol new file mode 100644 index 000000000..71582d9f5 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/EventEmitter.sol @@ -0,0 +1,62 @@ +pragma solidity ^0.4.24; + +contract EventEmitter { + event Argumentless(); + event ShortUint(uint8 value); + event ShortInt(int8 value); + event LongUint(uint256 value); + event LongInt(int256 value); + event Address(address value); + event Boolean(bool value); + event String(string value); + event LongUintBooleanString( + uint256 uintValue, + bool booleanValue, + string stringValue + ); + + function emitArgumentless() public { + emit Argumentless(); + } + + function emitShortUint(uint8 value) public { + emit ShortUint(value); + } + + function emitShortInt(int8 value) public { + emit ShortInt(value); + } + + function emitLongUint(uint256 value) public { + emit LongUint(value); + } + + function emitLongInt(int256 value) public { + emit LongInt(value); + } + + function emitAddress(address value) public { + emit Address(value); + } + + function emitBoolean(bool value) public { + emit Boolean(value); + } + + function emitString(string value) public { + emit String(value); + } + + function emitLongUintBooleanString( + uint256 uintValue, + bool booleanValue, + string stringValue) + public { + emit LongUintBooleanString(uintValue, booleanValue, stringValue); + } + + function emitLongUintAndBoolean(uint256 uintValue, bool boolValue) public { + emit LongUint(uintValue); + emit Boolean(boolValue); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/FinalizableCrowdsaleImpl.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/FinalizableCrowdsaleImpl.sol new file mode 100644 index 000000000..084780b1d --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/FinalizableCrowdsaleImpl.sol @@ -0,0 +1,21 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/IERC20.sol"; +import "../crowdsale/distribution/FinalizableCrowdsale.sol"; + +contract FinalizableCrowdsaleImpl is FinalizableCrowdsale { + + constructor ( + uint256 openingTime, + uint256 closingTime, + uint256 rate, + address wallet, + IERC20 token + ) + public + Crowdsale(rate, wallet, token) + TimedCrowdsale(openingTime, closingTime) + { + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/IncreasingPriceCrowdsaleImpl.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/IncreasingPriceCrowdsaleImpl.sol new file mode 100644 index 000000000..6f1f2e2a0 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/IncreasingPriceCrowdsaleImpl.sol @@ -0,0 +1,23 @@ +pragma solidity ^0.4.24; + +import "../crowdsale/price/IncreasingPriceCrowdsale.sol"; +import "../math/SafeMath.sol"; + +contract IncreasingPriceCrowdsaleImpl is IncreasingPriceCrowdsale { + + constructor ( + uint256 openingTime, + uint256 closingTime, + address wallet, + IERC20 token, + uint256 initialRate, + uint256 finalRate + ) + public + Crowdsale(initialRate, wallet, token) + TimedCrowdsale(openingTime, closingTime) + IncreasingPriceCrowdsale(initialRate, finalRate) + { + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/IndividuallyCappedCrowdsaleImpl.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/IndividuallyCappedCrowdsaleImpl.sol new file mode 100644 index 000000000..1bcb95301 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/IndividuallyCappedCrowdsaleImpl.sol @@ -0,0 +1,19 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/IERC20.sol"; +import "../crowdsale/validation/IndividuallyCappedCrowdsale.sol"; +import "./CapperRoleMock.sol"; + +contract IndividuallyCappedCrowdsaleImpl + is IndividuallyCappedCrowdsale, CapperRoleMock { + + constructor( + uint256 rate, + address wallet, + IERC20 token + ) + public + Crowdsale(rate, wallet, token) + { + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/MathMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/MathMock.sol new file mode 100644 index 000000000..72f7fc204 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/MathMock.sol @@ -0,0 +1,17 @@ +pragma solidity ^0.4.24; + +import "../math/Math.sol"; + +contract MathMock { + function max(uint256 a, uint256 b) public pure returns (uint256) { + return Math.max(a, b); + } + + function min(uint256 a, uint256 b) public pure returns (uint256) { + return Math.min(a, b); + } + + function average(uint256 a, uint256 b) public pure returns (uint256) { + return Math.average(a, b); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/MerkleProofWrapper.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/MerkleProofWrapper.sol new file mode 100644 index 000000000..b359dc790 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/MerkleProofWrapper.sol @@ -0,0 +1,18 @@ +pragma solidity ^0.4.24; + +import { MerkleProof } from "../cryptography/MerkleProof.sol"; + +contract MerkleProofWrapper { + + function verify( + bytes32[] proof, + bytes32 root, + bytes32 leaf + ) + public + pure + returns (bool) + { + return MerkleProof.verify(proof, root, leaf); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/MintedCrowdsaleImpl.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/MintedCrowdsaleImpl.sol new file mode 100644 index 000000000..518371b75 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/MintedCrowdsaleImpl.sol @@ -0,0 +1,18 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/ERC20Mintable.sol"; +import "../crowdsale/emission/MintedCrowdsale.sol"; + +contract MintedCrowdsaleImpl is MintedCrowdsale { + + constructor ( + uint256 rate, + address wallet, + ERC20Mintable token + ) + public + Crowdsale(rate, wallet, token) + { + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/MinterRoleMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/MinterRoleMock.sol new file mode 100644 index 000000000..45e5a4195 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/MinterRoleMock.sol @@ -0,0 +1,17 @@ +pragma solidity ^0.4.24; + +import "../access/roles/MinterRole.sol"; + +contract MinterRoleMock is MinterRole { + function removeMinter(address account) public { + _removeMinter(account); + } + + function onlyMinterMock() public view onlyMinter { + } + + // Causes a compilation error if super._removeMinter is not internal + function _removeMinter(address account) internal { + super._removeMinter(account); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/OwnableMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/OwnableMock.sol new file mode 100644 index 000000000..e16a89012 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/OwnableMock.sol @@ -0,0 +1,6 @@ +pragma solidity ^0.4.24; + +import "../ownership/Ownable.sol"; + +contract OwnableMock is Ownable { +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/PausableMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/PausableMock.sol new file mode 100644 index 000000000..72ec843ed --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/PausableMock.sol @@ -0,0 +1,24 @@ +pragma solidity ^0.4.24; + +import "../lifecycle/Pausable.sol"; +import "./PauserRoleMock.sol"; + +// mock class using Pausable +contract PausableMock is Pausable, PauserRoleMock { + bool public drasticMeasureTaken; + uint256 public count; + + constructor() public { + drasticMeasureTaken = false; + count = 0; + } + + function normalProcess() external whenNotPaused { + count++; + } + + function drasticMeasure() external whenPaused { + drasticMeasureTaken = true; + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/PauserRoleMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/PauserRoleMock.sol new file mode 100644 index 000000000..267101e4a --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/PauserRoleMock.sol @@ -0,0 +1,17 @@ +pragma solidity ^0.4.24; + +import "../access/roles/PauserRole.sol"; + +contract PauserRoleMock is PauserRole { + function removePauser(address account) public { + _removePauser(account); + } + + function onlyPauserMock() public view onlyPauser { + } + + // Causes a compilation error if super._removePauser is not internal + function _removePauser(address account) internal { + super._removePauser(account); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/PostDeliveryCrowdsaleImpl.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/PostDeliveryCrowdsaleImpl.sol new file mode 100644 index 000000000..98d056c66 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/PostDeliveryCrowdsaleImpl.sol @@ -0,0 +1,21 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/IERC20.sol"; +import "../crowdsale/distribution/PostDeliveryCrowdsale.sol"; + +contract PostDeliveryCrowdsaleImpl is PostDeliveryCrowdsale { + + constructor ( + uint256 openingTime, + uint256 closingTime, + uint256 rate, + address wallet, + IERC20 token + ) + public + TimedCrowdsale(openingTime, closingTime) + Crowdsale(rate, wallet, token) + { + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/PullPaymentMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/PullPaymentMock.sol new file mode 100644 index 000000000..63076c904 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/PullPaymentMock.sol @@ -0,0 +1,15 @@ +pragma solidity ^0.4.24; + +import "../payment/PullPayment.sol"; + +// mock class using PullPayment +contract PullPaymentMock is PullPayment { + + constructor() public payable { } + + // test helper function to call asyncTransfer + function callTransfer(address dest, uint256 amount) public { + _asyncTransfer(dest, amount); + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ReentrancyAttack.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ReentrancyAttack.sol new file mode 100644 index 000000000..96231de27 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ReentrancyAttack.sol @@ -0,0 +1,10 @@ +pragma solidity ^0.4.24; + +contract ReentrancyAttack { + + function callSender(bytes4 data) public { + // solium-disable-next-line security/no-low-level-calls + require(msg.sender.call(abi.encodeWithSelector(data))); + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ReentrancyMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ReentrancyMock.sol new file mode 100644 index 000000000..474ecd433 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/ReentrancyMock.sol @@ -0,0 +1,44 @@ +pragma solidity ^0.4.24; + +import "../utils/ReentrancyGuard.sol"; +import "./ReentrancyAttack.sol"; + +contract ReentrancyMock is ReentrancyGuard { + + uint256 public counter; + + constructor() public { + counter = 0; + } + + function callback() external nonReentrant { + count(); + } + + function countLocalRecursive(uint256 n) public nonReentrant { + if (n > 0) { + count(); + countLocalRecursive(n - 1); + } + } + + function countThisRecursive(uint256 n) public nonReentrant { + if (n > 0) { + count(); + // solium-disable-next-line security/no-low-level-calls + bool result = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); + require(result == true); + } + } + + function countAndCall(ReentrancyAttack attacker) public nonReentrant { + count(); + bytes4 func = bytes4(keccak256("callback()")); + attacker.callSender(func); + } + + function count() private { + counter += 1; + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/RefundableCrowdsaleImpl.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/RefundableCrowdsaleImpl.sol new file mode 100644 index 000000000..a14dfbcb3 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/RefundableCrowdsaleImpl.sol @@ -0,0 +1,23 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/ERC20Mintable.sol"; +import "../crowdsale/distribution/RefundableCrowdsale.sol"; + +contract RefundableCrowdsaleImpl is RefundableCrowdsale { + + constructor ( + uint256 openingTime, + uint256 closingTime, + uint256 rate, + address wallet, + ERC20Mintable token, + uint256 goal + ) + public + Crowdsale(rate, wallet, token) + TimedCrowdsale(openingTime, closingTime) + RefundableCrowdsale(goal) + { + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/RolesMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/RolesMock.sol new file mode 100644 index 000000000..bfcee20ee --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/RolesMock.sol @@ -0,0 +1,21 @@ +pragma solidity ^0.4.24; + +import "../access/Roles.sol"; + +contract RolesMock { + using Roles for Roles.Role; + + Roles.Role private dummyRole; + + function add(address account) public { + dummyRole.add(account); + } + + function remove(address account) public { + dummyRole.remove(account); + } + + function has(address account) public view returns (bool) { + return dummyRole.has(account); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SafeERC20Helper.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SafeERC20Helper.sol new file mode 100644 index 000000000..7e639f86f --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SafeERC20Helper.sol @@ -0,0 +1,112 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/IERC20.sol"; +import "../token/ERC20/SafeERC20.sol"; + +contract ERC20FailingMock { + uint256 private _allowance; + + function transfer(address, uint256) public returns (bool) { + return false; + } + + function transferFrom(address, address, uint256) public returns (bool) { + return false; + } + + function approve(address, uint256) public returns (bool) { + return false; + } + + function allowance(address, address) public view returns (uint256) { + return 0; + } +} + +contract ERC20SucceedingMock { + uint256 private _allowance; + + function transfer(address, uint256) public returns (bool) { + return true; + } + + function transferFrom(address, address, uint256) public returns (bool) { + return true; + } + + function approve(address, uint256) public returns (bool) { + return true; + } + + function setAllowance(uint256 allowance_) public { + _allowance = allowance_; + } + + function allowance(address, address) public view returns (uint256) { + return _allowance; + } +} + +contract SafeERC20Helper { + using SafeERC20 for IERC20; + + IERC20 private _failing; + IERC20 private _succeeding; + + constructor() public { + _failing = IERC20(new ERC20FailingMock()); + _succeeding = IERC20(new ERC20SucceedingMock()); + } + + // Using _failing + + function doFailingTransfer() public { + _failing.safeTransfer(address(0), 0); + } + + function doFailingTransferFrom() public { + _failing.safeTransferFrom(address(0), address(0), 0); + } + + function doFailingApprove() public { + _failing.safeApprove(address(0), 0); + } + + function doFailingIncreaseAllowance() public { + _failing.safeIncreaseAllowance(address(0), 0); + } + + function doFailingDecreaseAllowance() public { + _failing.safeDecreaseAllowance(address(0), 0); + } + + // Using _succeeding + + function doSucceedingTransfer() public { + _succeeding.safeTransfer(address(0), 0); + } + + function doSucceedingTransferFrom() public { + _succeeding.safeTransferFrom(address(0), address(0), 0); + } + + function doSucceedingApprove(uint256 amount) public { + _succeeding.safeApprove(address(0), amount); + } + + function doSucceedingIncreaseAllowance(uint256 amount) public { + _succeeding.safeIncreaseAllowance(address(0), amount); + } + + function doSucceedingDecreaseAllowance(uint256 amount) public { + _succeeding.safeDecreaseAllowance(address(0), amount); + } + + function setAllowance(uint256 allowance_) public { + ERC20SucceedingMock(_succeeding).setAllowance(allowance_); + } + + function allowance() public view returns (uint256) { + return _succeeding.allowance(address(0), address(0)); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SafeMathMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SafeMathMock.sol new file mode 100644 index 000000000..7ddf17e9f --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SafeMathMock.sol @@ -0,0 +1,26 @@ +pragma solidity ^0.4.24; + +import "../math/SafeMath.sol"; + +contract SafeMathMock { + + function mul(uint256 a, uint256 b) public pure returns (uint256) { + return SafeMath.mul(a, b); + } + + function div(uint256 a, uint256 b) public pure returns (uint256) { + return SafeMath.div(a, b); + } + + function sub(uint256 a, uint256 b) public pure returns (uint256) { + return SafeMath.sub(a, b); + } + + function add(uint256 a, uint256 b) public pure returns (uint256) { + return SafeMath.add(a, b); + } + + function mod(uint256 a, uint256 b) public pure returns (uint256) { + return SafeMath.mod(a, b); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SecondaryMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SecondaryMock.sol new file mode 100644 index 000000000..268c12516 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SecondaryMock.sol @@ -0,0 +1,8 @@ +pragma solidity ^0.4.24; + +import "../ownership/Secondary.sol"; + +contract SecondaryMock is Secondary { + function onlyPrimaryMock() public view onlyPrimary { + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SignatureBouncerMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SignatureBouncerMock.sol new file mode 100644 index 000000000..85076eae6 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SignatureBouncerMock.sol @@ -0,0 +1,73 @@ +pragma solidity ^0.4.24; + +import "../drafts/SignatureBouncer.sol"; +import "./SignerRoleMock.sol"; + +contract SignatureBouncerMock is SignatureBouncer, SignerRoleMock { + function checkValidSignature(address account, bytes signature) + public + view + returns (bool) + { + return _isValidSignature(account, signature); + } + + function onlyWithValidSignature(bytes signature) + public + onlyValidSignature(signature) + view + { + + } + + function checkValidSignatureAndMethod(address account, bytes signature) + public + view + returns (bool) + { + return _isValidSignatureAndMethod(account, signature); + } + + function onlyWithValidSignatureAndMethod(bytes signature) + public + onlyValidSignatureAndMethod(signature) + view + { + + } + + function checkValidSignatureAndData( + address account, + bytes, + uint, + bytes signature + ) + public + view + returns (bool) + { + return _isValidSignatureAndData(account, signature); + } + + function onlyWithValidSignatureAndData(uint, bytes signature) + public + onlyValidSignatureAndData(signature) + view + { + + } + + function theWrongMethod(bytes) + public + pure + { + + } + + function tooShortMsgData() + public + onlyValidSignatureAndData("") + view + { + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SignerRoleMock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SignerRoleMock.sol new file mode 100644 index 000000000..faf92db68 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/SignerRoleMock.sol @@ -0,0 +1,17 @@ +pragma solidity ^0.4.24; + +import "../access/roles/SignerRole.sol"; + +contract SignerRoleMock is SignerRole { + function removeSigner(address account) public { + _removeSigner(account); + } + + function onlySignerMock() public view onlySigner { + } + + // Causes a compilation error if super._removeSigner is not internal + function _removeSigner(address account) internal { + super._removeSigner(account); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/TimedCrowdsaleImpl.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/TimedCrowdsaleImpl.sol new file mode 100644 index 000000000..f16e5eb2a --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/mocks/TimedCrowdsaleImpl.sol @@ -0,0 +1,21 @@ +pragma solidity ^0.4.24; + +import "../token/ERC20/IERC20.sol"; +import "../crowdsale/validation/TimedCrowdsale.sol"; + +contract TimedCrowdsaleImpl is TimedCrowdsale { + + constructor ( + uint256 openingTime, + uint256 closingTime, + uint256 rate, + address wallet, + IERC20 token + ) + public + Crowdsale(rate, wallet, token) + TimedCrowdsale(openingTime, closingTime) + { + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/ownership/Ownable.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/ownership/Ownable.sol new file mode 100644 index 000000000..7b5b72102 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/ownership/Ownable.sol @@ -0,0 +1,75 @@ +pragma solidity ^0.4.24; + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address private _owner; + + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() internal { + _owner = msg.sender; + emit OwnershipTransferred(address(0), _owner); + } + + /** + * @return the address of the owner. + */ + function owner() public view returns(address) { + return _owner; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(isOwner()); + _; + } + + /** + * @return true if `msg.sender` is the owner of the contract. + */ + function isOwner() public view returns(bool) { + return msg.sender == _owner; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + * @notice Renouncing to ownership will leave the contract without an owner. + * It will not be possible to call the functions with the `onlyOwner` + * modifier anymore. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipTransferred(_owner, address(0)); + _owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + _transferOwnership(newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function _transferOwnership(address newOwner) internal { + require(newOwner != address(0)); + emit OwnershipTransferred(_owner, newOwner); + _owner = newOwner; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/ownership/Secondary.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/ownership/Secondary.sol new file mode 100644 index 000000000..67d2250d5 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/ownership/Secondary.sol @@ -0,0 +1,46 @@ +pragma solidity ^0.4.24; + +/** + * @title Secondary + * @dev A Secondary contract can only be used by its primary account (the one that created it) + */ +contract Secondary { + address private _primary; + + event PrimaryTransferred( + address recipient + ); + + /** + * @dev Sets the primary account to the one that is creating the Secondary contract. + */ + constructor() internal { + _primary = msg.sender; + emit PrimaryTransferred(_primary); + } + + /** + * @dev Reverts if called from any account other than the primary. + */ + modifier onlyPrimary() { + require(msg.sender == _primary); + _; + } + + /** + * @return the address of the primary. + */ + function primary() public view returns (address) { + return _primary; + } + + /** + * @dev Transfers contract to a new primary. + * @param recipient The address of new primary. + */ + function transferPrimary(address recipient) public onlyPrimary { + require(recipient != address(0)); + _primary = recipient; + emit PrimaryTransferred(_primary); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/PaymentSplitter.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/PaymentSplitter.sol new file mode 100644 index 000000000..0a1b470ef --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/PaymentSplitter.sol @@ -0,0 +1,116 @@ +pragma solidity ^0.4.24; + +import "../math/SafeMath.sol"; + +/** + * @title PaymentSplitter + * @dev This contract can be used when payments need to be received by a group + * of people and split proportionately to some number of shares they own. + */ +contract PaymentSplitter { + using SafeMath for uint256; + + event PayeeAdded(address account, uint256 shares); + event PaymentReleased(address to, uint256 amount); + event PaymentReceived(address from, uint256 amount); + + uint256 private _totalShares; + uint256 private _totalReleased; + + mapping(address => uint256) private _shares; + mapping(address => uint256) private _released; + address[] private _payees; + + /** + * @dev Constructor + */ + constructor(address[] payees, uint256[] shares) public payable { + require(payees.length == shares.length); + require(payees.length > 0); + + for (uint256 i = 0; i < payees.length; i++) { + _addPayee(payees[i], shares[i]); + } + } + + /** + * @dev payable fallback + */ + function () external payable { + emit PaymentReceived(msg.sender, msg.value); + } + + /** + * @return the total shares of the contract. + */ + function totalShares() public view returns(uint256) { + return _totalShares; + } + + /** + * @return the total amount already released. + */ + function totalReleased() public view returns(uint256) { + return _totalReleased; + } + + /** + * @return the shares of an account. + */ + function shares(address account) public view returns(uint256) { + return _shares[account]; + } + + /** + * @return the amount already released to an account. + */ + function released(address account) public view returns(uint256) { + return _released[account]; + } + + /** + * @return the address of a payee. + */ + function payee(uint256 index) public view returns(address) { + return _payees[index]; + } + + /** + * @dev Release one of the payee's proportional payment. + * @param account Whose payments will be released. + */ + function release(address account) public { + require(_shares[account] > 0); + + uint256 totalReceived = address(this).balance.add(_totalReleased); + uint256 payment = totalReceived.mul( + _shares[account]).div( + _totalShares).sub( + _released[account] + ); + + require(payment != 0); + + _released[account] = _released[account].add(payment); + _totalReleased = _totalReleased.add(payment); + + account.transfer(payment); + emit PaymentReleased(account, payment); + } + + /** + * @dev Add a new payee to the contract. + * @param account The address of the payee to add. + * @param shares_ The number of shares owned by the payee. + */ + function _addPayee(address account, uint256 shares_) private { + require(account != address(0)); + require(shares_ > 0); + require(_shares[account] == 0); + + _payees.push(account); + _shares[account] = shares_; + _totalShares = _totalShares.add(shares_); + emit PayeeAdded(account, shares_); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/PullPayment.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/PullPayment.sol new file mode 100644 index 000000000..f6d7e2c1e --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/PullPayment.sol @@ -0,0 +1,41 @@ +pragma solidity ^0.4.24; + +import "./escrow/Escrow.sol"; + +/** + * @title PullPayment + * @dev Base contract supporting async send for pull payments. Inherit from this + * contract and use _asyncTransfer instead of send or transfer. + */ +contract PullPayment { + Escrow private _escrow; + + constructor() internal { + _escrow = new Escrow(); + } + + /** + * @dev Withdraw accumulated balance. + * @param payee Whose balance will be withdrawn. + */ + function withdrawPayments(address payee) public { + _escrow.withdraw(payee); + } + + /** + * @dev Returns the credit owed to an address. + * @param dest The creditor's address. + */ + function payments(address dest) public view returns (uint256) { + return _escrow.depositsOf(dest); + } + + /** + * @dev Called by the payer to store the sent amount as credit to be pulled. + * @param dest The destination address of the funds. + * @param amount The amount to transfer. + */ + function _asyncTransfer(address dest, uint256 amount) internal { + _escrow.deposit.value(amount)(dest); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/escrow/ConditionalEscrow.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/escrow/ConditionalEscrow.sol new file mode 100644 index 000000000..c3f63ee37 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/escrow/ConditionalEscrow.sol @@ -0,0 +1,22 @@ +pragma solidity ^0.4.24; + +import "./Escrow.sol"; + +/** + * @title ConditionalEscrow + * @dev Base abstract escrow to only allow withdrawal if a condition is met. + * @dev Intended usage: See Escrow.sol. Same usage guidelines apply here. + */ +contract ConditionalEscrow is Escrow { + /** + * @dev Returns whether an address is allowed to withdraw their funds. To be + * implemented by derived contracts. + * @param payee The destination address of the funds. + */ + function withdrawalAllowed(address payee) public view returns (bool); + + function withdraw(address payee) public { + require(withdrawalAllowed(payee)); + super.withdraw(payee); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/escrow/Escrow.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/escrow/Escrow.sol new file mode 100644 index 000000000..b2f2a85ee --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/escrow/Escrow.sol @@ -0,0 +1,54 @@ +pragma solidity ^0.4.24; + +import "../../math/SafeMath.sol"; +import "../../ownership/Secondary.sol"; + + /** + * @title Escrow + * @dev Base escrow contract, holds funds designated for a payee until they + * withdraw them. + * @dev Intended usage: This contract (and derived escrow contracts) should be a + * standalone contract, that only interacts with the contract that instantiated + * it. That way, it is guaranteed that all Ether will be handled according to + * the Escrow rules, and there is no need to check for payable functions or + * transfers in the inheritance tree. The contract that uses the escrow as its + * payment method should be its primary, and provide public methods redirecting + * to the escrow's deposit and withdraw. + */ +contract Escrow is Secondary { + using SafeMath for uint256; + + event Deposited(address indexed payee, uint256 weiAmount); + event Withdrawn(address indexed payee, uint256 weiAmount); + + mapping(address => uint256) private _deposits; + + function depositsOf(address payee) public view returns (uint256) { + return _deposits[payee]; + } + + /** + * @dev Stores the sent amount as credit to be withdrawn. + * @param payee The destination address of the funds. + */ + function deposit(address payee) public onlyPrimary payable { + uint256 amount = msg.value; + _deposits[payee] = _deposits[payee].add(amount); + + emit Deposited(payee, amount); + } + + /** + * @dev Withdraw accumulated balance for a payee. + * @param payee The address whose funds will be withdrawn and transferred to. + */ + function withdraw(address payee) public onlyPrimary { + uint256 payment = _deposits[payee]; + + _deposits[payee] = 0; + + payee.transfer(payment); + + emit Withdrawn(payee, payment); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/escrow/RefundEscrow.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/escrow/RefundEscrow.sol new file mode 100644 index 000000000..a776a81c8 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/payment/escrow/RefundEscrow.sol @@ -0,0 +1,91 @@ +pragma solidity ^0.4.24; + +import "./ConditionalEscrow.sol"; + +/** + * @title RefundEscrow + * @dev Escrow that holds funds for a beneficiary, deposited from multiple + * parties. + * @dev Intended usage: See Escrow.sol. Same usage guidelines apply here. + * @dev The primary account (that is, the contract that instantiates this + * contract) may deposit, close the deposit period, and allow for either + * withdrawal by the beneficiary, or refunds to the depositors. All interactions + * with RefundEscrow will be made through the primary contract. See the + * RefundableCrowdsale contract for an example of RefundEscrow’s use. + */ +contract RefundEscrow is ConditionalEscrow { + enum State { Active, Refunding, Closed } + + event RefundsClosed(); + event RefundsEnabled(); + + State private _state; + address private _beneficiary; + + /** + * @dev Constructor. + * @param beneficiary The beneficiary of the deposits. + */ + constructor(address beneficiary) public { + require(beneficiary != address(0)); + _beneficiary = beneficiary; + _state = State.Active; + } + + /** + * @return the current state of the escrow. + */ + function state() public view returns (State) { + return _state; + } + + /** + * @return the beneficiary of the escrow. + */ + function beneficiary() public view returns (address) { + return _beneficiary; + } + + /** + * @dev Stores funds that may later be refunded. + * @param refundee The address funds will be sent to if a refund occurs. + */ + function deposit(address refundee) public payable { + require(_state == State.Active); + super.deposit(refundee); + } + + /** + * @dev Allows for the beneficiary to withdraw their funds, rejecting + * further deposits. + */ + function close() public onlyPrimary { + require(_state == State.Active); + _state = State.Closed; + emit RefundsClosed(); + } + + /** + * @dev Allows for refunds to take place, rejecting further deposits. + */ + function enableRefunds() public onlyPrimary { + require(_state == State.Active); + _state = State.Refunding; + emit RefundsEnabled(); + } + + /** + * @dev Withdraws the beneficiary's funds. + */ + function beneficiaryWithdraw() public { + require(_state == State.Closed); + _beneficiary.transfer(address(this).balance); + } + + /** + * @dev Returns whether refundees can withdraw their deposits (be refunded). + */ + function withdrawalAllowed(address payee) public view returns (bool) { + return _state == State.Refunding; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol new file mode 100644 index 000000000..25b2694a2 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol @@ -0,0 +1,211 @@ +pragma solidity ^0.4.24; + +import "./IERC20.sol"; +import "../../math/SafeMath.sol"; + +/** + * @title Standard ERC20 token + * + * @dev Implementation of the basic standard token. + * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md + * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol + */ +contract ERC20 is IERC20 { + using SafeMath for uint256; + + mapping (address => uint256) private _balances; + + mapping (address => mapping (address => uint256)) private _allowed; + + uint256 private _totalSupply; + + /** + * @dev Total number of tokens in existence + */ + function totalSupply() public view returns (uint256) { + return _totalSupply; + } + + /** + * @dev Gets the balance of the specified address. + * @param owner The address to query the balance of. + * @return An uint256 representing the amount owned by the passed address. + */ + function balanceOf(address owner) public view returns (uint256) { + return _balances[owner]; + } + + /** + * @dev Function to check the amount of tokens that an owner allowed to a spender. + * @param owner address The address which owns the funds. + * @param spender address The address which will spend the funds. + * @return A uint256 specifying the amount of tokens still available for the spender. + */ + function allowance( + address owner, + address spender + ) + public + view + returns (uint256) + { + return _allowed[owner][spender]; + } + + /** + * @dev Transfer token for a specified address + * @param to The address to transfer to. + * @param value The amount to be transferred. + */ + function transfer(address to, uint256 value) public returns (bool) { + _transfer(msg.sender, to, value); + return true; + } + + /** + * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. + * 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 + * @param spender The address which will spend the funds. + * @param value The amount of tokens to be spent. + */ + function approve(address spender, uint256 value) public returns (bool) { + require(spender != address(0)); + + _allowed[msg.sender][spender] = value; + emit Approval(msg.sender, spender, value); + return true; + } + + /** + * @dev Transfer tokens from one address to another + * @param from address The address which you want to send tokens from + * @param to address The address which you want to transfer to + * @param value uint256 the amount of tokens to be transferred + */ + function transferFrom( + address from, + address to, + uint256 value + ) + public + returns (bool) + { + require(value <= _allowed[from][msg.sender]); + + _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); + _transfer(from, to, value); + return true; + } + + /** + * @dev Increase the amount of tokens that an owner allowed to a spender. + * approve should be called when allowed_[_spender] == 0. To increment + * allowed value is better to use this function to avoid 2 calls (and wait until + * the first transaction is mined) + * From MonolithDAO Token.sol + * @param spender The address which will spend the funds. + * @param addedValue The amount of tokens to increase the allowance by. + */ + function increaseAllowance( + address spender, + uint256 addedValue + ) + public + returns (bool) + { + require(spender != address(0)); + + _allowed[msg.sender][spender] = ( + _allowed[msg.sender][spender].add(addedValue)); + emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); + return true; + } + + /** + * @dev Decrease the amount of tokens that an owner allowed to a spender. + * approve should be called when allowed_[_spender] == 0. To decrement + * allowed value is better to use this function to avoid 2 calls (and wait until + * the first transaction is mined) + * From MonolithDAO Token.sol + * @param spender The address which will spend the funds. + * @param subtractedValue The amount of tokens to decrease the allowance by. + */ + function decreaseAllowance( + address spender, + uint256 subtractedValue + ) + public + returns (bool) + { + require(spender != address(0)); + + _allowed[msg.sender][spender] = ( + _allowed[msg.sender][spender].sub(subtractedValue)); + emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); + return true; + } + + /** + * @dev Transfer token for a specified addresses + * @param from The address to transfer from. + * @param to The address to transfer to. + * @param value The amount to be transferred. + */ + function _transfer(address from, address to, uint256 value) internal { + require(value <= _balances[from]); + require(to != address(0)); + + _balances[from] = _balances[from].sub(value); + _balances[to] = _balances[to].add(value); + emit Transfer(from, to, value); + } + + /** + * @dev Internal function that mints an amount of the token and assigns it to + * an account. This encapsulates the modification of balances such that the + * proper events are emitted. + * @param account The account that will receive the created tokens. + * @param value The amount that will be created. + */ + function _mint(address account, uint256 value) internal { + require(account != 0); + _totalSupply = _totalSupply.add(value); + _balances[account] = _balances[account].add(value); + emit Transfer(address(0), account, value); + } + + /** + * @dev Internal function that burns an amount of the token of a given + * account. + * @param account The account whose tokens will be burnt. + * @param value The amount that will be burnt. + */ + function _burn(address account, uint256 value) internal { + require(account != 0); + require(value <= _balances[account]); + + _totalSupply = _totalSupply.sub(value); + _balances[account] = _balances[account].sub(value); + emit Transfer(account, address(0), value); + } + + /** + * @dev Internal function that burns an amount of the token of a given + * account, deducting from the sender's allowance for said account. Uses the + * internal burn function. + * @param account The account whose tokens will be burnt. + * @param value The amount that will be burnt. + */ + function _burnFrom(address account, uint256 value) internal { + require(value <= _allowed[account][msg.sender]); + + // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, + // this function needs to emit an event with the updated approval. + _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( + value); + _burn(account, value); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol new file mode 100644 index 000000000..ba4a2ccbe --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol @@ -0,0 +1,27 @@ +pragma solidity ^0.4.24; + +import "./ERC20.sol"; + +/** + * @title Burnable Token + * @dev Token that can be irreversibly burned (destroyed). + */ +contract ERC20Burnable is ERC20 { + + /** + * @dev Burns a specific amount of tokens. + * @param value The amount of token to be burned. + */ + function burn(uint256 value) public { + _burn(msg.sender, value); + } + + /** + * @dev Burns a specific amount of tokens from the target address and decrements allowance + * @param from address The address which you want to send tokens from + * @param value uint256 The amount of token to be burned + */ + function burnFrom(address from, uint256 value) public { + _burnFrom(from, value); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Capped.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Capped.sol new file mode 100644 index 000000000..a80dd491c --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Capped.sol @@ -0,0 +1,31 @@ +pragma solidity ^0.4.24; + +import "./ERC20Mintable.sol"; + +/** + * @title Capped token + * @dev Mintable token with a token cap. + */ +contract ERC20Capped is ERC20Mintable { + + uint256 private _cap; + + constructor(uint256 cap) + public + { + require(cap > 0); + _cap = cap; + } + + /** + * @return the cap for the token minting. + */ + function cap() public view returns(uint256) { + return _cap; + } + + function _mint(address account, uint256 value) internal { + require(totalSupply().add(value) <= _cap); + super._mint(account, value); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol new file mode 100644 index 000000000..706dbfc46 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol @@ -0,0 +1,42 @@ +pragma solidity ^0.4.24; + +import "./IERC20.sol"; + +/** + * @title ERC20Detailed token + * @dev The decimals are only for visualization purposes. + * All the operations are done using the smallest and indivisible token unit, + * just as on Ethereum all the operations are done in wei. + */ +contract ERC20Detailed is IERC20 { + string private _name; + string private _symbol; + uint8 private _decimals; + + constructor(string name, string symbol, uint8 decimals) public { + _name = name; + _symbol = symbol; + _decimals = decimals; + } + + /** + * @return the name of the token. + */ + function name() public view returns(string) { + return _name; + } + + /** + * @return the symbol of the token. + */ + function symbol() public view returns(string) { + return _symbol; + } + + /** + * @return the number of decimals of the token. + */ + function decimals() public view returns(uint8) { + return _decimals; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol new file mode 100644 index 000000000..eb01f06e7 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol @@ -0,0 +1,28 @@ +pragma solidity ^0.4.24; + +import "./ERC20.sol"; +import "../../access/roles/MinterRole.sol"; + +/** + * @title ERC20Mintable + * @dev ERC20 minting logic + */ +contract ERC20Mintable is ERC20, MinterRole { + /** + * @dev Function to mint tokens + * @param to The address that will receive the minted tokens. + * @param value The amount of tokens to mint. + * @return A boolean that indicates if the operation was successful. + */ + function mint( + address to, + uint256 value + ) + public + onlyMinter + returns (bool) + { + _mint(to, value); + return true; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol new file mode 100644 index 000000000..8e6aa881f --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol @@ -0,0 +1,67 @@ +pragma solidity ^0.4.24; + +import "./ERC20.sol"; +import "../../lifecycle/Pausable.sol"; + +/** + * @title Pausable token + * @dev ERC20 modified with pausable transfers. + **/ +contract ERC20Pausable is ERC20, Pausable { + + function transfer( + address to, + uint256 value + ) + public + whenNotPaused + returns (bool) + { + return super.transfer(to, value); + } + + function transferFrom( + address from, + address to, + uint256 value + ) + public + whenNotPaused + returns (bool) + { + return super.transferFrom(from, to, value); + } + + function approve( + address spender, + uint256 value + ) + public + whenNotPaused + returns (bool) + { + return super.approve(spender, value); + } + + function increaseAllowance( + address spender, + uint addedValue + ) + public + whenNotPaused + returns (bool success) + { + return super.increaseAllowance(spender, addedValue); + } + + function decreaseAllowance( + address spender, + uint subtractedValue + ) + public + whenNotPaused + returns (bool success) + { + return super.decreaseAllowance(spender, subtractedValue); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol new file mode 100644 index 000000000..37e5a447c --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol @@ -0,0 +1,34 @@ +pragma solidity ^0.4.24; + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +interface IERC20 { + function totalSupply() external view returns (uint256); + + function balanceOf(address who) external view returns (uint256); + + function allowance(address owner, address spender) + external view returns (uint256); + + function transfer(address to, uint256 value) external returns (bool); + + function approve(address spender, uint256 value) + external returns (bool); + + function transferFrom(address from, address to, uint256 value) + external returns (bool); + + event Transfer( + address indexed from, + address indexed to, + uint256 value + ); + + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol new file mode 100644 index 000000000..2774afa08 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol @@ -0,0 +1,72 @@ +pragma solidity ^0.4.24; + +import "./IERC20.sol"; +import "../../math/SafeMath.sol"; + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + + using SafeMath for uint256; + + function safeTransfer( + IERC20 token, + address to, + uint256 value + ) + internal + { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + IERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + 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(msg.sender, spender) == 0)); + require(token.approve(spender, value)); + } + + function safeIncreaseAllowance( + IERC20 token, + address spender, + uint256 value + ) + internal + { + uint256 newAllowance = token.allowance(address(this), spender).add(value); + require(token.approve(spender, newAllowance)); + } + + function safeDecreaseAllowance( + IERC20 token, + address spender, + uint256 value + ) + internal + { + uint256 newAllowance = token.allowance(address(this), spender).sub(value); + require(token.approve(spender, newAllowance)); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/TokenTimelock.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/TokenTimelock.sol new file mode 100644 index 000000000..55903482b --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC20/TokenTimelock.sol @@ -0,0 +1,69 @@ +pragma solidity ^0.4.24; + +import "./SafeERC20.sol"; + +/** + * @title TokenTimelock + * @dev TokenTimelock is a token holder contract that will allow a + * beneficiary to extract the tokens after a given release time + */ +contract TokenTimelock { + using SafeERC20 for IERC20; + + // ERC20 basic token contract being held + IERC20 private _token; + + // beneficiary of tokens after they are released + address private _beneficiary; + + // timestamp when token release is enabled + uint256 private _releaseTime; + + constructor( + IERC20 token, + address beneficiary, + uint256 releaseTime + ) + public + { + // solium-disable-next-line security/no-block-members + require(releaseTime > block.timestamp); + _token = token; + _beneficiary = beneficiary; + _releaseTime = releaseTime; + } + + /** + * @return the token being held. + */ + function token() public view returns(IERC20) { + return _token; + } + + /** + * @return the beneficiary of the tokens. + */ + function beneficiary() public view returns(address) { + return _beneficiary; + } + + /** + * @return the time when the tokens are released. + */ + function releaseTime() public view returns(uint256) { + return _releaseTime; + } + + /** + * @notice Transfers tokens held by timelock to beneficiary. + */ + function release() public { + // solium-disable-next-line security/no-block-members + require(block.timestamp >= _releaseTime); + + uint256 amount = _token.balanceOf(address(this)); + require(amount > 0); + + _token.safeTransfer(_beneficiary, amount); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol new file mode 100644 index 000000000..ec0763b96 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol @@ -0,0 +1,330 @@ +pragma solidity ^0.4.24; + +import "./IERC721.sol"; +import "./IERC721Receiver.sol"; +import "../../math/SafeMath.sol"; +import "../../utils/Address.sol"; +import "../../introspection/ERC165.sol"; + +/** + * @title ERC721 Non-Fungible Token Standard basic implementation + * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md + */ +contract ERC721 is ERC165, IERC721 { + + using SafeMath for uint256; + using Address for address; + + // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` + // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` + bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; + + // Mapping from token ID to owner + mapping (uint256 => address) private _tokenOwner; + + // Mapping from token ID to approved address + mapping (uint256 => address) private _tokenApprovals; + + // Mapping from owner to number of owned token + mapping (address => uint256) private _ownedTokensCount; + + // Mapping from owner to operator approvals + mapping (address => mapping (address => bool)) private _operatorApprovals; + + bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; + /* + * 0x80ac58cd === + * bytes4(keccak256('balanceOf(address)')) ^ + * bytes4(keccak256('ownerOf(uint256)')) ^ + * bytes4(keccak256('approve(address,uint256)')) ^ + * bytes4(keccak256('getApproved(uint256)')) ^ + * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ + * bytes4(keccak256('isApprovedForAll(address,address)')) ^ + * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ + * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ + * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) + */ + + constructor() + public + { + // register the supported interfaces to conform to ERC721 via ERC165 + _registerInterface(_InterfaceId_ERC721); + } + + /** + * @dev Gets the balance of the specified address + * @param owner address to query the balance of + * @return uint256 representing the amount owned by the passed address + */ + function balanceOf(address owner) public view returns (uint256) { + require(owner != address(0)); + return _ownedTokensCount[owner]; + } + + /** + * @dev Gets the owner of the specified token ID + * @param tokenId uint256 ID of the token to query the owner of + * @return owner address currently marked as the owner of the given token ID + */ + function ownerOf(uint256 tokenId) public view returns (address) { + address owner = _tokenOwner[tokenId]; + require(owner != address(0)); + return owner; + } + + /** + * @dev Approves another address to transfer the given token ID + * The zero address indicates there is no approved address. + * There can only be one approved address per token at a given time. + * Can only be called by the token owner or an approved operator. + * @param to address to be approved for the given token ID + * @param tokenId uint256 ID of the token to be approved + */ + function approve(address to, uint256 tokenId) public { + address owner = ownerOf(tokenId); + require(to != owner); + require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); + + _tokenApprovals[tokenId] = to; + emit Approval(owner, to, tokenId); + } + + /** + * @dev Gets the approved address for a token ID, or zero if no address set + * Reverts if the token ID does not exist. + * @param tokenId uint256 ID of the token to query the approval of + * @return address currently approved for the given token ID + */ + function getApproved(uint256 tokenId) public view returns (address) { + require(_exists(tokenId)); + return _tokenApprovals[tokenId]; + } + + /** + * @dev Sets or unsets the approval of a given operator + * An operator is allowed to transfer all tokens of the sender on their behalf + * @param to operator address to set the approval + * @param approved representing the status of the approval to be set + */ + function setApprovalForAll(address to, bool approved) public { + require(to != msg.sender); + _operatorApprovals[msg.sender][to] = approved; + emit ApprovalForAll(msg.sender, to, approved); + } + + /** + * @dev Tells whether an operator is approved by a given owner + * @param owner owner address which you want to query the approval of + * @param operator operator address which you want to query the approval of + * @return bool whether the given operator is approved by the given owner + */ + function isApprovedForAll( + address owner, + address operator + ) + public + view + returns (bool) + { + return _operatorApprovals[owner][operator]; + } + + /** + * @dev Transfers the ownership of a given token ID to another address + * Usage of this method is discouraged, use `safeTransferFrom` whenever possible + * Requires the msg sender to be the owner, approved, or operator + * @param from current owner of the token + * @param to address to receive the ownership of the given token ID + * @param tokenId uint256 ID of the token to be transferred + */ + function transferFrom( + address from, + address to, + uint256 tokenId + ) + public + { + require(_isApprovedOrOwner(msg.sender, tokenId)); + require(to != address(0)); + + _clearApproval(from, tokenId); + _removeTokenFrom(from, tokenId); + _addTokenTo(to, tokenId); + + emit Transfer(from, to, tokenId); + } + + /** + * @dev Safely transfers the ownership of a given token ID to another address + * If the target address is a contract, it must implement `onERC721Received`, + * which is called upon a safe transfer, and return the magic value + * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, + * the transfer is reverted. + * + * Requires the msg sender to be the owner, approved, or operator + * @param from current owner of the token + * @param to address to receive the ownership of the given token ID + * @param tokenId uint256 ID of the token to be transferred + */ + function safeTransferFrom( + address from, + address to, + uint256 tokenId + ) + public + { + // solium-disable-next-line arg-overflow + safeTransferFrom(from, to, tokenId, ""); + } + + /** + * @dev Safely transfers the ownership of a given token ID to another address + * If the target address is a contract, it must implement `onERC721Received`, + * which is called upon a safe transfer, and return the magic value + * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, + * the transfer is reverted. + * Requires the msg sender to be the owner, approved, or operator + * @param from current owner of the token + * @param to address to receive the ownership of the given token ID + * @param tokenId uint256 ID of the token to be transferred + * @param _data bytes data to send along with a safe transfer check + */ + function safeTransferFrom( + address from, + address to, + uint256 tokenId, + bytes _data + ) + public + { + transferFrom(from, to, tokenId); + // solium-disable-next-line arg-overflow + require(_checkOnERC721Received(from, to, tokenId, _data)); + } + + /** + * @dev Returns whether the specified token exists + * @param tokenId uint256 ID of the token to query the existence of + * @return whether the token exists + */ + function _exists(uint256 tokenId) internal view returns (bool) { + address owner = _tokenOwner[tokenId]; + return owner != address(0); + } + + /** + * @dev Returns whether the given spender can transfer a given token ID + * @param spender address of the spender to query + * @param tokenId uint256 ID of the token to be transferred + * @return bool whether the msg.sender is approved for the given token ID, + * is an operator of the owner, or is the owner of the token + */ + function _isApprovedOrOwner( + address spender, + uint256 tokenId + ) + internal + view + returns (bool) + { + address owner = ownerOf(tokenId); + // Disable solium check because of + // https://github.com/duaraghav8/Solium/issues/175 + // solium-disable-next-line operator-whitespace + return ( + spender == owner || + getApproved(tokenId) == spender || + isApprovedForAll(owner, spender) + ); + } + + /** + * @dev Internal function to mint a new token + * Reverts if the given token ID already exists + * @param to The address that will own the minted token + * @param tokenId uint256 ID of the token to be minted by the msg.sender + */ + function _mint(address to, uint256 tokenId) internal { + require(to != address(0)); + _addTokenTo(to, tokenId); + emit Transfer(address(0), to, tokenId); + } + + /** + * @dev Internal function to burn a specific token + * Reverts if the token does not exist + * @param tokenId uint256 ID of the token being burned by the msg.sender + */ + function _burn(address owner, uint256 tokenId) internal { + _clearApproval(owner, tokenId); + _removeTokenFrom(owner, tokenId); + emit Transfer(owner, address(0), tokenId); + } + + /** + * @dev Internal function to add a token ID to the list of a given address + * Note that this function is left internal to make ERC721Enumerable possible, but is not + * intended to be called by custom derived contracts: in particular, it emits no Transfer event. + * @param to address representing the new owner of the given token ID + * @param tokenId uint256 ID of the token to be added to the tokens list of the given address + */ + function _addTokenTo(address to, uint256 tokenId) internal { + require(_tokenOwner[tokenId] == address(0)); + _tokenOwner[tokenId] = to; + _ownedTokensCount[to] = _ownedTokensCount[to].add(1); + } + + /** + * @dev Internal function to remove a token ID from the list of a given address + * Note that this function is left internal to make ERC721Enumerable possible, but is not + * intended to be called by custom derived contracts: in particular, it emits no Transfer event, + * and doesn't clear approvals. + * @param from address representing the previous owner of the given token ID + * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address + */ + function _removeTokenFrom(address from, uint256 tokenId) internal { + require(ownerOf(tokenId) == from); + _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); + _tokenOwner[tokenId] = address(0); + } + + /** + * @dev Internal function to invoke `onERC721Received` on a target address + * The call is not executed if the target address is not a contract + * @param from address representing the previous owner of the given token ID + * @param to target address that will receive the tokens + * @param tokenId uint256 ID of the token to be transferred + * @param _data bytes optional data to send along with the call + * @return whether the call correctly returned the expected magic value + */ + function _checkOnERC721Received( + address from, + address to, + uint256 tokenId, + bytes _data + ) + internal + returns (bool) + { + if (!to.isContract()) { + return true; + } + bytes4 retval = IERC721Receiver(to).onERC721Received( + msg.sender, from, tokenId, _data); + return (retval == _ERC721_RECEIVED); + } + + /** + * @dev Private function to clear current approval of a given token ID + * Reverts if the given address is not indeed the owner of the token + * @param owner owner of the token + * @param tokenId uint256 ID of the token to be transferred + */ + function _clearApproval(address owner, uint256 tokenId) private { + require(ownerOf(tokenId) == owner); + if (_tokenApprovals[tokenId] != address(0)) { + _tokenApprovals[tokenId] = address(0); + } + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Burnable.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Burnable.sol new file mode 100644 index 000000000..3fc0277e5 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Burnable.sol @@ -0,0 +1,12 @@ +pragma solidity ^0.4.24; + +import "./ERC721.sol"; + +contract ERC721Burnable is ERC721 { + function burn(uint256 tokenId) + public + { + require(_isApprovedOrOwner(msg.sender, tokenId)); + _burn(ownerOf(tokenId), tokenId); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Enumerable.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Enumerable.sol new file mode 100644 index 000000000..c85514720 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Enumerable.sol @@ -0,0 +1,150 @@ +pragma solidity ^0.4.24; + +import "./IERC721Enumerable.sol"; +import "./ERC721.sol"; +import "../../introspection/ERC165.sol"; + +contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable { + // Mapping from owner to list of owned token IDs + mapping(address => uint256[]) private _ownedTokens; + + // Mapping from token ID to index of the owner tokens list + mapping(uint256 => uint256) private _ownedTokensIndex; + + // Array with all token ids, used for enumeration + uint256[] private _allTokens; + + // Mapping from token id to position in the allTokens array + mapping(uint256 => uint256) private _allTokensIndex; + + bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; + /** + * 0x780e9d63 === + * bytes4(keccak256('totalSupply()')) ^ + * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ + * bytes4(keccak256('tokenByIndex(uint256)')) + */ + + /** + * @dev Constructor function + */ + constructor() public { + // register the supported interface to conform to ERC721 via ERC165 + _registerInterface(_InterfaceId_ERC721Enumerable); + } + + /** + * @dev Gets the token ID at a given index of the tokens list of the requested owner + * @param owner address owning the tokens list to be accessed + * @param index uint256 representing the index to be accessed of the requested tokens list + * @return uint256 token ID at the given index of the tokens list owned by the requested address + */ + function tokenOfOwnerByIndex( + address owner, + uint256 index + ) + public + view + returns (uint256) + { + require(index < balanceOf(owner)); + return _ownedTokens[owner][index]; + } + + /** + * @dev Gets the total amount of tokens stored by the contract + * @return uint256 representing the total amount of tokens + */ + function totalSupply() public view returns (uint256) { + return _allTokens.length; + } + + /** + * @dev Gets the token ID at a given index of all the tokens in this contract + * Reverts if the index is greater or equal to the total number of tokens + * @param index uint256 representing the index to be accessed of the tokens list + * @return uint256 token ID at the given index of the tokens list + */ + function tokenByIndex(uint256 index) public view returns (uint256) { + require(index < totalSupply()); + return _allTokens[index]; + } + + /** + * @dev Internal function to add a token ID to the list of a given address + * This function is internal due to language limitations, see the note in ERC721.sol. + * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event. + * @param to address representing the new owner of the given token ID + * @param tokenId uint256 ID of the token to be added to the tokens list of the given address + */ + function _addTokenTo(address to, uint256 tokenId) internal { + super._addTokenTo(to, tokenId); + uint256 length = _ownedTokens[to].length; + _ownedTokens[to].push(tokenId); + _ownedTokensIndex[tokenId] = length; + } + + /** + * @dev Internal function to remove a token ID from the list of a given address + * This function is internal due to language limitations, see the note in ERC721.sol. + * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event, + * and doesn't clear approvals. + * @param from address representing the previous owner of the given token ID + * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address + */ + function _removeTokenFrom(address from, uint256 tokenId) internal { + super._removeTokenFrom(from, tokenId); + + // To prevent a gap in the array, we store the last token in the index of the token to delete, and + // then delete the last slot. + uint256 tokenIndex = _ownedTokensIndex[tokenId]; + uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); + uint256 lastToken = _ownedTokens[from][lastTokenIndex]; + + _ownedTokens[from][tokenIndex] = lastToken; + // This also deletes the contents at the last position of the array + _ownedTokens[from].length--; + + // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to + // be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping + // the lastToken to the first position, and then dropping the element placed in the last position of the list + + _ownedTokensIndex[tokenId] = 0; + _ownedTokensIndex[lastToken] = tokenIndex; + } + + /** + * @dev Internal function to mint a new token + * Reverts if the given token ID already exists + * @param to address the beneficiary that will own the minted token + * @param tokenId uint256 ID of the token to be minted by the msg.sender + */ + function _mint(address to, uint256 tokenId) internal { + super._mint(to, tokenId); + + _allTokensIndex[tokenId] = _allTokens.length; + _allTokens.push(tokenId); + } + + /** + * @dev Internal function to burn a specific token + * Reverts if the token does not exist + * @param owner owner of the token to burn + * @param tokenId uint256 ID of the token being burned by the msg.sender + */ + function _burn(address owner, uint256 tokenId) internal { + super._burn(owner, tokenId); + + // Reorg all tokens array + uint256 tokenIndex = _allTokensIndex[tokenId]; + uint256 lastTokenIndex = _allTokens.length.sub(1); + uint256 lastToken = _allTokens[lastTokenIndex]; + + _allTokens[tokenIndex] = lastToken; + _allTokens[lastTokenIndex] = 0; + + _allTokens.length--; + _allTokensIndex[tokenId] = 0; + _allTokensIndex[lastToken] = tokenIndex; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol new file mode 100644 index 000000000..293637501 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol @@ -0,0 +1,18 @@ +pragma solidity ^0.4.24; + +import "./ERC721.sol"; +import "./ERC721Enumerable.sol"; +import "./ERC721Metadata.sol"; + +/** + * @title Full ERC721 Token + * This implementation includes all the required and some optional functionality of the ERC721 standard + * Moreover, it includes approve all functionality using operator terminology + * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md + */ +contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { + constructor(string name, string symbol) ERC721Metadata(name, symbol) + public + { + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol new file mode 100644 index 000000000..cf0e9ce55 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol @@ -0,0 +1,17 @@ +pragma solidity ^0.4.24; + +import "./IERC721Receiver.sol"; + +contract ERC721Holder is IERC721Receiver { + function onERC721Received( + address, + address, + uint256, + bytes + ) + public + returns(bytes4) + { + return this.onERC721Received.selector; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol new file mode 100644 index 000000000..bd1105188 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol @@ -0,0 +1,87 @@ +pragma solidity ^0.4.24; + +import "./ERC721.sol"; +import "./IERC721Metadata.sol"; +import "../../introspection/ERC165.sol"; + +contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { + // Token name + string private _name; + + // Token symbol + string private _symbol; + + // Optional mapping for token URIs + mapping(uint256 => string) private _tokenURIs; + + bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; + /** + * 0x5b5e139f === + * bytes4(keccak256('name()')) ^ + * bytes4(keccak256('symbol()')) ^ + * bytes4(keccak256('tokenURI(uint256)')) + */ + + /** + * @dev Constructor function + */ + constructor(string name, string symbol) public { + _name = name; + _symbol = symbol; + + // register the supported interfaces to conform to ERC721 via ERC165 + _registerInterface(InterfaceId_ERC721Metadata); + } + + /** + * @dev Gets the token name + * @return string representing the token name + */ + function name() external view returns (string) { + return _name; + } + + /** + * @dev Gets the token symbol + * @return string representing the token symbol + */ + function symbol() external view returns (string) { + return _symbol; + } + + /** + * @dev Returns an URI for a given token ID + * Throws if the token ID does not exist. May return an empty string. + * @param tokenId uint256 ID of the token to query + */ + function tokenURI(uint256 tokenId) external view returns (string) { + require(_exists(tokenId)); + return _tokenURIs[tokenId]; + } + + /** + * @dev Internal function to set the token URI for a given token + * Reverts if the token ID does not exist + * @param tokenId uint256 ID of the token to set its URI + * @param uri string URI to assign + */ + function _setTokenURI(uint256 tokenId, string uri) internal { + require(_exists(tokenId)); + _tokenURIs[tokenId] = uri; + } + + /** + * @dev Internal function to burn a specific token + * Reverts if the token does not exist + * @param owner owner of the token to burn + * @param tokenId uint256 ID of the token being burned by the msg.sender + */ + function _burn(address owner, uint256 tokenId) internal { + super._burn(owner, tokenId); + + // Clear metadata (if any) + if (bytes(_tokenURIs[tokenId]).length != 0) { + delete _tokenURIs[tokenId]; + } + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721MetadataMintable.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721MetadataMintable.sol new file mode 100644 index 000000000..95a9f2124 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721MetadataMintable.sol @@ -0,0 +1,32 @@ +pragma solidity ^0.4.24; + +import "./ERC721Metadata.sol"; +import "../../access/roles/MinterRole.sol"; + + +/** + * @title ERC721MetadataMintable + * @dev ERC721 minting logic with metadata + */ +contract ERC721MetadataMintable is ERC721, ERC721Metadata, MinterRole { + /** + * @dev Function to mint tokens + * @param to The address that will receive the minted tokens. + * @param tokenId The token id to mint. + * @param tokenURI The token URI of the minted token. + * @return A boolean that indicates if the operation was successful. + */ + function mintWithTokenURI( + address to, + uint256 tokenId, + string tokenURI + ) + public + onlyMinter + returns (bool) + { + _mint(to, tokenId); + _setTokenURI(tokenId, tokenURI); + return true; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Mintable.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Mintable.sol new file mode 100644 index 000000000..74b7b0186 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Mintable.sol @@ -0,0 +1,28 @@ +pragma solidity ^0.4.24; + +import "./ERC721.sol"; +import "../../access/roles/MinterRole.sol"; + +/** + * @title ERC721Mintable + * @dev ERC721 minting logic + */ +contract ERC721Mintable is ERC721, MinterRole { + /** + * @dev Function to mint tokens + * @param to The address that will receive the minted tokens. + * @param tokenId The token id to mint. + * @return A boolean that indicates if the operation was successful. + */ + function mint( + address to, + uint256 tokenId + ) + public + onlyMinter + returns (bool) + { + _mint(to, tokenId); + return true; + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Pausable.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Pausable.sol new file mode 100644 index 000000000..c66d9da1f --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/ERC721Pausable.sol @@ -0,0 +1,41 @@ +pragma solidity ^0.4.24; + +import "./ERC721.sol"; +import "../../lifecycle/Pausable.sol"; + +/** + * @title ERC721 Non-Fungible Pausable token + * @dev ERC721 modified with pausable transfers. + **/ +contract ERC721Pausable is ERC721, Pausable { + function approve( + address to, + uint256 tokenId + ) + public + whenNotPaused + { + super.approve(to, tokenId); + } + + function setApprovalForAll( + address to, + bool approved + ) + public + whenNotPaused + { + super.setApprovalForAll(to, approved); + } + + function transferFrom( + address from, + address to, + uint256 tokenId + ) + public + whenNotPaused + { + super.transferFrom(from, to, tokenId); + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721.sol new file mode 100644 index 000000000..24bc6a242 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721.sol @@ -0,0 +1,49 @@ +pragma solidity ^0.4.24; + +import "../../introspection/IERC165.sol"; + +/** + * @title ERC721 Non-Fungible Token Standard basic interface + * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md + */ +contract IERC721 is IERC165 { + + event Transfer( + address indexed from, + address indexed to, + uint256 indexed tokenId + ); + event Approval( + address indexed owner, + address indexed approved, + uint256 indexed tokenId + ); + event ApprovalForAll( + address indexed owner, + address indexed operator, + bool approved + ); + + function balanceOf(address owner) public view returns (uint256 balance); + function ownerOf(uint256 tokenId) public view returns (address owner); + + function approve(address to, uint256 tokenId) public; + function getApproved(uint256 tokenId) + public view returns (address operator); + + function setApprovalForAll(address operator, bool _approved) public; + function isApprovedForAll(address owner, address operator) + public view returns (bool); + + function transferFrom(address from, address to, uint256 tokenId) public; + function safeTransferFrom(address from, address to, uint256 tokenId) + public; + + function safeTransferFrom( + address from, + address to, + uint256 tokenId, + bytes data + ) + public; +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721Enumerable.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721Enumerable.sol new file mode 100644 index 000000000..b772f2507 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721Enumerable.sol @@ -0,0 +1,20 @@ +pragma solidity ^0.4.24; + +import "./IERC721.sol"; + +/** + * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension + * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md + */ +contract IERC721Enumerable is IERC721 { + function totalSupply() public view returns (uint256); + function tokenOfOwnerByIndex( + address owner, + uint256 index + ) + public + view + returns (uint256 tokenId); + + function tokenByIndex(uint256 index) public view returns (uint256); +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721Full.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721Full.sol new file mode 100644 index 000000000..90d8c21d8 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721Full.sol @@ -0,0 +1,12 @@ +pragma solidity ^0.4.24; + +import "./IERC721.sol"; +import "./IERC721Enumerable.sol"; +import "./IERC721Metadata.sol"; + +/** + * @title ERC-721 Non-Fungible Token Standard, full implementation interface + * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md + */ +contract IERC721Full is IERC721, IERC721Enumerable, IERC721Metadata { +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721Metadata.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721Metadata.sol new file mode 100644 index 000000000..15b5ae4c6 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721Metadata.sol @@ -0,0 +1,13 @@ +pragma solidity ^0.4.24; + +import "./IERC721.sol"; + +/** + * @title ERC-721 Non-Fungible Token Standard, optional metadata extension + * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md + */ +contract IERC721Metadata is IERC721 { + function name() external view returns (string); + function symbol() external view returns (string); + function tokenURI(uint256 tokenId) external view returns (string); +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol new file mode 100644 index 000000000..e692f7e2c --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol @@ -0,0 +1,31 @@ +pragma solidity ^0.4.24; + +/** + * @title ERC721 token receiver interface + * @dev Interface for any contract that wants to support safeTransfers + * from ERC721 asset contracts. + */ +contract IERC721Receiver { + /** + * @notice Handle the receipt of an NFT + * @dev The ERC721 smart contract calls this function on the recipient + * after a `safeTransfer`. This function MUST return the function selector, + * otherwise the caller will revert the transaction. The selector to be + * returned can be obtained as `this.onERC721Received.selector`. This + * function MAY throw to revert and reject the transfer. + * Note: the ERC721 contract address is always the message sender. + * @param operator The address which called `safeTransferFrom` function + * @param from The address which previously owned the token + * @param tokenId The NFT identifier which is being transferred + * @param data Additional data with no specified format + * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` + */ + function onERC721Received( + address operator, + address from, + uint256 tokenId, + bytes data + ) + public + returns(bytes4); +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/utils/Address.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/utils/Address.sol new file mode 100644 index 000000000..92a43ff9c --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/utils/Address.sol @@ -0,0 +1,28 @@ +pragma solidity ^0.4.24; + +/** + * Utility library of inline functions on addresses + */ +library Address { + + /** + * Returns whether the target address is a contract + * @dev This function will return false if invoked during the constructor of a contract, + * as the code is not actually created until after the constructor finishes. + * @param account address of the account to check + * @return whether the target address is a contract + */ + function isContract(address account) internal view returns (bool) { + uint256 size; + // XXX Currently there is no better way to check if there is a contract in an address + // than to check the size of the code at that address. + // See https://ethereum.stackexchange.com/a/14016/36603 + // for more details about how this works. + // TODO Check this again before the Serenity release, because all addresses will be + // contracts then. + // solium-disable-next-line security/no-inline-assembly + assembly { size := extcodesize(account) } + return size > 0; + } + +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/utils/Arrays.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/utils/Arrays.sol new file mode 100644 index 000000000..6882ea995 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/utils/Arrays.sol @@ -0,0 +1,56 @@ +pragma solidity ^0.4.23; + +import "../math/Math.sol"; + + +/** + * @title Arrays + * @dev Utility library of inline array functions + */ +library Arrays { + + /** + * @dev Upper bound search function which is kind of binary search algoritm. It searches sorted + * array to find index of the element value. If element is found then returns it's index otherwise + * it returns index of first element which is grater than searched value. If searched element is + * bigger than any array element function then returns first index after last element (i.e. all + * values inside the array are smaller than the target). Complexity O(log n). + * @param array The array sorted in ascending order. + * @param element The element's value to be find. + * @return The calculated index value. Returns 0 for empty array. + */ + function findUpperBound( + uint256[] storage array, + uint256 element + ) + internal + view + returns (uint256) + { + if (array.length == 0) { + return 0; + } + + uint256 low = 0; + uint256 high = array.length; + + while (low < high) { + uint256 mid = Math.average(low, high); + + // Note that mid will always be strictly less than high (i.e. it will be a valid array index) + // because Math.average rounds down (it does integer division with truncation). + if (array[mid] > element) { + high = mid; + } else { + low = mid + 1; + } + } + + // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. + if (low > 0 && array[low - 1] == element) { + return low - 1; + } else { + return low; + } + } +} diff --git a/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol new file mode 100644 index 000000000..7a2895da2 --- /dev/null +++ b/labs/algo-erc20-token/src/AdvancedAlgos.AlgoErc20Token/SmartContracts/src/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol @@ -0,0 +1,34 @@ +pragma solidity ^0.4.24; + +/** + * @title Helps contracts guard against reentrancy attacks. + * @author Remco Bloemen , Eenae + * @dev If you mark a function `nonReentrant`, you should also + * mark it `external`. + */ +contract ReentrancyGuard { + + /// @dev counter to allow mutex lock with only one SSTORE operation + uint256 private _guardCounter; + + constructor() internal { + // The counter starts at one to prevent changing it from zero to a non-zero + // value, which is a more expensive operation. + _guardCounter = 1; + } + + /** + * @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 make it call a + * `private` function that does the actual work. + */ + modifier nonReentrant() { + _guardCounter += 1; + uint256 localCounter = _guardCounter; + _; + require(localCounter == _guardCounter); + } + +} diff --git a/labs/algo-erc20-token/test/AdvancedAlgos.AlgoErc20Token.IntegrationTests/AdvancedAlgos.AlgoErc20Token.IntegrationTests.csproj b/labs/algo-erc20-token/test/AdvancedAlgos.AlgoErc20Token.IntegrationTests/AdvancedAlgos.AlgoErc20Token.IntegrationTests.csproj new file mode 100644 index 000000000..b7afbca3b --- /dev/null +++ b/labs/algo-erc20-token/test/AdvancedAlgos.AlgoErc20Token.IntegrationTests/AdvancedAlgos.AlgoErc20Token.IntegrationTests.csproj @@ -0,0 +1,20 @@ + + + + netcoreapp2.1 + false + latest + + + + + + + + + + + + + + diff --git a/labs/algo-erc20-token/test/AdvancedAlgos.AlgoErc20Token.IntegrationTests/AlgoTokenV1Tests.cs b/labs/algo-erc20-token/test/AdvancedAlgos.AlgoErc20Token.IntegrationTests/AlgoTokenV1Tests.cs new file mode 100644 index 000000000..ec61b0cc6 --- /dev/null +++ b/labs/algo-erc20-token/test/AdvancedAlgos.AlgoErc20Token.IntegrationTests/AlgoTokenV1Tests.cs @@ -0,0 +1,74 @@ +using System; +using System.Numerics; +using System.Threading.Tasks; +using AdvancedAlgos.AlgoErc20Token.EthClientExtensions; +using AdvancedAlgos.AlgoErc20Token.EthClientExtensions.Exceptions; +using Nethereum.Web3; +using Nethereum.Web3.Accounts; +using Xunit; + +namespace AdvancedAlgos.AlgoErc20Token.IntegrationTests +{ + public class AlgoTokenV1Tests + { + private const long INITIAL_SUPPLY = 1000000000; + private const byte TOKEN_DECIMALS = 18; + + private static BigInteger _tokenFactor = BigInteger.Pow(10, TOKEN_DECIMALS); + + [Fact] + public async Task DeployContractAndTransferTokensTest() + { + EthNetwork.UseGethTestNet(); + + var account1 = new Account(EthNetwork.Instance.PrefundedPrivateKey); + var account2 = EthAccountFactory.Create(); + + var web3 = new Web3(account1, EthNetwork.Instance.Url); + + var contract = new AlgoTokenV1(); + + await contract.DeployAsync(web3, EthNetwork.Instance.GasPrice); + + Assert.Equal(INITIAL_SUPPLY.Algo(), await contract.BalanceOfAsync(account1.Address)); + + await contract.TransferAsync(EthNetwork.Instance.GasPrice, account2.Address, 2.Algo()); + + Assert.Equal(2.Algo(), await contract.BalanceOfAsync(account2.Address)); + } + + [Fact] + public async Task PausableFeatureTest() + { + EthNetwork.UseGethTestNet(); + + var account1 = new Account(EthNetwork.Instance.PrefundedPrivateKey); + var account2 = EthAccountFactory.Create(); + + var web3 = new Web3(account1, EthNetwork.Instance.Url); + + var contract = new AlgoTokenV1(); + + await contract.DeployAsync(web3, EthNetwork.Instance.GasPrice); + + await contract.TransferAsync(EthNetwork.Instance.GasPrice, account2.Address, 2.Algo()); + + Assert.Equal(2.Algo(), await contract.BalanceOfAsync(account2.Address)); + + await contract.PauseAsync(EthNetwork.Instance.GasPrice); + + await Assert.ThrowsAsync( + () => contract.TransferAsync(EthNetwork.Instance.GasPrice, account2.Address, 2.Algo())); + + Assert.Equal(2.Algo(), await contract.BalanceOfAsync(account2.Address)); + + await contract.UnpauseAsync(EthNetwork.Instance.GasPrice); + + Assert.Equal(2.Algo(), await contract.BalanceOfAsync(account2.Address)); + + await contract.TransferAsync(EthNetwork.Instance.GasPrice, account2.Address, 2.Algo()); + + Assert.Equal(4.Algo(), await contract.BalanceOfAsync(account2.Address)); + } + } +} diff --git a/labs/algo-erc20-token/test/AdvancedAlgos.AlgoErc20Token.IntegrationTests/EthNetwork.cs b/labs/algo-erc20-token/test/AdvancedAlgos.AlgoErc20Token.IntegrationTests/EthNetwork.cs new file mode 100644 index 000000000..b34dbe31d --- /dev/null +++ b/labs/algo-erc20-token/test/AdvancedAlgos.AlgoErc20Token.IntegrationTests/EthNetwork.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Nethereum.Hex.HexTypes; +using Nethereum.RPC.Accounts; +using Nethereum.Util; +using Nethereum.Web3; +using Nethereum.Web3.Accounts; + +namespace AdvancedAlgos.AlgoErc20Token.IntegrationTests +{ + public class EthNetwork + { + public const int TRANSACTION_BASE_FEE = 21000; + + public static EthNetwork Instance { get; private set; } + + private SemaphoreSlim _refillSync = new SemaphoreSlim(1, 1); + + public string Url { get; private set; } + public string PrefundedAddress { get; private set; } + public string PrefundedPrivateKey { get; private set; } + public BigInteger GasPrice { get; private set; } + public BigInteger TxBaseFeeWei => GasPrice * TRANSACTION_BASE_FEE; + + public static void UseGanacheTestNet() + { + Instance = new EthNetwork + { + Url = "http://127.0.0.1:8545", + PrefundedAddress = "0x06bB4674A4b08d07186b721378C7e241eD85443b", + PrefundedPrivateKey = "0936af475d2701538aad321f87e0a51f2b297634653393e8cab7290a674009a5", + GasPrice = 2000000000 + }; + } + + public static void UseGethTestNet() + { + Instance = new EthNetwork + { + Url = "http://10.4.0.4:8545", + PrefundedAddress = "0x88474Ec3cfddfC943d3E42C94763D43f181A5a83", + PrefundedPrivateKey = "0x69970bd6c1b6cfbffea16656c27ff7b330b751ed5e46c1644b54a642871f4bbb", + GasPrice = 2000000000 + }; + } + + public Task RefillAsync(IAccount account) + { + return RefillAsync(account, UnitConversion.Convert.ToWei(1)); + } + + public async Task RefillAsync(IAccount account, BigInteger weis) + { + await _refillSync.WaitAsync(); + try + { + var prefundedAccount = new Account(PrefundedPrivateKey); + var web3 = new Web3(prefundedAccount, Url); + var recepit = await web3.TransactionManager.TransactionReceiptService.SendRequestAndWaitForReceiptAsync(() => + web3.TransactionManager.SendTransactionAsync(prefundedAccount.Address, account.Address, new HexBigInteger(weis)) + ); + } + finally + { + _refillSync.Release(); + } + } + } +}