Skip to main content

Overview

Security Token smart contract implementation from CoMakery (dba Upside). The core purpose of the token is to enforce transfer restrictions for certain groups.

This implementation attempts to balance simplicity and sufficiency for smart contract security tokens that need to comply with regulatory authorities - without adding unnecessary complexity for simple use cases. It implements the ERC-20 token standard with ERC-1404 security token transfer restrictions.

This approach takes into account yet to be standardized guidance from ERC-1400 (which has additional recommendations for more complex security token needs) and ERC-1404 which offers an approach similar to ERC-902. Unfortunately ERC-1404 does not adopt ERC-1066 standard error codes - which this project may adopt in the future. Since no security token standards have reached mass adoption or maturity and they do not fully agree with each other, the token optimizes for a simple and sufficient implementation.

Simplicity is desirable so that contract functionality is clear. It also reduces the number of smart contract lines that need to be secured (each line of a smart contract is a security liability).

Disclaimer

This open or closed source software is provided with no warranty. This is not legal advice. CoMakery (dba Upside) is not a legal firm and is not your lawyer. Securities are highly regulated across multiple jurisdictions. Issuing a security token incorrectly can result in financial penalties or jail time if done incorrectly. Consult a lawyer and tax advisor. Conduct an independent security audit of the code.

On-Chain Holder/Wallet Management

Active Holder/Wallet management is conducted on-chain and autonomously, with multiple admin configurations that allow flexibility of transfer rule configuration. This greatly simplifies the off-chain accounting and effort required from Transfer (and other) Admins, removing the need to track Wallet holdings across different Holders.

Wallets are not programatically prohibited from assuming multiple Admin roles. We advise against this in practice; however, this must be enforced off-chain.

