Пример #1
0
 /// <summary>
 /// Constructor initializing a mining pool contract.
 /// </summary>
 /// <param name="state">Smart contract state.</param>
 /// <param name="minedToken">The address of the token being mined.</param>
 /// <param name="stakingToken">The address of the liquidity pool token used for mining.</param>
 public OpdexMiningPool(ISmartContractState state, Address minedToken, Address stakingToken) : base(state)
 {
     MinedToken       = minedToken;
     StakingToken     = stakingToken;
     MiningGovernance = GetMiningGovernance();
     MiningDuration   = GetMiningDuration();
 }
Пример #2
0
    public Token(ISmartContractState state)
        : base(state)
    {
        this.Owner = this.Message.Sender;

        this.Balances = this.PersistentState.GetUInt64Mapping("Balances");
    }
 public ThermostatContract(ISmartContractState smartContractState, Address user, int targetTemperature)
     : base(smartContractState)
 {
     this.Installer         = Message.Sender;
     this.User              = user;
     this.TargetTemperature = targetTemperature;
 }
Пример #4
0
        ///<inheritdoc />
        public ITransferResult Transfer(ISmartContractState smartContractState, Address addressTo, ulong amountToTransfer)
        {
            this.logger.LogTrace("({0}:{1},{2}:{3})", nameof(addressTo), addressTo, nameof(amountToTransfer), amountToTransfer);

            // TODO: Spend BaseFee here

            EnsureContractHasEnoughBalance(smartContractState, amountToTransfer);

            // Discern whether this is a contract or an ordinary address.
            byte[] contractCode = this.contractStateRepository.GetCode(addressTo.ToUint160(this.network));
            if (contractCode == null || contractCode.Length == 0)
            {
                this.internalTransferList.Add(new TransferInfo
                {
                    From  = smartContractState.Message.ContractAddress.ToUint160(this.network),
                    To    = addressTo.ToUint160(this.network),
                    Value = amountToTransfer
                });

                this.logger.LogTrace("(-)[TRANSFER_TO_SENDER]:Transfer {0} from {1} to {2}.", smartContractState.Message.ContractAddress, addressTo, amountToTransfer);
                return(TransferResult.Empty());
            }

            this.logger.LogTrace("(-)[TRANSFER_TO_CONTRACT]");

            // Calling a receive handler:
            string methodName = MethodCall.ExternalReceiveHandlerName;

            object[] parameters = new object[] { };
            ulong    gasBudget  = DefaultGasLimit; // for Transfer always send limited gas to prevent re-entrance.

            return(ExecuteTransferFundsToContract(contractCode, smartContractState, addressTo, amountToTransfer, methodName, parameters, gasBudget));
        }
Пример #5
0
        /// <summary>
        /// Loads the contract bytecode and returns an <see cref="IContract"/> representing an uninitialized contract instance.
        /// </summary>
        private Result <IContract> Load(
            ContractByteCode byteCode,
            string typeName,
            uint160 address,
            ISmartContractState contractState)
        {
            Result <IContractAssembly> assemblyLoadResult = this.assemblyLoader.Load(byteCode);

            if (!assemblyLoadResult.IsSuccess)
            {
                return(Result.Fail <IContract>(assemblyLoadResult.Error));
            }

            IContractAssembly contractAssembly = assemblyLoadResult.Value;

            Type type = contractAssembly.GetType(typeName);

            if (type == null)
            {
                return(Result.Fail <IContract>("Type not found!"));
            }

            IContract contract = Contract.CreateUninitialized(type, contractState, address);

            return(Result.Ok(contract));
        }
        private StateTransitionResult ApplyCall(IState state, CallMessage message, byte[] contractCode)
        {
            var gasMeter = new GasMeter(message.GasLimit);

            gasMeter.Spend((Gas)GasPriceList.BaseCost);

            // This needs to happen after the base fee is charged, which is why it's in here.
            // TODO - Remove this check. It isn't possible for the method name to be null.
            if (message.Method.Name == null)
            {
                return(StateTransitionResult.Fail(gasMeter.GasConsumed, StateTransitionErrorKind.NoMethodName));
            }

            string type = state.ContractState.GetContractType(message.To);

            ISmartContractState smartContractState = state.CreateSmartContractState(state, gasMeter, message.To, message, state.ContractState);

            VmExecutionResult result = this.Vm.ExecuteMethod(smartContractState, message.Method, contractCode, type);

            bool revert = !result.IsSuccess;

            if (revert)
            {
                return(StateTransitionResult.Fail(
                           gasMeter.GasConsumed,
                           result.Error));
            }

            return(StateTransitionResult.Ok(
                       gasMeter.GasConsumed,
                       message.To,
                       result.Success.Result
                       ));
        }
