Proposal for Enhancements to the XDCValidator Smart Contract


Enhancing the XDCValidator Smart Contract: Introducing Smart Contract Ownership, Ownership Transfers, and Automated Rewards

The XDC Network continues to lead the blockchain space with its robust and enterprise-ready infrastructure. To maintain its edge, we have enhanced the XDCValidator smart contract with new features that improve flexibility, scalability, and efficiency in masternode management. These updates empower both individuals and smart contracts to participate seamlessly in the XDC ecosystem.


Key Updates to the XDCValidator Smart Contract

1. Smart Contract Ownership of Masternodes

Previously, only externally owned accounts (EOAs) could own and manage masternodes. With this enhancement, smart contracts can now directly own and operate masternodes. This upgrade expands the potential use cases, enabling DAOs, decentralized applications, and other blockchain systems to manage masternodes effectively.

Why It Matters:

  • Decentralized Governance: DAOs can now manage masternodes collectively.
  • Extended Utility: Applications like staking platforms can integrate masternode management directly.
  • Inclusivity: Smart contracts become active participants in securing the network.

2. Node Ownership Transfers

Node ownership is no longer static. With the introduction of a secure transfer mechanism, masternode owners can reassign ownership to another individual or smart contract without disrupting node operations.

Why It Matters:

  • Flexibility: Owners can sell or delegate their nodes easily.
  • Business Continuity: Nodes remain operational during ownership changes.
  • Transparency: Ownership transfers are recorded on-chain for full accountability.

Example Use Case:

An individual managing multiple masternodes for their business can transfer specific nodes to a subsidiary or a smart contract that automates their operations.


3. Automated Reward Distribution

Rewards are now distributed programmatically to validators and standby nodes through a batch processing mechanism. This feature ensures rewards are paid out efficiently and on time, with minimal manual intervention.

Why It Matters:

  • Efficiency: Reduces the administrative burden of reward distribution.
  • Scalability: Handles large-scale payouts effectively.
  • Trust: Ensures timely payments, boosting confidence in the system.

Example Use Case:

A validator running multiple masternodes receives rewards automatically into their address or directly to a smart contract managing their funds.


Technical Overview of Updates

Enhanced Features

  1. Smart Contract Ownership:

    • Any valid Ethereum address (EOA or smart contract) can own a masternode.
    • Ownership mappings and transfer mechanisms have been adjusted to support this.
  2. Node Ownership Transfer:

    • A new transferOwnership function securely transfers masternode ownership.
    • On-chain mappings ensure the proper reassignment of ownership.
  3. Automated Rewards:

    • A new distributeRewards function enables batch processing of rewards.
    • Designed to handle scalability while ensuring efficiency.

Security Enhancements

  • Access Control: Critical functions like distributeRewards are restricted to the contract owner.
  • Reentrancy Protection: Reward transfers use call to mitigate gas issues and ensure robustness.
  • Fallback Logging: The fallback function includes logging for all incoming funds, enhancing transparency.

Updated Smart Contract Code

The enhanced XDCValidator smart contract incorporates these features. Below is a snippet highlighting the key updates:

pragma solidity ^0.8.0;

contract XDCValidator {
    using SafeMath for uint256;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner, address candidate);
    event RewardsDistributed(address indexed recipient, uint256 amount);
    event FundsReceived(address indexed sender, uint256 amount);

    struct ValidatorState {
        address owner;
        bool isCandidate;
        uint256 cap;
        mapping(address => uint256) voters;
    }

    mapping(address => ValidatorState) private validatorsState;
    mapping(address => address[]) private ownerToCandidate;

    address[] public candidates;
    address[] public owners;

    uint256 public minCandidateCap;
    uint256 public minVoterCap;
    uint256 public maxValidatorNumber;

    address private contractOwner;

    modifier onlyOwner(address _candidate) {
        require(validatorsState[_candidate].owner == msg.sender, "Not the owner of this candidate");
        _;
    }

    modifier onlyContractOwner() {
        require(msg.sender == contractOwner, "Not authorized");
        _;
    }

    modifier onlyValidCandidate(address _candidate) {
        require(validatorsState[_candidate].isCandidate, "Not a valid candidate");
        _;
    }

    constructor(
        uint256 _minCandidateCap,
        uint256 _minVoterCap,
        uint256 _maxValidatorNumber
    ) {
        minCandidateCap = _minCandidateCap;
        minVoterCap = _minVoterCap;
        maxValidatorNumber = _maxValidatorNumber;
        contractOwner = msg.sender;
    }

    function transferOwnership(address _candidate, address _newOwner)
        external
        onlyOwner(_candidate)
        onlyValidCandidate(_candidate)
    {
        require(_newOwner != address(0), "New owner address cannot be zero");
        ValidatorState storage validator = validatorsState[_candidate];
        address previousOwner = validator.owner;

        validator.owner = _newOwner;

        _removeCandidateFromOwner(previousOwner, _candidate);
        ownerToCandidate[_newOwner].push(_candidate);

        emit OwnershipTransferred(previousOwner, _newOwner, _candidate);
    }

    function distributeRewards(address[] calldata _recipients, uint256[] calldata _amounts)
        external
        onlyContractOwner
    {
        require(_recipients.length == _amounts.length, "Input arrays length mismatch");

        for (uint256 i = 0; i < _recipients.length; i++) {
            address recipient = _recipients[i];
            uint256 amount = _amounts[i];
            require(validatorsState[recipient].isCandidate, "Recipient must be a valid candidate");
            require(address(this).balance >= amount, "Insufficient balance");

            (bool success, ) = recipient.call{value: amount}("");
            require(success, "Reward transfer failed");

            emit RewardsDistributed(recipient, amount);
        }
    }

    receive() external payable {
        emit FundsReceived(msg.sender, msg.value);
    }

    function _removeCandidateFromOwner(address _owner, address _candidate) internal {
        uint256 length = ownerToCandidate[_owner].length;
        for (uint256 i = 0; i < length; i++) {
            if (ownerToCandidate[_owner][i] == _candidate) {
                ownerToCandidate[_owner][i] = ownerToCandidate[_owner][length - 1];
                ownerToCandidate[_owner].pop();
                break;
            }
        }
    }
}

