logo

Dividend Pool

ACS10 - Dividend Pool Standard#

ACS10 facilitates the creation and management of dividend pools within a contract.

Interface#

To create a dividend pool, implement these optional interfaces:

Methods#

Method NameRequest TypeResponse TypeDescription
Donateacs10.DonateInputgoogle.protobuf.EmptyTransfers tokens from the caller to the dividend pool. Converts non-native tokens to native tokens if required.
Releaseacs10.ReleaseInputgoogle.protobuf.EmptyReleases dividends based on the specified period number.
SetSymbolListacs10.SymbolListgoogle.protobuf.EmptySets the list of token symbols supported by the dividend pool.
GetSymbolListgoogle.protobuf.Emptyacs10.SymbolListRetrieves the list of token symbols supported by the dividend pool.
GetUndistributedDividendsgoogle.protobuf.Emptyacs10.DividendsQueries the balance of undistributed tokens according to the symbol list.
GetDividendsgoogle.protobuf.Int64Valueacs10.DividendsQueries dividend information based on the specified height.

Types#

acs10.Dividends

FieldTypeDescriptionLabel
valueDividends.ValueEntryThe dividends, symbol -> amount.repeated

acs10.Dividends.ValueEntry

FieldTypeDescriptionLabel
keystring
valueint64

acs10.DonateInput

FieldTypeDescriptionLabel
symbolstringThe token symbol to donate.
amountint64The amount to donate.

acs10.DonationReceived

FieldTypeDescriptionLabel
fromaelf.AddressThe address of donors.
pool_contractaelf.AddressThe address of dividend pool.
symbolstringThe token symbol Donated.
amountint64The amount Donated.

acs10.ReleaseInput

FieldTypeDescriptionLabel
period_numberint64The period number to release.

acs10.SymbolList

FieldTypeDescriptionLabel
valuestringThe token symbol list.repeated

aelf.Address

FieldTypeDescriptionLabel
valuebytes

aelf.BinaryMerkleTree

FieldTypeDescriptionLabel
nodesHashThe leaf nodes.
rootHashThe root node hash.repeated
leaf_countint32The count of leaf node.

aelf.Hash

FieldTypeDescriptionLabel
valuebytes

aelf.LogEvent

FieldTypeDescriptionLabel
addressAddressThe contract address.
namestringThe name of the log event.
indexedbytesThe indexed data, used to calculate bloom.repeated
non_indexedbytesThe non indexed data.repeated

aelf.MerklePath

FieldTypeDescriptionLabel
merkle_path_nodesMerklePathNodeThe merkle path nodes.repeated

aelf.MerklePathNode

FieldTypeDescriptionLabel
hashHashThe node hash.
is_left_child_nodeboolWhether it is a left child node.

aelf.SInt32Value

FieldTypeDescriptionLabel
valuesint32

aelf.SInt64Value

FieldTypeDescriptionLabel
valuesint64

aelf.ScopedStatePath

FieldTypeDescriptionLabel
addressAddressThe scope address.
pathStatePathThe path of contract state.

aelf.SmartContractRegistration