Пример #7
0
 private Contract(SmartContract instance, Type type, ISmartContractState state, uint160 address)
 {
     this.instance = instance;
     this.State    = state;
     this.Type     = type;
     this.Address  = address;
 }
Пример #8
0
 public PrivateYesNoVote(ISmartContractState smartContractState, ulong duration, byte[] addresses)
     : base(smartContractState)
 {
     VotePeriodEndBlock = checked (Block.Number + duration);
     Owner = Message.Sender;
     SetVotersExecute(addresses);
 }
Пример #9
0
        /// <summary>
        /// Invokes a smart contract's constructor with the provided parameters
        /// </summary>
        public static LifecycleResult Construct(Type type, ISmartContractState state, params object[] parameters)
        {
            object[] newParams;

            if (parameters != null && parameters.Length > 0)
            {
                newParams    = new object[parameters.Length + 1];
                newParams[0] = state;

                Array.Copy(parameters, 0, newParams, 1, parameters.Length);
            }
            else
            {
                newParams = new object[] { state };
            }

            try
            {
                var smartContract = (SmartContract)Activator.CreateInstance(type, newParams);
                return(new LifecycleResult(smartContract));
            }
            catch (Exception e)
            {
                return(new LifecycleResult(e));
            }
        }
Пример #10
0
 public Auction(ISmartContractState smartContractState, ulong durationBlocks)
     : base(smartContractState)
 {
     this.Owner    = this.Message.Sender;
     this.EndBlock = this.Block.Number + durationBlocks;
     this.HasEnded = false;
 }
Пример #11
0
 public DirectAid(ISmartContractState smartContractState, ulong startTime, ulong endTime)
     : base(smartContractState)
 {
     Owner     = Message.Sender;
     StartTime = startTime;
     EndTime   = endTime;
 }
Пример #12
0
 public Cat(ISmartContractState smartContractState, int catNumber) : base(smartContractState)
 {
     CatNumber = catNumber;
     Log(new CatCreated {
         CatNumber = catNumber
     });
 }
Пример #13
0
 public BasicParameters(ISmartContractState smartContractState, ulong number1, ulong number2) : base(smartContractState)
 {
     this.PersistentState.SetBool("Created", true);
     this.Log(new Created {
         From = this.Message.Sender
     });
 }
Пример #14
0
        private StateTransitionResult ApplyCreate(IState state,
                                                  object[] parameters,
                                                  byte[] code,
                                                  BaseMessage message,
                                                  uint160 address,
                                                  RuntimeObserver.IGasMeter gasMeter,
                                                  string type = null)
        {
            state.ContractState.CreateAccount(address);

            ISmartContractState smartContractState = state.CreateSmartContractState(state, gasMeter, address, message, state.ContractState);

            VmExecutionResult result = this.Vm.Create(state.ContractState, smartContractState, gasMeter, code, parameters, type);

            bool revert = !result.IsSuccess;

            if (revert)
            {
                return(StateTransitionResult.Fail(
                           gasMeter.GasConsumed,
                           result.Error));
            }

            return(StateTransitionResult.Ok(
                       gasMeter.GasConsumed,
                       address,
                       result.Success.Result
                       ));
        }
        private StateTransitionResult ApplyCall(IState state, CallMessage message, byte[] contractCode, ExecutionContext executionContext)
        {
            // This needs to happen after the base fee is charged, which is why it's in here.

            if (message.Method.Name == null)
            {
                return(StateTransitionResult.Fail(executionContext.GasMeter.GasConsumed, StateTransitionErrorKind.NoMethodName));
            }

            string type = state.ContractState.GetContractType(message.To);

            ISmartContractState smartContractState = state.CreateSmartContractState(state, executionContext.GasMeter, message.To, message, state.ContractState);

            VmExecutionResult result = this.Vm.ExecuteMethod(smartContractState, executionContext, message.Method, contractCode, type);

            bool revert = !result.IsSuccess;

            if (revert)
            {
                return(StateTransitionResult.Fail(
                           executionContext.GasMeter.GasConsumed,
                           result.Error));
            }

            return(StateTransitionResult.Ok(
                       executionContext.GasMeter.GasConsumed,
                       message.To,
                       result.Success.Result
                       ));
        }