Holders are allowed to keep multiple Wallet addresses, which can be spread across multiple Transfer Groups (in which case, they would be added to each group's holder count) as well as within Transfer Groups. These Wallets are consolidated under a common holderId.

  • Ex.: Holder A can have 4 wallets spread across two Transfer Groups, X and Y. The Holder can have Wallets 1 & 2 in Group X, and Wallets 3 & 4 in Group Y. They will still count overall as one single Holder, but it will also be considered as a unique holder in Group X and one unique holder in Group Y.

To manage these Holders and their Wallets:

  • A hook has been overridden (_update) for mint/transfer/burn/freeze functions, automatically checking that recipient Wallet addresses of tokens are cataloged and assigned holderIds as needed.
  • If a "new" Wallet address receives a token, a new holderId is created for that Wallet address.
  • Admins can also separately create Holders from Wallet addresses and append Wallet addresses to existing Holder accounts

Transfer Restrictions

The Security Token can be configured after deployment to enforce transfer restrictions such as the ones shown in the diagram below. Each Holder's blockchain Wallet address corresponds to a different group.

This is enforced in TransferRules.sol.

Example

Only transfers between wallet address groups in the direction of the arrows are allowed:

Here's an example overview of how transfer restrictions could be configured and enforced.

The Transfer Admin for the Token Contract can provision wallet addresses to transfer and receive tokens under certain defined conditions. This is the process for configuring transfer restrictions and executing token transfers:

  1. An Investor sends their Anti Money Laundering and Know Your Customer (AML/KYC) information to the Transfer Admin or to a proxy vetting service off-chain to verify this information.

    • The benefit of using a qualified third party provider is to avoid needing to store privately identifiable information.
    • We recommend implementations use off-chain mechanisms (such as a 3rd party AML/KYC provider) that ensure a given address is approved and is a non-malicious smart contract wallet. However, generally multi-signature type wallets must be allowed in order to provide adequate security for investors.
    • This smart contract implementation does not provide a solution for collecting AML/KYC information.
  2. The Transfer Admin or Wallet Admin calls setAddressPermissions(buyerAddress, transferGroup, freezeStatus) to provision their account. Initially this will be done for the Primary Issuance of tokens to Investors where tokens are distributed directly from the Issuer to Holder wallets, where:

    • buyerAddress: Buyer/Investor wallet address for which to set permissions
    • transferGroup: desired transfer group ID for wallet address
    • freezeStatus: boolean flag signifying whether the address is frozen from executing transfers (if set to true)
  3. A potential Investor sends their AML/KYC information to the Transfer Admin or Wallet Admin or a trusted AML/KYC provider.

  4. The Transfer Admin or Wallet Admin calls setAddressPermissions(buyerAddress, transferGroup, freezeStatus) to provision the Investor account.

  5. At this time (or potentially earlier), the Transfer Admin or Wallet Admin authorizes the transfer of tokens between account groups with setAllowGroupTransfer(fromGroup, toGroup, afterTimestamp). Note that allowing a transfer from group A to group B by default does not allow the reverse transfer from group B to group A. This would need to be configured separately.

    • Ex.: Reg CF unaccredited Investors may be allowed to sell to Accredited US Investors but not vice versa.

Relevant methods:

/**
* @dev Sets an allowed transfer from a group to another group beginning at a specific time.
* There is only one definitive rule per from and to group.
* @param from The group the transfer is coming from.
* @param to The group the transfer is going to.
* @param lockedUntil The unix timestamp that the transfer is locked until. 0 is a special number. 0 means the transfer is not allowed.
* This is because in the smart contract mapping all pairs are implicitly defined with a default lockedUntil value of 0.
* But no transfers should be authorized until explicitly allowed. Thus 0 must mean no transfer is allowed.
*/
function setAllowGroupTransfer(
uint256 from,
uint256 to,
uint256 lockedUntil
) external onlyTransferAdmin {
/**
* @dev A convenience method for updating the transfer group and freeze status.
* @notice This function has a different signature than the Utility Token implementation
* @param buyerAddr_ The wallet address to set permissions for.
* @param groupId_ The desired groupId to set for the address.
* @param freezeStatus_ The frozenAddress status of the address. True means frozen false means not frozen.
*/
function setAddressPermissions(
address buyerAddr_,
uint256 groupId_,
bool freezeStatus_
) external validAddress(buyerAddr_) onlyWalletsAdminOrTransferAdmin {

WARNING: Maximum Total Supply, Minting and Burning of Tokens

The variable maxTotalSupply is set when the contract is created and limits the total number of tokens that can be minted. It represents authorized shares and can be updated per company legal documents by setMaxTotalSupply.

Reserve Admins can mint tokens to and burn tokens from any address. This is primarily to comply with law enforcement, regulations and stock issuance scenarios - but this centralized power could be abused. Transfer Admins, authorized by Contract Admins, can also update the transfer rules at any moment in time as many times as they want.

Token Supply

There are also values that can be read from the smart contract for total token supply, circulating token supply, and unissued token supply. These correspond to the analogous Authorized shares, Outstanding shares, and Unissued shares, respectively, that exist in the context of stocks.

These methods are totalTokenSupply(), circulatingTokenSupply(), and unissuedTokenSupply().

Issue shares to investors

The reserve admin distributes the unissuedTokenSupply() to investors using either mint() or mintReleaseSchedule(), which increases the circulatingTokenSupply(). This method of token issuance should be used by issuers.

From a company shares perspective there are “authorized” and “outstanding” (issued) shares. For security tokens the authorized and unissued shares should not be held in a blockchain account. If they are unissued they should be distributed using the mint() or mintReleaseSchedule() functions. If shares are repurchased or reclaimed they should be retired by burning them. This is because all shares distributed to blockchain addresses receive dividend distributions.

Issued is a synonym for outstanding.

It should always hold true that circulatingTokenSupply == outstanding == issued, as these terms represent the same concept. Both circulatingTokenSupply() and totalSupply() reflect this value on-chain, ensuring consistency across these metrics.

Any “treasury” should not be issued on chain in a blockchain address. authorized == maxTokenSupply (also synonyms).

Overview of Transfer Restriction Enforcement Functions

FromToRestrictEnforced ByAdmin Role
Reg D/S/CFAnyoneUntil TimeLock endsfundReleaseSchedule(investorAddress, balanceReserved, commencementTime, scheduleId, cancelableByAddresses)Any Admin
Reg D/S/CFAnyoneUntil TimeLock endsmintReleaseSchedule(investorAddress, balanceReserved, commencementTime, scheduleId, cancelableByAddresses)Reserve Admin
Reg S GroupUS AccreditedForbidden During Flowback Restriction PeriodsetAllowGroupTransfer(fromGroupS, toGroupD, afterTime)Transfer Admin
Reg S GroupReg S GroupForbidden Until Shorter Reg S TimeLock EndedsetAllowGroupTransfer(fromGroupS, toGroupS, afterTime)Transfer Admin
IssuerReg CF with > maximum number of total holders allowedForbid transfers increasing number of total Holders (across all groups) above a certain thresholdsetHolderMax(maxAmount)Transfer Admin
IssuerReg CF with > maximum number of Holders per group allowedForbid transfers increasing number of total Holders (within each group) above a certain thresholdsetHolderGroupMax(transferGroupID, maxAmount)Transfer Admin
Stolen TokensAnyoneFix With Freeze, Burn, Reissuefreeze(address, isFrozenFlag);
burn(address, amount);
mint(newOwnerAddress);
Wallets Admin or Transfer Admin can freeze() and Reserve Admin can do mint() burn()
Any Address During Regulatory FreezeAnyoneForbid all transfers while pausedpause(isPausedFlag)Transfer Admin
Any Address During Regulatory FreezeAnyoneUnpause from a paused statepause(isPausedFlag)Transfer Admin
AnyoneAnyoneForce the transfer of tokens for emergenciesforceTransferBetween(sender, recipient, amount)Reserve Admin

Roles

The smart contract enforces specific admin roles. The roles divide responsibilities to reduce abuse vectors and create checks and balances. Ideally each role should be managed by a separate admin with separate key control.

In some cases, such as for the Contract Admin or Wallets Admin, it is recommended that the role's private key is managed through multi-signature (e.g. requiring 2 of 3 or N of M approvers) authentication.

Admin Types

The Admin functionality breaks down into 4 main roles. The contract is configured to expect these wallets. In the contract constructor:

  • Contract Admin
    • Akin to root level access administrator. Can upgrade internal contract dependencies (ie RestrictedSwap, TransferRules) or grant Admin permissions. Recommended to be a secure multi-sig wallet.
  • Reserve Admin
    • Receives initial tranche of minted tokens from deployment. Also can adjust the supply of tokens by minting or burning or forcibly initiate transfers.

Via granted roles (from Contract Admin):

  • Transfer Admin
    • Can set transfer restriction permissions/rules between groups.
    • Transfer Admin capabilities are a superset of those of Wallets Admin.
  • Wallets Admin
    • Can manage Holder/Wallet transfer group assignments.

Typically any legal entity third-party Transfer Agent will need access to both the roles for Transfer Admin and Wallets Admin. However some agents (such as exchanges) will, for example, be able to assign groups to wallets and permission them (as a Wallets Admin) but will not be able to adjust the transfer rules.

Admin Functionality

FunctionContract AdminReserve AdminTransfer AdminWallets Admin
grantRole()yesnonono
revokeRole()yesnonono
upgradeTransferRules()yesnonono
pause() or unpause (ie pause(false))yesnoyesno
mint()noyesnono
burn()noyesnono
forceTransferBetween()noyesnono
batchMintReleaseSchedule()noyesnono
mintReleaseSchedule()noyesnono
setMaxTotalSupply()noyesnono
setAllowGroupTransfer()nonoyesno
setHolderMax()nonoyesno
setHolderGroupMax()nonoyesno
fundDividend()nonoyesno
setAddressPermissions()nonoyesyes
freeze()nonoyesyes
setTransferGroup()nonoyesyes
createHolderFromAddress()nonoyesyes
appendHolderAddress()nonoyesyes
addHolderWithAddresses()nonoyesyes
removeHolder()nonoyesyes
removeWalletFromHolder()nonoyesyes
batchRemoveWalletFromHolder()nonoyesyes
createReleaseSchedule()yesyesyesyes
batchFundReleaseSchedule()yesyesyesyes
fundReleaseSchedule()yesyesyesyes

Use Cases

Initial Security Token Deployment

  1. The Deployer configures the parameters and deploys the smart contracts to a public EVM blockchain. At the time of deployment, the deployer configures a separate Reserve Admin address, a Transfer Admin address, and a Wallets Admin address. This allows the reserve security tokens to be stored in cold storage since the treasury Reserve Admin address private keys are not needed for everyday use by the Transfer Admin.
  2. The Reserve Admin then provisions a Wallets Admin address for distributing tokens to investors or other stakeholders. The Wallets Admin uses setAddressPermissions(investorAddress, transferGroup, freezeStatus) to set address restrictions.
  3. The Transfer Admin authorizes the transfer of tokens between account groups with setAllowGroupTransfer(fromGroup, toGroup, afterTimestamp) .
  4. The Reserve Admin then transfers tokens to the Wallets Admin address.
  5. The Wallets Admin then transfers tokens to Investors or other stakeholders who are entitled to tokens.

Setup For Separate Issuer Private Key Management Roles

By default the reserve tokens cannot be transferred to. To allow transfers the Transfer Admin or Wallets Admin must configure transfer rules using both setAddressPermissions(account, ...) to configure the individual account rules and setAllowGroupTransfer(...) to configure transfers between accounts in a group. A group represents a category like US accredited investors (Reg D) or foreign investors (Reg S).

During the setup process to split transfer oversight across three private key holders, the Transfer Admin can setup rules that only allow the Reserve Admin group to only transfer tokens to the Wallets Admin address group. The Wallets Admin should be restricted to a limited maximum balance necessary for doing one batch of token distributions - rather than the whole reserve. The use of a hot wallet Wallets Admin for small balances also makes everyday token administration easier without exposing the issuer's reserve of tokens to the risk of total theft in a single transaction. Each of these private keys may also be managed with a multi-sig solution for added security.

Multi-sig is especially important for the token Reserve Admin and Contract Admin.

Here is how these restricted Admin accounts can be configured:

  1. Transfer Admin, Reserve Admin and Wallets Admin accounts are managed by separate users with separate keys. For example, separate Nano Ledger S hardware wallets.
  2. Reserve and Wallets Admin addresses can have their own separate transfer groups.
    • setAddressPermissions(reserveAdminAddress, reserveAdminTransferGroup, freezeStatus)
    • setAddressPermissions(walletsAdminAddress, walletsAdminTransferGroup, freezeStatus)
  3. Reserve Address Group can only transfer to Wallets Admin Groups after a certain Timestamp.
    • setAllowGroupTransfer(reserveAdminTransferGroup, walletsAdminTransferGroup, afterTimestamp)
  4. Wallets Admin Address can transfer to investor groups like Reg D and Reg S after a certain Timestamp.
    • setAllowGroupTransfer(walletsAdminTransferGroup, regD_TransferGroup, afterTimestamp)
    • setAllowGroupTransfer(walletsAdminTransferGroup, regS_TransferGroup, afterTimestamp)

Then the Wallets Admin can distribute tokens to investors and stakeholders as described below...

Issuing the Token To AML / KYC'd Recipients

  1. The Transfer Admin gathers AML/KYC and accreditation information from investors and stakeholders who will receive tokens directly from the Issuer (the Primary Issuance).

  2. (optional) set the Holder max if desired

  3. Transfer Admin configures approved Transfer Group for Wallets Admin.

  4. Transfer Admin then configures approved Transfer Groups for Investor and stakeholders with setAddressPermissions(address, transferGroup, freezeStatus). Based on the AML/KYC and accreditation process the investor can provision the account address with:

    a) a transfer group designating a regulatory class like "Reg D", "Reg CF" or "Reg S"

    b) the freeze status of that address (with true meaning the account will be frozen from activity)]

  5. The Transfer Admin then must allow transfers between groups with setAllowGroupTransfer(walletsAdminGroup, investorAdminGroup...)

  6. The tokens can then be transferred from the Issuer's wallet to the provisioned addresses.

  7. Transfer Restrictions are detected.

