Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamically adjust fees #1453

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/neo/SmartContract/ApplicationEngine.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Neo.Ledger;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.SmartContract.Native;
using Neo.VM;
using Neo.VM.Types;
using System;
Expand Down Expand Up @@ -78,7 +79,7 @@ public override void Dispose()

protected override bool OnSysCall(uint method)
{
if (!AddGas(InteropService.GetPrice(method, CurrentContext.EvaluationStack)))
if (!AddGas(NativeContract.Fee.GetSyscallPrice(method, Snapshot, CurrentContext.EvaluationStack)))
return false;
return InteropService.Invoke(this, method);
}
Expand All @@ -87,7 +88,7 @@ protected override bool PreExecuteInstruction()
{
if (CurrentContext.InstructionPointer >= CurrentContext.Script.Length)
return true;
return AddGas(OpCodePrices[CurrentContext.CurrentInstruction.OpCode]);
return AddGas(NativeContract.Fee.GetOpCodePrice(CurrentContext.CurrentInstruction.OpCode, Snapshot));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should use GetRatio only, otherwise we will lose a big performance, other way is caching the prices, and refresh this cache when it's needed.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're concerned that some instructions' cost may be too high, which may need to be adjusted in the future.

}

private static Block CreateDummyBlock(StoreView snapshot)
Expand Down
132 changes: 132 additions & 0 deletions src/neo/SmartContract/Native/FeeContract.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
#pragma warning disable IDE0051
#pragma warning disable IDE0060

using Neo.Ledger;
using Neo.Persistence;
using Neo.SmartContract.Manifest;
using Neo.VM;
using Neo.VM.Types;
using System;
using System.Collections.Generic;
using System.Numerics;
using Array = Neo.VM.Types.Array;

namespace Neo.SmartContract.Native
{
public sealed class FeeContract : NativeContract
{
public override string ServiceName => "Neo.Native.Fee";
public override int Id => -4;

private const byte Prefix_Ratio = 11;
private const byte Prefix_Syscall = 12;
private const byte Prefix_OpCode = 13;

private const uint DefaultRatio = 1;

public FeeContract()
{
Manifest.Features = ContractFeatures.HasStorage;
}

internal override bool Initialize(ApplicationEngine engine)
{
if (!base.Initialize(engine)) return false;
engine.Snapshot.Storages.Add(CreateStorageKey(Prefix_Ratio), new StorageItem
{
Value = BitConverter.GetBytes(DefaultRatio)
});
return true;
}

private bool CheckValidators(ApplicationEngine engine)
{
UInt256 prev_hash = engine.Snapshot.PersistingBlock.PrevHash;
TrimmedBlock prev_block = engine.Snapshot.Blocks[prev_hash];
return InteropService.Runtime.CheckWitnessInternal(engine, prev_block.NextConsensus);
}

[ContractMethod(0_00010000, ContractParameterType.Integer, ParameterTypes = new[] { ContractParameterType.Integer }, ParameterNames = new[] { "value" })]
private StackItem GetSyscallPrice(ApplicationEngine engine, Array args)
{
uint method = (uint)args[0].GetBigInteger();
return GetSyscallPrice(method, engine.Snapshot);
}

public long GetSyscallPrice(uint method, StoreView snapshot, EvaluationStack stack = null)
{
if (snapshot.Storages.TryGet(CreateStorageKey(Prefix_Syscall, BitConverter.GetBytes(method))) != null)
{
return BitConverter.ToInt64(snapshot.Storages[CreateStorageKey(Prefix_Syscall, BitConverter.GetBytes(method))].Value, 0) / GetRatio(snapshot);
}
return InteropService.GetPrice(method, stack) / GetRatio(snapshot);
}

[ContractMethod(0_00030000, ContractParameterType.Boolean, ParameterTypes = new[] { ContractParameterType.Array }, ParameterNames = new[] { "value" })]
private StackItem SetSyscallPrice(ApplicationEngine engine, Array args)
{
if (!CheckValidators(engine)) return false;
uint method = (uint)((Array)args[0])[0].GetBigInteger();
long value = (long)((Array)args[0])[1].GetBigInteger();
if (value < 0) return false;
StorageKey key = CreateStorageKey(Prefix_Syscall, BitConverter.GetBytes(method));
StorageItem item = engine.Snapshot.Storages.GetAndChange(key, () => new StorageItem());
item.Value = BitConverter.GetBytes(value);
return true;
}

[ContractMethod(0_00010000, ContractParameterType.Integer, ParameterTypes = new[] { ContractParameterType.Integer }, ParameterNames = new[] { "value" })]
private StackItem GetOpCodePrice(ApplicationEngine engine, Array args)
{
uint opCode = (uint)args[0].GetBigInteger();
return GetOpCodePrice((OpCode)opCode, engine.Snapshot);
}

public long GetOpCodePrice(OpCode opCode, StoreView snapshot)
{
if (snapshot.Storages.TryGet(CreateStorageKey(Prefix_OpCode, BitConverter.GetBytes((int)opCode))) != null)
{
return BitConverter.ToInt64(snapshot.Storages[CreateStorageKey(Prefix_OpCode, BitConverter.GetBytes((int)opCode))].Value, 0) / GetRatio(snapshot);
}
return ApplicationEngine.OpCodePrices[opCode] / GetRatio(snapshot);
}

[ContractMethod(0_00030000, ContractParameterType.Boolean, ParameterTypes = new[] { ContractParameterType.Array }, ParameterNames = new[] { "value" })]
private StackItem SetOpCodePrice(ApplicationEngine engine, Array args)
{
if (!CheckValidators(engine)) return false;
uint opCode = (uint)((Array)args[0])[0].GetBigInteger();
long value = (long)((Array)args[0])[1].GetBigInteger();
if (value < 0) return false;
StorageKey key = CreateStorageKey(Prefix_OpCode, BitConverter.GetBytes(opCode));
StorageItem item = engine.Snapshot.Storages.GetAndChange(key, () => new StorageItem());
item.Value = BitConverter.GetBytes(value);
return true;
}

[ContractMethod(0_00010000, ContractParameterType.Integer, SafeMethod = true)]
private StackItem GetRatio(ApplicationEngine engine, Array args)
{
return GetRatio(engine.Snapshot);
}

public uint GetRatio(StoreView snapshot)
{
if (snapshot.Storages.TryGet(CreateStorageKey(Prefix_Ratio)) != null)
return BitConverter.ToUInt32(snapshot.Storages[CreateStorageKey(Prefix_Ratio)].Value, 0);
else
return DefaultRatio;
}

[ContractMethod(0_00030000, ContractParameterType.Boolean, ParameterTypes = new[] { ContractParameterType.Integer }, ParameterNames = new[] { "value" })]
private StackItem SetRatio(ApplicationEngine engine, Array args)
{
if (!CheckValidators(engine)) return false;
uint value = (uint)args[0].GetBigInteger();
if (value == 0) return false;
StorageItem storage = engine.Snapshot.Storages.GetAndChange(CreateStorageKey(Prefix_Ratio));
storage.Value = BitConverter.GetBytes(value);
return true;
}
}
}
1 change: 1 addition & 0 deletions src/neo/SmartContract/Native/NativeContract.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public abstract class NativeContract
public static NeoToken NEO { get; } = new NeoToken();
public static GasToken GAS { get; } = new GasToken();
public static PolicyContract Policy { get; } = new PolicyContract();
public static FeeContract Fee { get; } = new FeeContract();