Пример #16
0
        ///<inheritdoc />
        public ITransferResult TransferFunds(ISmartContractState smartContractState, Address addressTo, ulong amountToTransfer, TransferFundsToContract contractDetails)
        {
            this.logger.LogTrace("({0}:{1},{2}:{3})", nameof(addressTo), addressTo, nameof(amountToTransfer), amountToTransfer);

            // TODO: Spend BaseFee here

            var balance = smartContractState.GetBalance();

            if (balance < amountToTransfer)
            {
                this.logger.LogTrace("(-)[INSUFFICIENT_BALANCE]:{0}={1}", nameof(balance), balance);
                throw new InsufficientBalanceException();
            }

            // Discern whether this is a contract or an ordinary address.
            byte[] contractCode = this.contractStateRepository.GetCode(addressTo.ToUint160(this.network));
            if (contractCode == null || contractCode.Length == 0)
            {
                this.internalTransferList.Add(new TransferInfo
                {
                    From  = smartContractState.Message.ContractAddress.ToUint160(this.network),
                    To    = addressTo.ToUint160(this.network),
                    Value = amountToTransfer
                });

                this.logger.LogTrace("(-)[TRANSFER_TO_SENDER]:Transfer {0} from {1} to {2}.", smartContractState.Message.ContractAddress, addressTo, amountToTransfer);
                return(TransferResult.Empty());
            }

            this.logger.LogTrace("(-)[TRANSFER_TO_CONTRACT]");

            return(ExecuteTransferFundsToContract(contractCode, smartContractState, addressTo, amountToTransfer, contractDetails));
        }
Пример #17
0
        public Moloch(
            ISmartContractState state,
            Address summoner,
            Address _approvedToken,
            ulong _periodDuration,
            ulong _votingPeriodLength,
            ulong _gracePeriodLength,
            ulong _abortWindow,
            ulong _proposalDeposit,
            ulong _dilutionBound,
            ulong _processingReward,
            Address approvedTokenAddress,
            IStandardToken approvedStandardToken
            ) : base(state)
        {
            Assert(summoner != Address.Zero, "Moloch::constructor - summoner cannot be 0");
            Assert(_approvedToken != Address.Zero, "Moloch::constructor - _approvedToken cannot be 0");
            Assert(_periodDuration > 0, "Moloch::constructor - _periodDuration cannot be 0");
            Assert(_votingPeriodLength > 0, "Moloch::constructor - _votingPeriodLength cannot be 0");
            Assert(_votingPeriodLength <= MAX_VOTING_PERIOD_LENGTH, "Moloch::constructor - _votingPeriodLength exceeds limit");
            Assert(_gracePeriodLength <= MAX_GRACE_PERIOD_LENGTH, "Moloch::constructor - _gracePeriodLength exceeds limit");
            Assert(_abortWindow > 0, "Moloch::constructor - _abortWindow cannot be 0");
            Assert(_abortWindow <= _votingPeriodLength, "Moloch::constructor - _abortWindow must be smaller than or equal to _votingPeriodLength");
            Assert(_dilutionBound > 0, "Moloch::constructor - _dilutionBound cannot be 0");
            Assert(_dilutionBound <= MAX_DILUTION_BOUND, "Moloch::constructor - _dilutionBound exceeds limit");
            Assert(_proposalDeposit >= _processingReward, "Moloch::constructor - _proposalDeposit cannot be smaller than _processingReward");

            // todo: how to wrap calls from/to?
            ApprovedTokenAddress  = approvedTokenAddress;
            ApprovedStandardToken = approvedStandardToken;

            // todo: how to start a new guildbank contract as well?
            GuildBank = new GuildBank(state, approvedTokenAddress, approvedStandardToken);

            PeriodDuration     = _periodDuration;
            VotingPeriodLength = _votingPeriodLength;
            GracePeriodLength  = _gracePeriodLength;
            AbortWindow        = _abortWindow;
            ProposalDeposit    = _proposalDeposit;
            DilutionBound      = _dilutionBound;
            ProcessingReward   = _processingReward;

            // todo: summoningTime = now; // now operator/call missing in stratis?
            SummoningTime = DateTime.UtcNow.Ticks;

            SetMember(summoner, new Member()
            {
                DelegateKey         = summoner,
                Shares              = 1,
                Exists              = true,
                HighestIndexYesVote = 0
            });

            SetMemberAddressByDelegateKey(summoner, summoner);

            TotalShares = 1;
            SetProposalQueue(new Proposal[0]);

            LogSummonComplete(summoner, 1);
        }
 public HelloBlockchain(ISmartContractState state, string message)
     : base(state)
 {
     Requestor      = Message.Sender;
     RequestMessage = message;
     State          = (uint)StateType.Request;
 }