Note that there are no transfers initially authorized between groups. By default no transfers are allowed between groups - all transfer groups are restricted.

Lockup Periods

Lockup periods are enforced via:

  • setAllowGroupTransfer(fromGroup, toGroup, unixTimestamp) allows transfers from one Transfer Group to another after the unixTimestamp. If the unixTimestamp is 0, then no transfer is allowed.

Maximum Number of Holders Allowed

By default Transfer Groups cannot receive token transfers. To receive tokens the issuer gathers AML/KYC information and then calls setAddressPermissions().

A single Holder may have unlimited Wallet addresses. This cannot be altered. The Issuer can only configure the maximum number of Holders allowed (via Transfer Admin) by calling setHolderMax. By default, this limit is set to 2**255-1.

setHolderMax(amount)

Maximum Number of Holders Allowed Per Group

Transfer Admin can configure the maximum number of allowed Holders per group by calling setHolderGroupMax. By default, the holderGroupMax for each group is set to 0, meaning that it won't be applied as a restriction.

Group 0 (the default Holder group) is the only group for which the holder group max variable cannot be applied (an unlimited number of Group 0 Holders are allowed in perpetuity).

setHolderGroupMax(groupID, amount)

Remove holder and wallet from holder

To efficiently remove unused holders and their associated wallets, transfer or wallet admins can call the removeHolder function, which iterates through all linked wallets and removes them. However, for holders with unusually large number of wallets, to avoid reaching block gas limit, it is possible first using batchRemoveWalletFromHolder and then calling removeHolder. If a user does not have ownership of a specific wallet, it can still be removed from the holder's list individually using the removeWalletFromHolder function.

