Skip to content

Commit

Permalink
Removed staking contract
Browse files Browse the repository at this point in the history
  • Loading branch information
vsuharnikov committed Sep 16, 2024
1 parent 6d10b34 commit 8f9d93e
Show file tree
Hide file tree
Showing 10 changed files with 36 additions and 232 deletions.
1 change: 0 additions & 1 deletion local-network/deploy/src/common-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,5 @@ function mkWavesAccount(seed: string, nonce: number): WavesAccount {

export const elBridgeContractAddress = '0x1000000000000000000000000000000000000000';
export const chainContract = mkWavesAccount('devnet-1', 2);
export const stakingContract = mkWavesAccount('devnet-1', 1);
export const wavesMiner1 = mkWavesAccount('devnet-1', 0);
export const wavesMiner2 = mkWavesAccount('devnet-2', 0);
26 changes: 0 additions & 26 deletions local-network/deploy/src/waves-txs.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,6 @@
import * as wt from '@waves/waves-transactions';
import * as s from './common-settings';

// 1. Set staking contract balances, sc - staking contract
export const scSetBalances = wt.data(
{
chainId: s.chainId,
fee: 2_400_000,
data: [
{
key: `%s__${s.wavesMiner1.address}`,
type: "string",
value: "%d%d%d%d__1__50000000__8__10000001"
},
{
key: `%s__${s.wavesMiner2.address}`,
type: "string",
value: "%d%d%d%d__1__50000000__9__1000000"
}
]
},
{ privateKey: s.stakingContract.privateKey }
)

// cc - Chain contract
// 2. Deploy chain contract script
export function mkCcDeploy(script: string) {
Expand Down Expand Up @@ -57,11 +36,6 @@ export function ccSetup(elGenesisBlockHashHex: string) {
// see bridge.sol for conversion details
value: 2_000_000_000
},
{
// stakingContractAddressB58
type: "string",
value: s.stakingContract.address
},
{
// elBridgeAddressHex
type: "string",
Expand Down
31 changes: 6 additions & 25 deletions local-network/deploy/src/waves.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,27 +25,11 @@ export interface SetupResult {
export async function setup(force: boolean): Promise<SetupResult> {
logger.info('Set up CL');

const scSetBalances = async (): Promise<boolean> => {
const tx = wavesTxs.scSetBalances;
const dAppAddress = wt.libs.crypto.address({ publicKey: tx.senderPublicKey }, s.chainId);

let dataKeyResponse: DataTransactionEntry<TLong>;
try { dataKeyResponse = await wavesApi1.addresses.fetchDataKey(dAppAddress, tx.data[0].key); } catch { }

// @ts-ignore: Property 'value' does not exist on type 'object'.
if (dataKeyResponse && dataKeyResponse.value) {
logger.info('Staking contract data is already set up');
return false;
} else {
await wavesApi1.transactions.broadcast(tx);
return true;
}
};

const deployChainContract = async (): Promise<void> => {
const deployChainContract = async (): Promise<boolean> => {
const scriptInfo = await wavesApi1.addresses.fetchScriptInfo(s.chainContract.address);
if (scriptInfo.script) {
logger.info(`${s.chainContract.address} already has a script, cancel deploying.`);
logger.info(`${s.chainContract.address} already has a script.`);
return false;
} else {
logger.info('Compile CL chain contract');
const chainContractCode = await fs.readFile('./setup/waves/main.ride', 'utf-8');
Expand All @@ -56,6 +40,7 @@ export async function setup(force: boolean): Promise<SetupResult> {
const tx = wavesTxs.mkCcDeploy(compiledChainContract.script);
await wavesApi1.transactions.broadcast(tx)
await wavesUtils.waitForTxn(wavesApi1, tx.id);
return true;
}
};

Expand Down Expand Up @@ -98,16 +83,12 @@ export async function setup(force: boolean): Promise<SetupResult> {

logger.info(`Waves nodes peers: ${connectedPeers}`);

logger.info('Set staking contract balances');
const isNew = await scSetBalances();
logger.info('Deploy chain contract');
const isNew = await deployChainContract();
const waitTime = 3000;// To eliminate micro fork issue
if (isNew) await common.sleep(waitTime);

if (isNew || force) {
logger.info('Deploy chain contract');
await deployChainContract();
if (isNew) await common.sleep(waitTime);

logger.info('Setup chain contract');
await setupChainContract();
if (isNew) await common.sleep(waitTime);
Expand Down
25 changes: 9 additions & 16 deletions src/main/scala/units/client/contract/ChainContractClient.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import com.wavesplatform.serialization.ByteBufferOps
import com.wavesplatform.state.{BinaryDataEntry, Blockchain, DataEntry, EmptyDataEntry, IntegerDataEntry, StringDataEntry}
import units.BlockHash
import units.client.contract.ChainContractClient.*
import units.client.staking.StakingContractClient
import units.eth.{EthAddress, Gwei}
import units.util.HexBytesConverter
import units.util.HexBytesConverter.*
Expand Down Expand Up @@ -166,29 +165,23 @@ trait ChainContractClient {
hitSource: Array[Byte],
baseTarget: Long,
miner: Address,
stakingContractAddress: Address,
blockchain: Blockchain
): Option[(Address, Long)] = {
val hit = Global.blake2b256(hitSource ++ miner.bytes).take(PoSCalculator.HitSize)
val l2mpBalance = new StakingContractClient(blockchain.accountData(stakingContractAddress, _))
.getL2mpBalance(miner, blockchain.height)

if (blockchain.generatingBalance(miner) >= MinMinerBalance && l2mpBalance > 0) {
val hit = Global.blake2b256(hitSource ++ miner.bytes).take(PoSCalculator.HitSize)
val generatingBalance = blockchain.generatingBalance(miner)
if (generatingBalance >= MinMinerBalance) {
// See WavesEnvironment.calculateDelay
val delay = FairPoSCalculator(0, 0).calculateDelay(BigInt(1, hit), baseTarget, l2mpBalance)
val delay = FairPoSCalculator(0, 0).calculateDelay(BigInt(1, hit), baseTarget, generatingBalance)
Some(miner -> delay)
} else None
}

def calculateEpochMiner(header: BlockHeader, hitSource: ByteStr, epochNumber: Int, blockchain: Blockchain): Either[String, Address] =
for {
stakingContractAddress <- getStakingContractAddress.toRight("Staking contract address is not defined")
bestMiner <- getAllActualMiners
.flatMap(miner => calculateMinerDelay(hitSource.arr, header.baseTarget, miner, stakingContractAddress, blockchain))
.minByOption(_._2)
.map(_._1)
.toRight(s"No miner for epoch $epochNumber")
} yield bestMiner
getAllActualMiners
.flatMap(miner => calculateMinerDelay(hitSource.arr, header.baseTarget, miner, blockchain))
.minByOption(_._2)
.map(_._1)
.toRight(s"No miner for epoch $epochNumber")

private def getBlockHash(key: String): Option[BlockHash] =
extractData(key).collect {
Expand Down
8 changes: 4 additions & 4 deletions src/main/scala/units/client/contract/ContractFunction.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ abstract class ContractFunction(name: String, reference: BlockHash, extraArgs: E

object ContractFunction {
case class ExtendMainChain(reference: BlockHash, vrf: ByteStr)
extends ContractFunction("extendMainChain_v4", reference, CONST_BYTESTR(vrf).map(v => List(v)))
extends ContractFunction("extendMainChain", reference, CONST_BYTESTR(vrf).map(v => List(v)))

case class AppendBlock(reference: BlockHash) extends ContractFunction("appendBlock_v3", reference, Right(Nil))
case class AppendBlock(reference: BlockHash) extends ContractFunction("appendBlock", reference, Right(Nil))

case class ExtendAltChain(reference: BlockHash, vrf: ByteStr, chainId: Long)
extends ContractFunction("extendAltChain_v4", reference, CONST_BYTESTR(vrf).map(v => List(v, CONST_LONG(chainId))))
extends ContractFunction("extendAltChain", reference, CONST_BYTESTR(vrf).map(v => List(v, CONST_LONG(chainId))))

case class StartAltChain(reference: BlockHash, vrf: ByteStr)
extends ContractFunction("startAltChain_v4", reference, CONST_BYTESTR(vrf).map(v => List(v)))
extends ContractFunction("startAltChain", reference, CONST_BYTESTR(vrf).map(v => List(v)))
}
29 changes: 0 additions & 29 deletions src/main/scala/units/client/staking/StakingContractClient.scala

This file was deleted.

103 changes: 9 additions & 94 deletions src/test/resources/main.ride
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ let mainChainIdKey = "mainChainId"
let lastChainIdKey = "lastChainId"
let firstValidAltChainIdKey = "firstValidAltChainId"
let minerRewardKey = "minerReward" # In Gwei. Changing the value is unexpected and isn't held by code
let stakingContractAddressKey = "stakingContractAddress"
let blockMetaK = "block_0x"
let finalizedBlockKey = "finalizedBlock"
let tokenIdKey = "tokenId"
Expand Down Expand Up @@ -84,24 +83,8 @@ func amountGtEq(t: AttachedPayment, gtEq: Int, queueSize: Int) = {
)
}

let stakingContractAddress = match this.getString(stakingContractAddressKey) {
case s: String => addressFromString(s).valueOrErrorMessage("invalid staking contract address: " + s)
case _ => Address(this.getBinaryValue(stakingContractAddressKey))
}

func generatingBalance(address: Address) = {
match stakingContractAddress.getString("%s__" + address.toString()) {
case str: String =>
let paramList = str.split("__")
let prevHeight = paramList[1].parseIntValue()
let prevBalance = paramList[2].parseIntValue()
let nextHeight = paramList[3].parseIntValue()
let nextBalance = paramList[4].parseIntValue()
if (height >= nextHeight) then nextBalance
else if (height >= prevHeight) then prevBalance
else 0
case _ => 0
}
address.wavesBalance().generating
}

func chainMeta(chainId: Int) = {
Expand Down Expand Up @@ -354,8 +337,8 @@ func getUpdateFinalizedBlockAction(caller: Address, newBlockHashHex: String, pre
else []
}

func extendMainChainImpl(
i: Invocation,
@Callable(i)
func extendMainChain(
blockHashHex: String,
referenceHex: String,
vrf: ByteVector,
Expand Down Expand Up @@ -387,8 +370,8 @@ func extendMainChainImpl(
] ++ updateFinalizedBlock
}

func startAltChainImpl(
i: Invocation,
@Callable(i)
func startAltChain(
blockHashHex: String,
referenceHex: String,
vrf: ByteVector,
Expand Down Expand Up @@ -428,8 +411,8 @@ func startAltChainImpl(
]
}

func extendAltChainImpl(
i: Invocation,
@Callable(i)
func extendAltChain(
chainId: Int,
blockHashHex: String,
referenceHex: String,
Expand Down Expand Up @@ -485,72 +468,8 @@ func extendAltChainImpl(
] ++ updateMainChainData ++ addSupporter(chainId, i.originCaller) ++ updateMainChainLastMinedBlock
}

func allowOmittingVrf(epoch: Int) =
match getInteger("requireVrfArgumentFromHeight") {
case _: Unit => vrfAt(epoch)
case h: Int =>
if (h < epoch) then vrfAt(epoch) else throw("VRF argument is mandatory. Upgrade your client!")
}

@Callable(i)
func extendMainChain_v3(
blockHashHex: String,
referenceHex: String,
epoch: Int,
elToClTransfersRootHashHex: String,
lastClToElTransferIndex: Int
) = extendMainChainImpl(i, blockHashHex, referenceHex, allowOmittingVrf(epoch), elToClTransfersRootHashHex, lastClToElTransferIndex)


@Callable(i)
func extendMainChain_v4(
blockHashHex: String,
referenceHex: String,
vrf: ByteVector,
elToClTransfersRootHashHex: String,
lastClToElTransferIndex: Int
) = extendMainChainImpl(i, blockHashHex, referenceHex, vrf, elToClTransfersRootHashHex, lastClToElTransferIndex)

@Callable(i)
func startAltChain_v3(
blockHashHex: String,
referenceHex: String,
epoch: Int,
elToClTransfersRootHashHex: String,
lastClToElTransferIndex: Int
) = startAltChainImpl(i, blockHashHex, referenceHex, allowOmittingVrf(epoch), elToClTransfersRootHashHex, lastClToElTransferIndex)

@Callable(i)
func startAltChain_v4(
blockHashHex: String,
referenceHex: String,
vrf: ByteVector,
elToClTransfersRootHashHex: String,
lastClToElTransferIndex: Int
) = startAltChainImpl(i, blockHashHex, referenceHex, vrf, elToClTransfersRootHashHex, lastClToElTransferIndex)

@Callable(i)
func extendAltChain_v3(
chainId: Int,
blockHashHex: String,
referenceHex: String,
epoch: Int,
elToClTransfersRootHashHex: String,
lastClToElTransferIndex: Int
) = extendAltChainImpl(i, chainId, blockHashHex, referenceHex, allowOmittingVrf(epoch), elToClTransfersRootHashHex, lastClToElTransferIndex)

@Callable(i)
func extendAltChain_v4(
blockHashHex: String,
referenceHex: String,
vrf: ByteVector,
chainId: Int,
elToClTransfersRootHashHex: String,
lastClToElTransferIndex: Int
) = extendAltChainImpl(i, chainId, blockHashHex, referenceHex, vrf, elToClTransfersRootHashHex, lastClToElTransferIndex)

@Callable(i)
func appendBlock_v3(
func appendBlock(
blockHashHex: String,
referenceHex: String,
elToClTransfersRootHashHex: String,
Expand Down Expand Up @@ -739,16 +658,13 @@ func withdraw(blockHashHex: String, merkleProof: List[ByteVector], transferIndex
# genesisBlockHashHex without 0x
# elBridgeAddressHex without 0x
@Callable(i)
func setup(genesisBlockHashHex: String, minerRewardInGwei: Int, stakingContractAddressB58: String, elBridgeAddressHex: String) = {
func setup(genesisBlockHashHex: String, minerRewardInGwei: Int, elBridgeAddressHex: String) = {
if (isContractSetup()) then throw("The contract has been already set up")
else if (minerRewardInGwei < 0) then throw("The miner reward must be nonnegative")
else {
let genesisBlockHash = genesisBlockHashHex.fromBase16String()
strict checkGenesisBlockHashSize = if (genesisBlockHash.size() == BLOCK_HASH_SIZE) then true else throw("Wrong genesis block hash")

let stakingContractAddressBytes = fromBase58String(stakingContractAddressB58)
strict checkStakingContractAddress = if (stakingContractAddressBytes.size() == ADDRESS_SIZE) then true else throw("Wrong staking contract address")

strict checkElBridgeAddress = if (elBridgeAddressHex.size() == ETH_ADDRESS_STR_SIZE)
then fromBase16String(elBridgeAddressHex)
else throw("Wrong bridge address")
Expand Down Expand Up @@ -776,7 +692,6 @@ func setup(genesisBlockHashHex: String, minerRewardInGwei: Int, stakingContractA
StringEntry(chainFirstBlockIdKey(0), genesisBlockHashHex),
mkChainMetaEntry(0, 0, genesisBlockHashHex),
IntegerEntry(minerRewardKey, minerRewardInGwei),
StringEntry(stakingContractAddressKey, stakingContractAddressB58),
StringEntry(epochMetaKey(height), genesisMinerAddress.toString() + ",0," + genesisBlockHashHex),
StringEntry(finalizedBlockKey, genesisBlockHashHex),
issue,
Expand Down
9 changes: 1 addition & 8 deletions src/test/scala/units/BaseIntegrationTestSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,7 @@ trait BaseIntegrationTestSuite
d.chainContract.setScript(),
d.chainContract.setup(d.ecGenesisBlock, elMinerDefaultReward.amount.longValue())
) ++
settings.initialMiners
.flatMap { x =>
List(
d.stakingContract.stakingBalance(x.address, 0, x.stakingBalance, 1, x.stakingBalance),
d.chainContract.join(x.account, x.elRewardAddress)
)
}
settings.initialMiners.map { x => d.chainContract.join(x.account, x.elRewardAddress) }

d.appendBlock(txs*)
d.advanceConsensusLayerChanged()
Expand Down Expand Up @@ -77,7 +71,6 @@ trait BaseIntegrationTestSuite

val balances = List(
AddrWithBalance(TxHelpers.defaultAddress, 1_000_000.waves),
AddrWithBalance(d.stakingContractAddress, 10.waves),
AddrWithBalance(d.chainContractAddress, 10.waves)
) ++ settings.finalAdditionalBalances

Expand Down
3 changes: 1 addition & 2 deletions src/test/scala/units/ExtensionDomain.scala
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ class ExtensionDomain(
with CustomMatchers
with AutoCloseable
with ScorexLogging { self =>
override val chainContractAccount: KeyPair = KeyPair("chain-contract".getBytes(StandardCharsets.UTF_8))
override val stakingContractAccount: KeyPair = KeyPair("staking-contract".getBytes(StandardCharsets.UTF_8))
override val chainContractAccount: KeyPair = KeyPair("chain-contract".getBytes(StandardCharsets.UTF_8))

val l2Config = settings.config.as[ClientConfig]("waves.l2")
require(l2Config.chainContractAddress == chainContractAddress, "Check settings")
Expand Down
Loading

0 comments on commit 8f9d93e

Please sign in to comment.