public abstract string ServiceName { get; }
public uint ServiceHash { get; }
Expand Down
16 changes: 8 additions & 8 deletions src/neo/Wallets/Wallet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -339,34 +339,34 @@ private Transaction MakeTransaction(StoreView snapshot, byte[] script, Transacti
{
byte[] witness_script = GetAccount(hash)?.Contract?.Script ?? snapshot.Contracts.TryGet(hash)?.Script;
if (witness_script is null) continue;
tx.NetworkFee += CalculateNetworkFee(witness_script, ref size);
tx.NetworkFee += CalculateNetworkFee(witness_script, ref size, snapshot);
}
tx.NetworkFee += size * NativeContract.Policy.GetFeePerByte(snapshot);
if (value >= tx.SystemFee + tx.NetworkFee) return tx;
}
throw new InvalidOperationException("Insufficient GAS");
}

public static long CalculateNetworkFee(byte[] witness_script, ref int size)
public static long CalculateNetworkFee(byte[] witness_script, ref int size, StoreView snapshot)
{
long networkFee = 0;

if (witness_script.IsSignatureContract())
{
size += 67 + witness_script.GetVarSize();
networkFee += ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHNULL] + InteropService.GetPrice(InteropService.Crypto.ECDsaVerify, null);
networkFee += NativeContract.Fee.GetOpCodePrice(OpCode.PUSHDATA1, snapshot) + NativeContract.Fee.GetOpCodePrice(OpCode.PUSHDATA1, snapshot) + NativeContract.Fee.GetOpCodePrice(OpCode.PUSHNULL, snapshot) + NativeContract.Fee.GetSyscallPrice(InteropService.Crypto.ECDsaVerify, snapshot);
}
else if (witness_script.IsMultiSigContract(out int m, out int n))
{
int size_inv = 66 * m;
size += IO.Helper.GetVarSize(size_inv) + size_inv + witness_script.GetVarSize();
networkFee += ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] * m;
networkFee += NativeContract.Fee.GetOpCodePrice(OpCode.PUSHDATA1, snapshot) * m;
using (ScriptBuilder sb = new ScriptBuilder())
networkFee += ApplicationEngine.OpCodePrices[(OpCode)sb.EmitPush(m).ToArray()[0]];
networkFee += ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] * n;
networkFee += NativeContract.Fee.GetOpCodePrice((OpCode)sb.EmitPush(m).ToArray()[0], snapshot);
networkFee += NativeContract.Fee.GetOpCodePrice(OpCode.PUSHDATA1, snapshot) * n;
using (ScriptBuilder sb = new ScriptBuilder())
networkFee += ApplicationEngine.OpCodePrices[(OpCode)sb.EmitPush(n).ToArray()[0]];
networkFee += ApplicationEngine.OpCodePrices[OpCode.PUSHNULL] + InteropService.GetPrice(InteropService.Crypto.ECDsaVerify, null) * n;
networkFee += NativeContract.Fee.GetOpCodePrice((OpCode)sb.EmitPush(n).ToArray()[0], snapshot);
networkFee += NativeContract.Fee.GetOpCodePrice(OpCode.PUSHNULL, snapshot) + NativeContract.Fee.GetSyscallPrice(InteropService.Crypto.ECDsaVerify, snapshot) * n;
}
else
{
Expand Down
16 changes: 8 additions & 8 deletions tests/neo.UnitTests/Extensions/Nep5NativeContractExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ public static bool Transfer(this NativeContract contract, StoreView snapshot, by
return result.ToBoolean();
}

public static string[] SupportedStandards(this NativeContract contract)
public static string[] SupportedStandards(this NativeContract contract, StoreView snapshot)
{
var engine = new ApplicationEngine(TriggerType.Application, null, null, 0, testMode: true);
var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, testMode: true);

engine.LoadScript(contract.Script);

Expand Down Expand Up @@ -131,9 +131,9 @@ public static BigInteger BalanceOf(this NativeContract contract, StoreView snaps
return (result as VM.Types.Integer).GetBigInteger();
}

public static BigInteger Decimals(this NativeContract contract)
public static BigInteger Decimals(this NativeContract contract, StoreView snapshot)
{
var engine = new ApplicationEngine(TriggerType.Application, null, null, 0, testMode: true);
var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, testMode: true);

engine.LoadScript(contract.Script);

Expand All @@ -151,9 +151,9 @@ public static BigInteger Decimals(this NativeContract contract)
return (result as VM.Types.Integer).GetBigInteger();
}