FieldTypeDescriptionLabel
categorysint32The category of contract code (0: C#).
codebytesThe byte array of the contract code.
code_hashHashThe hash of the contract code.
is_system_contractboolWhether it is a system contract.
versionint32The version of the current contract.

aelf.StatePath

FieldTypeDescriptionLabel
partsstringThe partial path of the state path.repeated

aelf.Transaction

FieldTypeDescriptionLabel
fromAddressThe address of the sender of the transaction.
toAddressThe address of the contract when calling a contract.
ref_block_numberint64The height of the referenced block hash.
ref_block_prefixbytesThe first four bytes of the referenced block hash.
method_namestringThe name of a method in the smart contract at the To address.
paramsbytesThe parameters to pass to the smart contract method.
signaturebytesWhen signing a transaction, subset of fields: from/to, target method, parameter, reference block number, prefix.

aelf.TransactionExecutingStateSet

FieldTypeDescriptionLabel
writesTransactionExecutingStateSet.WritesEntryThe changed states.repeated
readsTransactionExecutingStateSet.ReadsEntryThe read states.repeated
deletesTransactionExecutingStateSet.DeletesEntryThe deleted states.repeated

aelf.TransactionExecutingStateSet.DeletesEntry

FieldTypeDescriptionLabel
keystring
valuebool

aelf.TransactionExecutingStateSet.ReadsEntry

FieldTypeDescriptionLabel
keystring
valuebool

aelf.TransactionExecutingStateSet.WritesEntry

FieldTypeDescriptionLabel
keystring
valuebytes

aelf.TransactionResult

FieldTypeDescriptionLabel
transaction_idHashThe transaction id.
statusTransactionResultStatusThe transaction result status.
logsLogEventThe log events.repeated
bloombytesBloom filter for transaction logs.repeated
return_valuebytesThe return value of the transaction execution.
block_numberint64The height of the block that packages the transaction.
block_hashHashThe hash of the block that packages the transaction.
errorstringFailed execution error message.

aelf.TransactionResultStatus

NameNumberDescription
NOT_EXISTEDThe execution result of the transaction does not exist.
PENDING1The transaction is in the transaction pool waiting to be packaged.
FAILED2Transaction execution failed.
MINED3The transaction was successfully executed and packaged into a block.
CONFLICT4When executed in parallel, there are conflicts with other transactions.
PENDING_VALIDATION5The transaction is waiting for validation.
NODE_VALIDATION_FAILED6Transaction validation failed.

Usage#

ACS10 provides a standardized interface for dividend pools, independent of aelf chain interactions.

Implementation#

  • Using the Profit Contract
  • 1
    State.ProfitContract.Value =
    2
    Context.GetContractAddressByName(SmartContractConstants.ProfitContractSystemName);
    3
    var schemeToken = HashHelper.ComputeFrom(Context.Self);
    4
    State.ProfitContract.CreateScheme.Send(new CreateSchemeInput
    5
    {
    6
    Manager = Context.Self,
    7
    CanRemoveBeneficiaryDirectly = true,
    8
    IsReleaseAllBalanceEveryTimeByDefault = true,
    9
    Token = schemeToken
    10
    });
    11
    State.ProfitSchemeId.Value = Context.GenerateId(State.ProfitContract.Value, schemeToken);
  • Using the TokenHolder Contract
  • 1
    State.TokenHolderContract.Value =
    2
    Context.GetContractAddressByName(SmartContractConstants.TokenHolderContractSystemName);
    3
    State.TokenHolderContract.CreateScheme.Send(new CreateTokenHolderProfitSchemeInput
    4
    {
    5
    Symbol = Context.Variables.NativeSymbol,
    6
    MinimumLockMinutes = input.MinimumLockMinutes
    7
    });
    8
    return new Empty();
  • Donate can be implemented as:
  • 1
    public override Empty Donate(DonateInput input)
    2
    {
    3
    State.TokenContract.TransferFrom.Send(new TransferFromInput
    4
    {
    5
    From = Context.Sender,
    6
    Symbol = input.Symbol,
    7
    Amount = input.Amount,
    8
    To = Context.Self
    9
    });
    10
    State.TokenContract.Approve.Send(new ApproveInput
    11
    {
    12
    Symbol = input.Symbol,
    13
    Amount = input.Amount,
    14
    Spender = State.TokenHolderContract.Value
    15
    });
    16
    State.TokenHolderContract.ContributeProfits.Send(new ContributeProfitsInput
    17
    {
    18
    SchemeManager = Context.Self,
    19
    Symbol = input.Symbol,
    20
    Amount = input.Amount
    21
    });
    22
    Context.Fire(new DonationReceived
    23
    {
    24
    From = Context.Sender,
    25
    Symbol = input.Symbol,
    26
    Amount = input.Amount,
    27
    PoolContract = Context.Self
    28
    });
    29
    var currentReceivedDividends = State.ReceivedDividends[Context.CurrentHeight];
    30
    if (currentReceivedDividends != null && currentReceivedDividends.Value.ContainsKey(input.Symbol))
    31
    {
    32
    currentReceivedDividends.Value[input.Symbol] =
    33
    currentReceivedDividends.Value[input.Symbol].Add(input.Amount);
    34
    }
    35
    else
    36
    {
    37
    currentReceivedDividends = new Dividends
    38
    {
    39
    Value =
    40
    {
    41
    {
    42
    input.Symbol, input.Amount
    43
    }
    44
    }
    45
    };
    46
    }
    47
    State.ReceivedDividends[Context.CurrentHeight] = currentReceivedDividends;
    48
    Context.LogDebug(() => string.Format("Contributed {0} {1}s to side chain dividends pool.", input.Amount, input.Symbol));
    49
    return new Empty();
    50
    }
  • The method Release directly sends the TokenHolder’s method DistributeProfits transaction:
  • 1
    public override Empty Release(ReleaseInput input)
    2
    {
    3
    State.TokenHolderContract.DistributeProfits.Send(new DistributeProfitsInput
    4
    {
    5
    SchemeManager = Context.Self
    6
    });
    7
    return new Empty();
    8
    }
  • GetSymbolList returns the symbol list recorded in dividend scheme:
  • 1
    public override SymbolList GetSymbolList(Empty input)
    2
    {
    3
    return new SymbolList
    4
    {
    5
    Value =
    6
    {
    7
    GetDividendPoolScheme().ReceivedTokenSymbols
    8
    }
    9
    };
    10
    }
    11
    private Scheme GetDividendPoolScheme()
    12
    {
    13
    if (State.DividendPoolSchemeId.Value == null)
    14
    {
    15
    var tokenHolderScheme = State.TokenHolderContract.GetScheme.Call(Context.Self);
    16
    State.DividendPoolSchemeId.Value = tokenHolderScheme.SchemeId;
    17
    }
    18
    return Context.Call<Scheme>(
    19
    Context.GetContractAddressByName(SmartContractConstants.ProfitContractSystemName),
    20
    nameof(ProfitContractContainer.ProfitContractReferenceState.GetScheme),
    21
    State.DividendPoolSchemeId.Value);
    22
    }
  • Implementation of GetUndistributedDividends returns the balance (same as previous section):
  • 1
    public override Dividends GetUndistributedDividends(Empty input)
    2
    {
    3
    var scheme = GetDividendPoolScheme();
    4
    return new Dividends
    5
    {
    6
    Value =
    7
    {
    8
    scheme.ReceivedTokenSymbols.Select(s => State.TokenContract.GetBalance.Call(new GetBalanceInput
    9
    {
    10
    Owner = scheme.VirtualAddress,
    11
    Symbol = s
    12
    })).ToDictionary(b => b.Symbol, b => b.Balance)
    13
    }
    14
    };
    15
    }

    Test#

    Testing includes sending Donate, Release transactions, and querying operations. Example:

  • Define the required Stubs:
  • 1
    const long amount = 10_00000000;
    2
    var keyPair = SampleECKeyPairs.KeyPairs[0];
    3
    var address = Address.FromPublicKey(keyPair.PublicKey);
    4
    var acs10DemoContractStub =
    5
    GetTester<ACS10DemoContractContainer.ACS10DemoContractStub>(DAppContractAddress, keyPair);
    6
    var tokenContractStub =
    7
    GetTester<TokenContractContainer.TokenContractStub>(TokenContractAddress, keyPair);
    8
    var tokenHolderContractStub =
    9
    GetTester<TokenHolderContractContainer.TokenHolderContractStub>(TokenHolderContractAddress,
    10
    keyPair);
  • Approve the TokenHolder contract and the dividend pool contract
  • 1
    await tokenContractStub.Approve.SendAsync(new ApproveInput
    2
    {
    3
    Spender = TokenHolderContractAddress,
    4
    Symbol = "ELF",
    5
    Amount = long.MaxValue
    6
    });
    7
    await tokenContractStub.Approve.SendAsync(new ApproveInput
    8
    {
    9
    Spender = DAppContractAddress,
    10
    Symbol = "ELF",
    11
    Amount = long.MaxValue
    12
    });
  • Lock the position to reducethe account balance by 10 ELF:
  • 1
    await tokenHolderContractStub.RegisterForProfits.SendAsync(new RegisterForProfitsInput
    2
    {
    3
    SchemeManager = DAppContractAddress,
    4
    Amount = amount
    5
    });
  • Implement Donate to reduce the account balance by another 10 ELF:
  • 1
    await acs10DemoContractStub.Donate.SendAsync(new DonateInput
    2
    {
    3
    Symbol = "ELF",
    4
    Amount = amount
    5
    });
  • Test the GetUndistributedDividends and GetDividends:
  • 1
    // Check undistributed dividends before releasing.
    2
    {
    3
    var undistributedDividends =
    4
    await acs10DemoContractStub.GetUndistributedDividends.CallAsync(new Empty());
    5
    undistributedDividends.Value["ELF"].ShouldBe(amount);
    6
    }
    7
    var blockchainService = Application.ServiceProvider.GetRequiredService<IBlockchainService>();
    8
    var currentBlockHeight = (await blockchainService.GetChainAsync()).BestChainHeight;
    9
    var dividends =
    10
    await acs10DemoContractStub.GetDividends.CallAsync(new Int64Value {Value = currentBlockHeight});
    11
    dividends.Value["ELF"].ShouldBe(amount);
  • Release bonus, and test GetUndistributedDividends again:
  • 1
    await acs10DemoContractStub.Release.SendAsync(new ReleaseInput
    2
    {
    3
    PeriodNumber = 1
    4
    });
    5
    // Check undistributed dividends after releasing.
    6
    {
    7
    var undistributedDividends =
    8
    await acs10DemoContractStub.GetUndistributedDividends.CallAsync(new Empty());
    9
    undistributedDividends.Value["ELF"].ShouldBe(0);
    10
    }
  • Account will receive the dividend and will change the balance:
  • 1
    var balanceBeforeClaimForProfits = await tokenContractStub.GetBalance.CallAsync(new GetBalanceInput
    2
    {
    3
    Owner = address,
    4
    Symbol = "ELF"
    5
    });
    6
    await tokenHolderContractStub.ClaimProfits.SendAsync(new ClaimProfitsInput
    7
    {
    8
    SchemeManager = DAppContractAddress,
    9
    Beneficiary = address
    10
    });
    11
    var balanceAfterClaimForProfits = await tokenContractStub.GetBalance.CallAsync(new GetBalanceInput
    12
    {
    13
    Owner = address,
    14
    Symbol = "ELF"
    15
    });
    16
    balanceAfterClaimForProfits.Balance.ShouldBe(balanceBeforeClaimForProfits.Balance + amount);

    Example#

    Implementing ACS10 facilitates building dividend pools on main and side chains.

    Edited on: 15 July 2024 05:41:01 GMT+0