setTransferGroup vs setAddressPermissions

setAddressPermissions is very similar to setTransferGroup, but contains a third argument with frozen status. This status can allow or deny transfers to the provided user.

setAddressPermissions is usually used after KYC/AML verification to activate a particular wallet for transfers. So in cases where you do not need to change the frozen status, you should use setTransferGroup. The frozen status restrictions described in the TransferRules contract.

Timelock Cancellations and Transfers

Cancel Timelock

In the case of cancellations, the transfer restrictions must be enabled between the initial target recipient and the reclaimTo address designated by the canceler.

Timelocks can be configured to be cancelled by a specific canceler address. This canceler can designate a separate reclaim address to receive the locked token portion of the remaining timelock, pending allowed group transfers as described above. The remaining unlocked portion will be transferred directly to the initial target recipient of the original vesting.

Transfer Timelock

For unlocked tokens within a timelock, the initial target recipient can choose to transfer unlocked tokens directly to another recipient. This is a convenience atop the typical transfer method.

In the case of a timelock transfer, the initial target recipient of the timelock must be in a group able to transfer tokens to the new recipient of the tokens. The initial target recipient must also be in a group able to transfer tokens to the new recipient.

Example Transfer Restrictions

Example: Investors Can Trade With Other Investors In The Same Group (e.g. Reg S)

To allow trading in a group:

  • Call setAddressPermissions(address, transferGroup, freezeStatus) for trader Wallets in the group
  • setAllowGroupTransfer(fromGroupX, toGroupX, groupTimeLock) for Wallets associated with groupIDs (for example, Reg S)
  • A token transfer for an allowed group will succeed if:
    • the timelock conditions have passed
    • the recipient of a token transfer does not result in a total holder count in a given group that exceeds the defined holderGroupMax (if configured, ie holderGroupMax set to > 0)
    • the recipient of a token transfer does not result in a total global holder count that exceeds the defined holderMax

Example: Avoiding Flowback of Reg S "Foreign" Assets

To allow trading between Foreign Reg S account addresses but forbid flow back to US Reg D account addresses until the end of the Reg D lockup period

  • Call setAddressPermissions(address, groupIDForRegS, freezeStatus) to configure settings for Reg S investors
  • Call setAddressPermissions(address, groupIDForRegD, freezeStatus) to configure settings for Reg D investors
  • setAllowGroupTransfer(groupIDForRegS, groupIDForRegS, addressTimelock) allow Reg S trading
  • A token transfer for between allowed groups will succeed if:
    • the addressTimelock time has passed; and
    • the recipient of a token transfer is not frozen (ie freezeStatus is false).

Example: Exchanges Can Register Omnibus Accounts

Centralized exchanges can register custody addresses using the same method as other users. They contact the Issuer to provision accounts and the Transfer Admin or Wallets Admin calls setAddressPermissions() for the exchange account.

When customers of the exchange want to withdraw tokens from the exchange account they must withdraw into an account that the Transfer Admin has provisioned for them with setAddressPermissions().

Talk to a lawyer about when exchange accounts may or may not exceed the maximum number of holders allowed for a token.

Group 0 Transfer Restrictions

In general, it is possible to allow Group 0 transfers. They are configurable in the same way that other transfer restrictions across different groups can be configured. This allowance is required for certain real-world situations. For example, if all tokens are freely tradeable under Reg A+ or a public filing, then Group 0 transfers can be allowed.