Пример #19
0
 /// <summary>
 /// Constructor initializing a standard pool contract.
 /// </summary>
 /// <param name="state">Smart contract state.</param>
 /// <param name="token">The address of the SRC token in the pool.</param>
 /// <param name="authProviders">Flag to authorize liquidity providers or not.</param>
 /// <param name="authTraders">Flag to authorize traders or not.</param>
 /// <param name="fee">The market transaction fee, 0-10 equal to 0-1%.</param>
 public OpdexStandardPool(ISmartContractState state, Address token, bool authProviders, bool authTraders, uint fee)
     : base(state, token, fee)
 {
     Market        = Message.Sender;
     AuthProviders = authProviders;
     AuthTraders   = authTraders;
 }
        private StateTransitionResult ApplyCreate(IState state, object[] parameters, byte[] code, BaseMessage message,
                                                  uint160 address,
                                                  string type = null)
        {
            var gasMeter = new GasMeter(message.GasLimit);

            gasMeter.Spend((Gas)GasPriceList.BaseCost);

            state.ContractState.CreateAccount(address);

            ISmartContractState smartContractState = state.CreateSmartContractState(state, gasMeter, address, message, state.ContractState);

            VmExecutionResult result = this.Vm.Create(state.ContractState, smartContractState, code, parameters, type);

            bool revert = !result.IsSuccess;

            if (revert)
            {
                return(StateTransitionResult.Fail(
                           gasMeter.GasConsumed,
                           result.Error));
            }

            return(StateTransitionResult.Ok(
                       gasMeter.GasConsumed,
                       address,
                       result.Success.Result
                       ));
        }
Пример #21
0
 public TestContract(ISmartContractState smartContractState, int param)
     : base(smartContractState)
 {
     this.ConstructorCalledCount++;
     this.State = smartContractState;
     this.Param = param;
 }
Пример #22
0
    public ForwardParameters(ISmartContractState state,
                             char aChar,
                             Address anAddress,
                             bool aBool,
                             int anInt,
                             long aLong,
                             uint aUint,
                             ulong aUlong,
                             string aString,
                             Address sendTo) : base(state)
    {
        ITransferResult result = this.Call(sendTo, this.Balance, "Call", new object[]
        {
            aChar,
            anAddress,
            aBool,
            anInt,
            aLong,
            aUint,
            aUlong,
            aString
        });

        Assert(result.Success);
    }
        ///<inheritdoc />
        public ITransferResult Call(
            ISmartContractState smartContractState,
            Address addressTo,
            ulong amountToTransfer,
            string methodName,
            object[] parameters,
            ulong gasLimit = 0)
        {
            // For a method call, send all the gas unless an amount was selected.Should only call trusted methods so re - entrance is less problematic.
            ulong gasBudget = (gasLimit != 0) ? gasLimit : smartContractState.GasMeter.GasAvailable;

            var message = new InternalCallMessage(
                addressTo.ToUint160(this.network),
                smartContractState.Message.ContractAddress.ToUint160(this.network),
                amountToTransfer,
                (Gas)gasBudget,
                new MethodCall(methodName, parameters)
                );

            var result = this.state.Apply(message);

            return(result.IsSuccess
                ? TransferResult.Transferred(result.Success.ExecutionResult)
                : TransferResult.Failed());
        }
 public Auction(ISmartContractState smartContractState, ulong durationBlocks)
     : base(smartContractState)
 {
     Owner    = Message.Sender;
     EndBlock = Block.Number + durationBlocks;
     HasEnded = false;
 }