Conclusion

These enhancements make the XDCValidator contract more flexible, scalable, and user-friendly. By enabling smart contract ownership, secure ownership transfers, and automated reward distribution, the XDC Network strengthens its position as a leader in enterprise-grade blockchain technology.

We invite the XDC community to review, test, and implement these changes to further improve the ecosystem. Let us know your thoughts and feedback!


3 Likes

This proposal addresses several important issues:

  1. Inconsistencies in reward distribution.
  2. Manual interventions in reward distribution (along with related regulatory concerns).
  3. The inability to automatically distribute node rewards via a smart contract mechanism (along with related regulatory concerns).
  4. Inflexibility in node ownership and transfer.

Resolution of these issues would be a significant step forward in the technology of XDC Network. Please review, test, and provide critical feedback.

1 Like

This is a great proposal for enhancements that are extremely needed to catch up with what other chains have achieved. Chains that have recently launched their mainnet have also allowed the tokenization of their nodes into NFT’s to sell in secondary markets (not a priority but very desired). One thing to note is that the current 2.3.0 version (2.4.0 coming soon) does not address any of these issues. Allowing these changes will free up liquidity for validators that want to utilize their current holds in the XDC Ecosystem. Huge changes in this proposal but if we address reward distribution automation and allowing to change ownership to a different address will significally enhance the network posture by allowing the change of address if a wallet were to be compromised as well. Imagine your wallet gets hacked and rewards are still coming in…you can lose your entire hold if you dont have this feature enabled.

Have been seeking to see such proposal for a long term. Thanks for sharing.

Ease of access of other smart contract to build on top without doing a lot of hard work for verification of MN owner address is important.

I see a downfall with the Ownership transferring mechanism is that if the Ownership changes from address A to address B, this change may affect the SCs are already built on top and requires an extra work by an off-chain service to sync up the current Owner state which doesn’t encourage decentralization for most of high-level SCs by default.

From my understanding, the Reward automation process for standby nodes is a bit tricky.

Validator gets rewarded based on each epoch time. I’m still in doubt that where the reward of standby node comes from. And where is the right place to release reward whether XDCValidator sc or treasury or inflation on each epoch?(need to be double-checked on tokenomics/whitepaper)

From the verification stand point, “Validator” address and “Standby” address are not flagged separately, means let’s say an owner has 10 MNs, 7 in the validator list(in that 108) and 3 in standby. In the XDCValidator contract you can’t understand who is validator or who is standby. Identifying the wrong standby simply leads, validator gets rewarded twice.

This proposal requires more technical specs and details.

Pls correct me in case of any misunderstanding or mistake on the my feedback.

@0xBeny @arturo – Have you considered an X space or similar forum to get more eyes on this proposal? It’s important in two ways: (1) the substantive concern over the current limitations of the Masternode smart contract and (2) the procedural concern related to the difficulty of proposing a meaningful change and seeing it through to adoption. From a broad perspective, the latter is more important than the former.

The creation of the XIP Process was a strong effort to address how change is implemented but, despite a consensus of approval and contemporaneous adoption, few community members have been following the protocol. Similarly, efforts around the XDCDao (thank you for your efforts, @0xBeny) seem to have lost momentum. But if neither of those processes are being followed, how are things getting done? The possible answers–which include (1) nothing is getting done, (2) another, unidentified process is being used to foster change, and (3) all progress is fully centralized–leave a lot to be desired.

What do you propose as a next step to shepherding this proposal through to finality? I believe you have the consensus among the developer community. Let’s go! :fire:

Combining XIP process and XDCDAO are ideal to get both maturity and transparency on the future decisions of protocol.

However, doing all require hands-on help of community or more OG members as its heavy lifting for only one or two person to take it forward with ZERO collaboration of the others.