Transfers Can Be Paused To Comply With Regulatory Action

If there is a regulatory issue with the token, all transfers may be paused by the Transfer Admin calling pause(). During normal functioning of the contract pause() should never need to be called.

The pause() mechanism has been implemented into the RestrictedLockupToken and RestrictedSwap, and Dividends contracts.

Recovery From A Blockchain Fork

Issuers should have a plan for what to do during a blockchain fork. Often security tokens represent a scarce off chain asset and a fork in the blockchain may present ambiguity about who can claim an off chain asset. For example, if 1 token represents 1 ounce of gold, a fork introduces 2 competing claims for 1 ounce of gold.

In the advent of a blockchain fork, the issuer should do something like the following:

  • have a clear and previously defined way of signaling which branch of the blockchain is valid
  • signal which branch is the system of record at the time of the fork
  • call pause() on the invalid fork (Transfer Admin)
  • use burn() and mint() to fix errors that have been agreed to by both parties involved or ruled by a court in the issuers jurisdiction (Reserve Admin)

Law Enforcement Recovery of Stolen Assets

In the case of stolen assets with sufficient legal reason to be returned to their owner, the issuer can call freeze() (Wallets Admin, Transfer Admin), burn(), and mint() (Reserve Admin) to transfer the assets to the appropriate account.

Although this is not in the spirit of a cryptocurrency, it is available as a response to requirements that some regulators impose on blockchain security token projects.

Asset Recovery In The Case of Lost Keys

In the case of lost keys with sufficient legal reason to be returned to their owner, the issuer can call freeze(), burn(), and mint() to transfer the assets to the appropriate account. This opens the issuer up to potential cases of fraud. Handle with care.

Once again, although this is not in the spirit of a cryptocurrency, it is available as a response to requirements that some regulators impose on blockchain security token projects.

Swap

Swap functionality is described in RestrictedSwap.sol.

RestrictedSwap provides a secure means of swapping tokens between known holders of the primary Restricted token and any payment ERC-20 tokens (ie USDC, DAI, etc).

Note: Swap is not intended between two Restricted tokens. Rather, it is intended as a purchase of Restricted tokens using ERC-20 tokens (AKA payment token or quote token). This is enforced in the swap contract itself, by preventing ERC-1404 compatible tokens (checked via ERC-165 interface support) from being used as payment. However, other types of Restricted tokens may not explicitly support the ERC-1404 interface and thus cannot be checked programatically; therefore, this functionality should be used with caution and payment token types should always be verified first.

How It Works

As a prerequisite, users of the swap functionality are assumed to have passed any necessary off-chain AML/KYC and deemed valid holders. Contracts are also assumed to have been configured properly with admin-granted roles and transfer restrictions in place. In particular, transfers must be allowed between the groups of Seller (of Restricted token) and Buyer.

Configuring a Purchase of Restricted Token

As a holder (Buyer) of an ERC-20 payment token (ie USDC, DAI, etc), one can configure a purchase order for a specified amount of Restricted token with a known party (Seller). Here is an example involving USDC:

  1. Buyer must know in advance specifically how much Restricted token they'd like to receive, how much USDC they are willing to pay, and the Seller on the other end.
  2. Buyer must approve the Swap contract itself to handle their USDC in the purchase amount required.
  3. Buyer then configures an open purchase order by calling configureBuy with the following parameters. A Swap ID is emitted in an event.
    • amount of Restricted token desired
    • address of Seller
    • amount of payment token (USDC) willing to swap
    • address of payment token contract
  4. Seller must approve the Swap contract itself to handle their Restricted token in the sell amount required by the configured swap.
  5. Seller can complete this order by calling completeSwapWithRestrictedToken with the emitted Swap ID.

When transfer restrictions are validated between Buyer and Seller, the swap is completed and assets are actually transferred between transacting parties.

Configuring a Sale of Restricted Token

As a holder of the Restricted token, one can also configure a sell order for a specified amount of desired payment ERC-20 token. It is extremely similar to the example above, except terms of the sale must be specified in advance. Here is an example involving USDC:

  1. Seller must know in advance specifically how much Restricted token they'd like to sell, how much USDC they require, and the Buyer on the other end.
  2. Seller must approve the Swap contract itself to handle their Restricted token in the sell amount desired.
  3. Seller then configures an open sell order by calling configureSell with the following parameters. A Swap ID is emitted in an event.
    • amount of Restricted token to sell
    • address of Buyer
    • amount of payment token (USDC) required
    • address of payment token contract
  4. Buyer must approve the Swap contract itself to handle their USDC in the amount specified by the configured swap.
  5. Buyer can complete this order by calling completeSwapWithQuoteToken with the emitted Swap ID.

When transfer restrictions are validated between Buyer and Seller, the swap is completed and assets are actually transferred between transacting parties.

Lockup

A "vesting" smart contract that can implement token lockup with scheduled release and distribution:

  • Can enforce a scheduled release of tokens (e.g. investment lockups)
  • Smart contract enforced lockup schedules are used to control the circulating supply and can be an important part of tokenomics.
  • Some lockups are cancelable - such as employee vestings. When canceled, unlocked tokens remain in the recipients account address and locked tokens are returned to an address specified by the administrator that has an appropriate transfer group to receive the tokens.