Пример #25
0
 // Constructor takes two parameters - the 2 owners of the multisig. They must agree to make any outgoing transactions.
 public MultiSig2of2(ISmartContractState smartContractState, Address owner1, Address owner2)
     : base(smartContractState)
 {
     Owner1 = owner1;
     Owner2 = owner2;
     LogMessage("Constructor called. Owners: " + owner1 + ", " + owner2);
 }
        ///<inheritdoc />
        public ICreateResult Create <T>(ISmartContractState smartContractState,
                                        ulong amountToTransfer,
                                        object[] parameters,
                                        ulong gasLimit = 0)
        {
            // TODO: Expend any neccessary costs.

            ulong gasBudget = (gasLimit != 0) ? gasLimit : DefaultGasLimit;

            // Ensure we have enough gas left to be able to fund the new GasMeter.
            if (smartContractState.GasMeter.GasAvailable < gasBudget)
            {
                throw new InsufficientGasException();
            }

            var nestedGasMeter = new GasMeter((Gas)gasBudget);

            // Check balance.
            EnsureContractHasEnoughBalance(smartContractState, amountToTransfer);

            // Build objects for VM
            byte[] contractCode = this.contractStateRepository.GetCode(smartContractState.Message.ContractAddress.ToUint160(this.network)); // TODO: Fix this when calling from constructor.

            var context = new TransactionContext(
                this.transactionContext.TransactionHash,
                this.transactionContext.BlockHeight,
                this.transactionContext.Coinbase,
                smartContractState.Message.ContractAddress.ToUint160(this.network),
                amountToTransfer,
                this.transactionContext.GetNonceAndIncrement());

            IContractStateRepository track = this.contractStateRepository.StartTracking();

            var createData = new CreateData(nestedGasMeter.GasLimit, contractCode, parameters);

            // Do create in vm
            VmExecutionResult result = this.vm.Create(nestedGasMeter, track, createData, context, typeof(T).Name);

            // Update parent gas meter.
            smartContractState.GasMeter.Spend(nestedGasMeter.GasConsumed);

            var revert = result.ExecutionException != null;

            if (revert)
            {
                this.logger.LogTrace("(-)[CONTRACT_EXECUTION_FAILED]");
                track.Rollback();
                return(CreateResult.Failed());
            }

            this.logger.LogTrace("(-)[CONTRACT_EXECUTION_SUCCEEDED]");
            track.Commit();

            // TODO: Add internaltransfer update here

            this.contractLogHolder.AddRawLogs(result.RawLogs);

            return(CreateResult.Succeeded(result.NewContractAddress.ToAddress(this.network)));
        }
Пример #27
0
 /// <summary>
 /// Constructor initializing the router contract.
 /// </summary>
 /// <param name="state">Smart contract state.</param>
 /// <param name="market">The address of the market associated.</param>
 /// <param name="transactionFee">0-10 transaction fee equal to 0-1%.</param>
 /// <param name="authProviders">Flag indicating if liquidity providers should be authorized.</param>
 /// <param name="authTraders">Flag indicating if traders should be authorized.</param>
 public OpdexRouter(ISmartContractState state, Address market, uint transactionFee, bool authProviders, bool authTraders) : base(state)
 {
     Assert(transactionFee <= 10, "OPDEX: INVALID_TRANSACTION_FEE");
     Market         = market;
     TransactionFee = transactionFee;
     AuthProviders  = authProviders;
     AuthTraders    = authTraders;
 }
Пример #28
0
 /// <summary>
 /// Constructor used to create a new instance of the token. Assigns the total token supply to the creator of the contract.
 /// </summary>
 /// <param name="smartContractState">The execution state for the contract.</param>
 /// <param name="totalSupply">The total token supply.</param>
 /// <param name="name">The name of the token.</param>
 /// <param name="symbol">The symbol used to identify the token.</param>
 public StandardToken(ISmartContractState smartContractState, ulong totalSupply, string name, string symbol)
     : base(smartContractState)
 {
     this.TotalSupply = totalSupply;
     this.Name        = name;
     this.Symbol      = symbol;
     this.SetBalance(Message.Sender, totalSupply);
 }
Пример #29
0
    private const ulong ProposalDeposit = 50000000000ul; // 500 CRS

    /// <summary>
    /// Constructor initializing an empty vault smart contract.
    /// </summary>
    /// <param name="state">Smart contract state.</param>
    /// <param name="token">The locked SRC token.</param>
    /// <param name="vestingDuration">The length in blocks of the vesting period.</param>
    /// <param name="totalPledgeMinimum">The minimum total number of tokens pledged to a proposal to move to a vote.</param>
    /// <param name="totalVoteMinimum">The minimum total number of tokens voted on a proposal to have a chance to be approved.</param>
    public OpdexVault(ISmartContractState state, Address token, ulong vestingDuration, ulong totalPledgeMinimum, ulong totalVoteMinimum) : base(state)
    {
        Token              = token;
        VestingDuration    = vestingDuration;
        TotalPledgeMinimum = totalPledgeMinimum;
        TotalVoteMinimum   = totalVoteMinimum;
        NextProposalId     = 1;
    }
Пример #30
0
 public TimeLock(ISmartContractState smartContractState, ulong duration, Address owner)
     : base(smartContractState)
 {
     EndBlock = Block.Number + duration;
     LogMessage("End Block: " + EndBlock);
     Owner = owner;
     LogMessage("Owner: " + Owner);
 }