XDCDAO side, master node onboarding stuck which I will probably come with another way around it to take it forward soon.

Community has been always the priority of XDC.
However when we say community, we expect more people to show up and be active in community and XDC ecosystem for long term wins. Level of collaboration is clear when look at two different forums that we have.
Otherwise there will be a few people left to move things forward.

At the end Community will decide the way out!

We are up to elaborate and engage on any social media on it.

Sorry i had to be transparent on that.

@0xBeny,
Thanks for the response. I’m not sure why you’d apologize for being transparent; I’d expect an apology if you were intentionally being opaque.

I understand the problem faced with the fractured response and inconsistency. But that’s my point. How do we refocus the community?

Part of the problem is the redundancy in processes and resources. Most people don’t want to be forced to check two sites when there’s not a good reason for doing so. So, for example, can the XIP Process be “built in” to the DAO process, or vice versa? Do we need multiple sites that serve as resources, or can they all just point to one repository?

Also, shepherding an improvement proposal (whether initiated in the XIP Process or via XDCDAO) is not your job or XinFin’s job; it’s the responsibility of the party that proposed and stands to gain from the change (in this case, Prime Numbers Labs). But the process must be made clear for them, and that is what you and others who are close to the project should be focusing on. Once the road is paved, developers will walk down it. But they won’t leap over holes and climb over walls that should have been fixed by now. And they don’t want to be told that they must walk down three roads simultaneously. The XIP process was designed with those concerns in mind, but the follow through was lacking. As the most obvious example, after the XIP Process was adopted, the XDC 2.0 update should have been migrated there as an XDC Network Improvement Proposal; it would easily have reached consensus and would have sent a loud and clear message to the community that all changes to the network protocol needed to be routed through the new process.

Are there any concrete actions you need help with as you try to move this forward?

I don’t think we have any responsibility from Prime Numbers Labs to build this.

We can help with advice about improving the network from our point of view.

Our mission was to improve the network since Day 0.

We bring etherscan, layerzero, Stargate…

As I said, someone needs to make proposals to benefit everyone.

If the proposal involves development work, we will request a proportional amount of funding because this implicates time that we will not be focused on and funds that are not spent in our company.

I agree with you that someone needs a well-structured development.

Arturo! Thanks for chiming in.

TL:DR

You’re right. Prime Numbers has no responsibility here. And neither does any other person or entity. This is decentralization: no one has responsibility.

Perhaps this was a poor proposal for Beny and me to be discussing how to improve the general process as it apparently lacks the typical incentives. I wrote above that Prime Numbers bore the “responsibility” to shepherd the “Proposal for Enhancements to the XDCValidator Smart Contract” which you proposed. That was poor of me. I based that assertion on my assumption that Prime Numbers had an economic incentive to propose and develop the change and ultimately convince the community (whoever that is) that the change ought to be adopted. Good for you that you’re being more charitable than I was giving you credit for (inasmuch as you proposed this for the good of the community and not because it affects your bottom line).

What I was trying to communicate is that change is unlikely to occur unless an interested party stands up and takes responsibility throughout the process.

I disagree with you that “someone needs to make proposals to benefit everyone.” That view ignores financial incentives and even you couldn’t resist stating the obvious in that regard:

XDC Network cannot afford a pure “what’s best for the community” mentality; companies must be invited to build because doing so improves their own bottom line. At that point, they will spend their own funds to propose, fund, and finalize changes that help them do what they came to do: make money.

I digress. The point here and now, as you stated, is that companies need a well-structured process with a short and shallow learning curve so they can appropriately change the network and network-adjacent programming to suit their specific needs. If a developer gets stuck at the threshold of immutable code, he’ll go somewhere else. XDC Network is not–in its current state–the Network of the Next Millennium. 2.0 proves that even immutable ledgers require process changes.

Let’s go. :fire:

First off, I’m happy that this topic opened in public forum not in private chats,

Xinfin is still the main contributor of the XDC protocol. Since day one has provided bounty to open source contributors as well. And looking for more open source contributors.

XIPs hadn’t proceeded well a few years back(already heard stories) due to lack of participation. And after that we haven’t had structured way to proceed ideas. We fell into a poor process on xdc.dev.

I believe it requires a dedicated person to take it forward. And OG members of XDC should come and speak in public not private groups.
Then we will have a proper and standard way to move the protocol forward.

Considering that we’re not inventing XIP process, ten different best practices are available in the market.

Let’s make progress i feel we’re stagnant in a way that people tend to complain rather than taking actions. And it requires all OGs effort and encouraging others to have a voice. Not one buddy.

Would like to invite you all to have a deep conversation as AMA session on X to gather initiatives again into one round table.

2 Likes

I agree that OG’s tend to chime in private chats (me included) and they all bring great ideas and conversations, but we need to start voicing our opinion in the official channels setup for this purpose. I am for one going to make an effort to bring awareness and keep inviting OG’s to the group.
I am game to support this effort.