Note that tokens in lockups cannot be burned by admins to avoid significant complexity. In order to burn those tokens, first cancelTimelock so they are removed from the timelock, and then burn them.

superBalanceOf

There are 3 classes of token types: simple tokens, unlocked tokens, and locked tokens. Locked and unlocked tokens are tokens supplied to the user via either fundReleaseSchedule or mintReleaseSchedule, but still evaluated within the timelock.

Unlocked tokens become removed from the timelock once they are transferred, and then are converted into simple tokens. A user's full balance of tokens consists of the sum of their simple, unlocked, and locked tokens. Cancelling a timelock also converts the unlocked tokens into simple tokens that become burnable.

Convenience Balance Methods

  • unlockedBalanceOf: tokens that are ONLY supplied via fundReleaseSchedule or mintReleaseSchedule that have been unlocked but not yet transferred out (ie not yet "removed" from the timelock). Includes unlocked tokens across all timelocks.
  • superBalanceOf: simple tokens belonging to the wallet. Does not include locked or unlocked tokens still within timelocks.
  • unlockedTotalBalanceOf: the sum of unlockedBalanceOf and superBalanceOf, ie the total amount of tokens available to the wallet to transfer. Includes unlocked tokens across all timelocks.
  • lockedBalanceOf: tokens that are ONLY supplied via fundReleaseSchedule or mintReleaseSchedule that are still locked. Includes unlocked tokens across all timelocks.
  • balanceOf: the sum of unlockedBalanceOf, lockedBalanceOf, and superBalanceOf. The total balance belonging to the wallet. Not all of this balance is tradeable though, as this includes locked tokens too.
  • lockedBalanceOfTimelock: locked balance for a wallet within a specific timelock.
  • unlockedBalanceOfTimelock: unlocked balance for a wallet within a specific timelock.

fundReleaseSchedule vs mintReleaseSchedule

Lockups, also referred to as token release schedules, are distinguished between funded and minted types. Funded release schedules are done using already-minted tokens that are owned by any admin. These are akin to a type of token transfer and thus must adhere to transfer restrictions.

Release schedules can also be minted directly to recipients by the Reserve Admin. In this case, as it is akin to token minting, it does not have to adhere to transfer restrictions, and is purely under the discretion of the Reserve Admin.

This is described in RestrictedLockupToken.sol.

Dividends

Dividends functionality (Dividends.sol) provides the administrators of the Primary security token the ability to make dividend distributions at certain points in time. RestrictedLockupToken.sol must be deployed with snapshotsEnabled feature, which makes each balance change recorded as a checkpoint. A checkpoint includes absolute balance value and block number.

All dividends distributions/payments are made to recipients on the basis of their proportional ownership of the Primary security token at the time of each snapshot. Dividends are funded for specific snapshots which are represented by block number.

For example, assume at snapshot (1) there are two Primary security token holders, a) one with 40% and the other b) with 60% of token supply. If a dividend is funded for snapshot (1) for 100 USDC, a) will be entitled to 40 USDC and b) will be entitled to 60 USDC.

Transfer Admins on the Dividends.sol contract can fund dividends by invoking the fundDividend() method.

The recipients must proactively claim their dividend from a specific snapshot (block number) by utilizing the claimDividend() and batchClaimDividend() methods. Any number of snapshots are allowed, and dividends are funded for specific snapshots (block numbers).

Any standard ERC-20 tokens are supported for dividend payment (ie USDC, USDT, etc.). However, tokens that capture a fee on each transaction are not supported (see contracts/mocks/ERC20TxFeeMock.sol for an example of an unsupported ERC-20 token).

The snapshot mechanism uses similar to the ERC-20 extension provided by OpenZeppelin/ERC20Votes. So Snapshots.sol utilizes logic and tracking of timepoints but removes delegation part.

See below for the Dividends payment distribution and claim flow utilizing USDC.

  1. Transfer Admin should first approve the Dividends contract to manage the necessary ERC-20 tokens for funding.

  2. Transfer Admin can fund the dividend using a payment token of their choice. This example uses USDC. Note that this is Transfer Admin on the Dividends.sol contract. Each contract has its own set of admins. The dividend must be funded for a specific snapshotId (block number).

  3. Transfer Admin wallet must hold the payment token in order to fund the dividend. The payment token is extracted and sent to the Dividends.sol contract upon successful funding.

  4. Recipient is free to claim the dividend by invoking claimDividend from the Dividends.sol contract.

  5. Amount of entitled dividend token is transferred from the Dividends.sol contract to the rightful recipient.

See Dividends Distribution Calculations for details on methodology.

Relevant Methods

From RestrictedLockupToken.sol: Must be deployed with snapshotsEnabled feature.

From Dividends.sol:

  • fundDividend(address token, uint256 amount, uint256 snapshotId): can only be invoked by the Transfer Admin on the Dividends.sol contract.
    • token: the address of the payment token.
    • amount: the amount of payment token to be disbursed in the funded dividends snapshot.
    • snapshotId: block number of the snapshot to be funded.
  • claimDividend(address token, uint256 snapshotId)
    • token: the address of the payment token.
    • snapshotId: block number of the dividends snapshot to be claimed.
  • batchClaimDividend(address token, uint256[] calldata snapshotIds): allows claiming dividends across multiple snapshots for a given recipient.
    • token: the address of the payment token.
    • snapshotId: block number of the dividends snapshot to be claimed.