public static string Symbol(this NativeContract contract)
public static string Symbol(this NativeContract contract, StoreView snapshot)
{
var engine = new ApplicationEngine(TriggerType.Application, null, null, 0, testMode: true);
var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, testMode: true);

engine.LoadScript(contract.Script);

Expand All @@ -171,9 +171,9 @@ public static string Symbol(this NativeContract contract)
return result.GetString();
}

public static string Name(this NativeContract contract)
public static string Name(this NativeContract contract, StoreView snapshot)
{
var engine = new ApplicationEngine(TriggerType.Application, null, null, 0, testMode: true);
var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, testMode: true);

engine.LoadScript(contract.Script);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,16 @@ public void TestSetup()
}

[TestMethod]
public void Check_Name() => NativeContract.GAS.Name().Should().Be("GAS");
public void Check_Name() => NativeContract.GAS.Name(Blockchain.Singleton.GetSnapshot()).Should().Be("GAS");

[TestMethod]
public void Check_Symbol() => NativeContract.GAS.Symbol().Should().Be("gas");
public void Check_Symbol() => NativeContract.GAS.Symbol(Blockchain.Singleton.GetSnapshot()).Should().Be("gas");

[TestMethod]
public void Check_Decimals() => NativeContract.GAS.Decimals().Should().Be(8);
public void Check_Decimals() => NativeContract.GAS.Decimals(Blockchain.Singleton.GetSnapshot()).Should().Be(8);

[TestMethod]
public void Check_SupportedStandards() => NativeContract.GAS.SupportedStandards().Should().BeEquivalentTo(new string[] { "NEP-5", "NEP-10" });
public void Check_SupportedStandards() => NativeContract.GAS.SupportedStandards(Blockchain.Singleton.GetSnapshot()).Should().BeEquivalentTo(new string[] { "NEP-5", "NEP-10" });

[TestMethod]
public void Check_BalanceOfTransferAndBurn()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,16 @@ public void TestSetup()
}

[TestMethod]
public void Check_Name() => NativeContract.NEO.Name().Should().Be("NEO");
public void Check_Name() => NativeContract.NEO.Name(Blockchain.Singleton.GetSnapshot()).Should().Be("NEO");

[TestMethod]
public void Check_Symbol() => NativeContract.NEO.Symbol().Should().Be("neo");
public void Check_Symbol() => NativeContract.NEO.Symbol(Blockchain.Singleton.GetSnapshot()).Should().Be("neo");

[TestMethod]
public void Check_Decimals() => NativeContract.NEO.Decimals().Should().Be(0);
public void Check_Decimals() => NativeContract.NEO.Decimals(Blockchain.Singleton.GetSnapshot()).Should().Be(0);

[TestMethod]
public void Check_SupportedStandards() => NativeContract.NEO.SupportedStandards().Should().BeEquivalentTo(new string[] { "NEP-5", "NEP-10" });
public void Check_SupportedStandards() => NativeContract.NEO.SupportedStandards(Blockchain.Singleton.GetSnapshot()).Should().BeEquivalentTo(new string[] { "NEP-5", "NEP-10" });

[TestMethod]
public void Check_Vote()
Expand Down
Loading