Access Control

To decreasing the contract size we provide an optimized version of Access Control. This is similar to the linux file permission bitmask exposed in the chmod command line function.

Our implementation uses binary bitmask determine the access control roles for an address. This optimizes the gas cost and the size of the smart contract code itself.

This is described in EasyAccessControl.sol.

How it works

We use a uint8 binary representation of a number, such as 01010101 to represent the roles IDs within the access controls.

Roles are defined by a specific bit position in the bit storage representation.

As example decimal 1 is 00000001 in binary mode, 2 is 00000010, 3 is 00000011, 4 is 00000100, 7 is 00000111 etc.

We describe the roles in use as:

uint8 constant CONTRACT_ADMIN_ROLE = 1; // 0001
uint8 constant RESERVE_ADMIN_ROLE = 2; // 0010
uint8 constant WALLETS_ADMIN_ROLE = 4; // 0100
uint8 constant TRANSFER_ADMIN_ROLE = 8; // 1000

If you want to use the unused bits in the future to add new roles you can add something like

uint8 constant NEW_ROLE = 16; // 000010000
uint8 constant SECOND_ROLE = 32; // 000100000
...etc

You can grant multiple roles by adding the role number values together to get the correct bitmask representation like this:

uint8 constant WALLET_AND_TRANSFER_ADMIN_ROLE = 12; // 0001100

or

uint8 constant WALLET_AND_TRANSFER_ADMIN_ROLE = WALLETS_ADMIN_ROLE | TRANSFER_ADMIN_ROLE; // 0001100

For manipulating binary numbers you can use binary operators *&, | and ^.

Example:

uint8 constant CONTRACT_ADMIN_ROLE = 1; // 0001
uint8 constant RESERVE_ADMIN_ROLE = 2; // 0010
uint8 constant WALLETS_ADMIN_ROLE = 4; // 0100
uint8 constant TRANSFER_ADMIN_ROLE = 8; // 1000

WALLETS_ADMIN_ROLE | TRANSFER_ADMIN_ROLE == 1100 // adding of bits, granting multiple roles

AnyNumber & WALLETS_ADMIN_ROLE > 0 // checking if AnyNumber contains 0100 bit, it can be used for checking the role

The contract implements simple methods to manipulate Access Controls and check the roles. Note that granting new and revoking existing roles must be done in separate transactions.

Batched functions also allow for multiple roles to be granted or revoked in a single transaction.

 function batchGrantRoles(address[] calldata addresses, uint8[] calldata roles) public onlyContractAdmin

function grantRole(address addr, uint8 role) public validRole(role) validAddress(addr) onlyContractAdmin

function batchRevokeRoles(address[] calldata addresses, uint8[] calldata roles) public onlyContractAdmin

function revokeRole(address addr, uint8 role) public validRole(role) validAddress(addr) onlyContractAdmin

function hasRole(address addr, uint8 role) public view validRole(role) validAddress(addr) returns (bool)

Appendix

Roles Matrix

Admin permissions are defined with the following binary values. Roles are defined as the OR of a set of admin roles:

Contract Admin: 0001 Reserve Admin: 0010 Wallets Admin: 0100 Transfer Admin: 1000

Role IntegerAdmin RolesBit Mask Representation
0None (Default)0000
1Contract Admin0001
2Reserve Admin0010
3Contract Admin + Reserve Admin0011
4Wallets Admin0100
5Contract Admin + Wallets Admin0101
6Reserve Admin + Wallets Admin0110
7Contract Admin + Reserve Admin + Wallets Admin0111
8Transfer Admin1000
9Contract Admin + Transfer Admin1001
10Reserve Admin + Transfer Admin1010
11Contract Admin + Reserve Admin + Transfer Admin1011
12Wallets Admin + Transfer Admin1100
13Contract Admin + Wallets Admin + Transfer Admin1101
14Reserve Admin + Wallets Admin + Transfer Admin1110
15All Roles (Contract, Reserve, Wallets, Transfer)1111

Post-Deployment Configuration

After smart contract deployment, there are certain configurations to complete before token issuance and trading can occur smoothly.

  1. Grant Transfer Admin Role

    Although Transfer Admin is a required deployment parameter for the Dividends contract, it still must be specifically set in the Token contract separately, by the Contract Admin.

    This is important so that an admin exists which can configure group transfers.

  2. Allow Group Transfers

    The Transfer Admin can then allow group transfers, for example between all traders within Group 1. This will allow transfers to occur between all traders placed in Group 1.

    This is important so that transfers of tokens are enabled between designated groups.

  3. Whitelist Funder [optional]

    The Transfer Admin can then set the group of the admin funder address, so that fundReleaseSchedule can be invoked. Note that Reserve Admin can mintReleaseSchedule to any recipient, regardless of group transfer restrictions. However, funding release schedules via fundReleaseSchedule, for tokens that have already been minted, must adhere to transfer restrictions between the funding admin and timelock recipient.

Meta Transactions

Meta Transactions are enabled for RestrictedLockupToken.sol. Transactions can be signed off-chain, and then a third party (the relayer) can pay the transaction fees on behalf of the user. This greatly simplifies the user experience, and also allows batching of multiple transactions natively via the forwarder contract. In particular, this simplifies the wallet whitelisting process by allowing the relayer to process multiple transactions on behalf of the Transfer Admin.

A custom ERC2771 forwarder contract has been created to allow for unique, but non-sequential nonce management. The forwarder is based on OpenZeppelin's ERC2771Forwarder.sol contract, except with custom nonce management. This ensures replay protection while also allowing multiple nonces to be utilized within the same batch of transactions without the need to order them.

See contracts/metatx/ERC2771CustomForwarder.sol and contracts/utils/Nonces.sol for more details.

Here is an example flow:

  1. The EIP-712 format is used for off-chain signing. The domain specifies the context of the signing, including the contract name, version, chain ID, and verifying contract address (which is the address of the ERC2771 Forwarder). The typed structured data consists of the fields: from (tx signer), to (target token contract), value (amount of coin provided), gas, nonce (unique but not sequential), deadline (timestamp deadline for expiration), and data.

  2. The Relayer (any third party payer wallet) must then be provided that signed transaction.

  3. The Relayer then executes the meta transaction on behalf of the Transfer Admin signer by calling execute or executeBatch on the ERC2771Forwarder contract with the signed transaction.

  4. The forwarder contract will forward the transaction to the target RestrictedLockupToken contract to execute the whitelisting transaction.

Dividends Distribution Calculations

This explains the process of dividend distribution via Solidity, ensuring that the total dividend amount DD is fully distributed among token users when all claims have been made, without leaving any dust (small remaining amounts) trapped within the smart contract.

This is achieved by restricting the amount of fundable dividend to be divisible by the total supply of Security Token, in base units. This ensures that every base unit of Security Token is guaranteed whole units of shares of dividends.

Notes

  • only full claiming of dividends is allowed. A recipient for example cannot claim only 50% of their entitled dividends for a given snapshot. However, if there are multiple dividends funded for a given snapshot, recipients can claim between funding rounds.

  • batch claiming dividends is only allowed across multiple snapshots for one recipient for the same dividend payment token (ie USDC).

  • ONLY dividend tokens with a number of decimals greater than or equal to the number of decimals of the Restricted Lockup Token are allowed. This is to bound the minimal funding amount required.

    For example, consider if the lockup token had a decimals value of 18, and the dividend token had decimals value of 6. Ensuring that every base unit of lockup token had at least one share of dividend token would mean the lower bound is: 101810^{-18} of lockup token yields at least 10610^{-6} of dividend token. Implicitly this means that 11 full unit of lockup token yields 101210^{12} dividend tokens. In the case of typical stablecoins, this means a dividend payout of $1T per security token balance is required for divisibility, which is unfeasible.

Variable Definitions

  • DD: Total dividend amount.
  • ii: Index representing the current funding round.
  • SS: Total supply of Security Tokens at a given snapshot.
  • CRCR: Current Funding Round.
  • DPTDPT: Dividend per Security Token.
  • cDPTcDPT: Cumulative Dividend Per Token (cumulativeDPT).
  • TCTC: Total Claimed (totalClaimed).
  • NN: Total number of users.
  • jj: Index representing the current user in iteration.
  • RR: Number of funding rounds.
  • TjT_j: Total entitled dividend for user jj.
  • UjU_j: Unclaimed dividend for user jj.
  • CjC_j: Total claimed amount by user jj.
  • FjF_j: Floor value of the dividend for user jj.
  • LCRjLCR_j: Last claimed round for jj-th user.
  • BjB_j: Token balance of user jj.

Dividend Distribution Process

Ensure that:

D%S=0D \text{\%} S = 0

Multiple Funding Rounds

For multiple funding rounds per snapshot, total claimable Dividends per Security Token are added together. Remaining claimable amounts are derived by finding the total claimable portion and subtracting the already-claimed amount.

Steps

  1. Calculate the total Dividends per Security Token for each funding round:

    DPTi=DiS\text{DPT}_i = \lfloor\frac{D_i}{S}\rfloor

    where ii is the index representing the current funding round.

  2. Sum the Dividends per Security Token for all funding rounds:

    cDPT=i=1RDPTi\text{cDPT} = \sum_{i=1}^{R} \text{DPT}_i

    where RR is the total number of funding rounds.

  3. Calculate the total entitled dividend for each user jj:

    Tj=cDPTBjT_j = \text{cDPT} \cdot B_j

    where BjB_j is the token balance of user jj.

  4. Calculate the remaining unclaimed dividend for each user jj at funding round ii:

    Cij=DPTiBjC_{ij} = \text{DPT}_i \cdot B_j

    where CjC_j is the total claimed amount by user jj if there is intermediate claiming between funding rounds.

    Uj=TjCjU_j = T_j - C_j

  5. Due to the enforcement of exactly divisible dividends during the funding process, there should be no remaining tokens left after all users have claimed.

Troubleshooting

To enable transfers between wallets, ensure that:

  • both sender and recipient are placed into desired transfer groups (ie invoking setAddressPermissions or setTransferGroup)
  • these transfer groups have approved transfer restrictions (ie invoking setAllowGroupTransfer)
  • sender has available unlocked tokens to be transferred

Note that balanceOf() method typically used by wallet providers (ie Metamask) will display wallet balance that includes the amount of both locked and unlocked/simple tokens. Only unlocked/simple tokens are transferrable.

External Security

Because snapshots are written continuously and are used to calculate share of dividends awarded to recipients, proportional to token holdings, there is no risk of front-running by malicious holders.