Voltar para Documentação

Docs Técnicas

Standard Library

TREA ships built-in modules under the std namespace, grouped by product domain. They are published on-chain as part of the platform bootstrap and are available to every contract without any separate deployment step.

O conteúdo abaixo vem das fontes técnicas do repositório e é prerenderizado no site para leitura direta por pessoas, crawlers e agentes.

TREA ships built-in modules under the std namespace, grouped by product domain. They are published on-chain as part of the platform bootstrap and are available to every contract without any separate deployment step.

Import them by canonical path:

python
# Token foundations
import std.token.BasicToken
import std.token.Pausable

# Access control
import std.access.Ownable
import std.access.Roles

# Credit and settlement templates
import std.credit.LoanContract
import std.credit.TradeSettlement
import std.credit.ReceivableContract
import std.credit.TermLoan
import std.credit.RevolvingCredit

# Real-world asset templates
import std.rwa.RwaVault
import std.rwa.RwaToken
import std.rwa.RwaFund

# Oracle
import std.oracle.PriceFeed

# Asset and authorization contracts
import std.asset.FungibleAsset
import std.asset.UniqueAsset
import std.asset.CustodyVault
import std.asset.EscrowAgreement
import std.asset.DelegationPolicy
import std.asset.SpendingVault
import std.asset.AuthorizedSpendingVault
import std.asset.CreditCardVault

# On-demand product factory
import std.factory.ProductTemplate

Current catalog:

| Path | Purpose | |------|---------| | std.token.BasicToken | Simple token foundation | | std.token.Pausable | Pause switch for composed contracts | | std.access.Ownable | Single-owner access control | | std.access.Roles | Single-admin operational role | | std.credit.LoanContract | Basic loan lifecycle | | std.credit.TradeSettlement | Bilateral settlement template | | std.credit.ReceivableContract | Receivable lifecycle | | std.credit.TermLoan | Fixed-term loan product | | std.credit.RevolvingCredit | Credit limit with draw/repay cycle | | std.oracle.PriceFeed | Push-based price feed | | std.rwa.RwaVault | Legal transfer and redemption of RWA | | std.rwa.RwaToken | Token backed by a registered RWA | | std.rwa.RwaFund | Pooled RWA fund | | std.asset.FungibleAsset | Balance[Asset]-based fungible asset | | std.asset.UniqueAsset | Claim[Asset]-based unique claim | | std.asset.CustodyVault | Custody and reserve proof | | std.asset.EscrowAgreement | Escrow lifecycle | | std.asset.DelegationPolicy | Decremental delegated spending | | std.asset.SpendingVault | Deposited card-style spending vault | | std.asset.AuthorizedSpendingVault | Direct authorized spending vault | | std.asset.CreditCardVault | Issuer-funded credit card vault | | std.factory.ProductTemplate | On-demand child contract factory |

`std.token.BasicToken`

Fungible token foundation. Tracks total supply and exposes an unprotected mint entry point that child contracts are expected to override.

Inherited storage

| Field | Type | Default | |-------|------|---------| | total | u128 | 0 |

Functions

python
@view
def total_supply() -> u128

@tx
def mint(amount: u128)
    # require amount > 0
    # self.total += amount
    # No access control — override in child

Typical override pattern

python
@tx
override def mint(amount: u128):
    require(ctx.caller == self.owner, "only_owner")
    require(amount > 0, "amount_must_be_positive")
    self.balances[ctx.caller] = self.balances[ctx.caller] + amount
    self.total = self.total + amount

`std.access.Ownable`

Single-owner access control. Initialization is left to the child contract. New contracts should set owner from a @construct entrypoint; the legacy zero-address sentinel is only an internal pre-construction state.

Inherited storage

| Field | Type | Default | |-------|------|---------| | owner | Address | internal pre-construction sentinel |

Functions

python
@view
def get_owner() -> Address

@view
def is_owner(account: Address) -> bool

@tx
def transfer_ownership(new_owner: Address)
    # require ctx.caller == self.owner
    # self.owner = new_owner

Construction pattern

python
@construct
def initialize(initial_owner: Address):
    self.owner = initial_owner

`std.token.Pausable`

Emergency pause switch. pause and unpause are unprotected — child contracts must override them to add access control.

Inherited storage

| Field | Type | Default | |-------|------|---------| | paused | bool | False |

Functions

python
@view
def is_paused() -> bool

@tx
def pause()
    # require self.paused == False
    # self.paused = True
    # No access control — override in child

@tx
def unpause()
    # require self.paused == True
    # self.paused = False
    # No access control — override in child

Typical override pattern

python
@tx
override def pause():
    require(ctx.caller == self.owner, "only_owner")
    super.pause()

@tx
override def unpause():
    require(ctx.caller == self.owner, "only_owner")
    super.unpause()

The super.pause() call delegates to the base implementation, which handles the double-pause guard. The override only needs to add the access check.

`std.access.Roles`

Single-admin role. Semantically similar to Ownable but names the privileged account admin, signalling an operational role rather than economic ownership. Useful for loan servicers, compliance officers, and operator accounts.

Inherited storage

| Field | Type | Default | |-------|------|---------| | admin | Address | internal pre-construction sentinel | | admin_active | bool | False |

Functions

python
@view
def is_admin(account: Address) -> bool

@tx
def grant_admin(new_admin: Address)
    # require self.admin_active == False or ctx.caller == self.admin
    # self.admin = new_admin
    # self.admin_active = True

@tx
def renounce_admin()
    # require ctx.caller == self.admin
    # self.admin_active = False

renounce_admin disables the admin role without writing a zero address. A later bootstrap grant can reactivate the role according to the module policy.

`std.credit.LoanContract`

Full loan lifecycle: origination, accrual, and repayment. Uses the loan_origination, loan_accrual, and loan_repayment operation kinds from the canonical Operation Kind Catalog.

Loan storage

| Field | Type | Default | |-------|------|---------| | lender | Address | internal inactive sentinel | | borrower | Address | internal inactive sentinel | | outstanding | u128 | 0 | | active | bool | False |

Loan entrypoints

python
@tx
def originate(lender: Address, borrower: Address, amount: u128)
    # Sets lender + borrower, marks active=True, records outstanding amount.
    # Emits loan_origination posting lines.

@tx
def accrue(amount: u128)
    # Increases outstanding by amount.
    # Emits loan_accrual posting lines.
    # require active

@tx
def repay(amount: u128)
    # Reduces outstanding by amount.
    # Emits loan_repayment posting lines.
    # require active; require amount <= outstanding

`std.credit.TradeSettlement`

Bilateral trade settlement with propose/cancel/settle lifecycle. Uses the generic operation kind via send for the final transfer.

Settlement storage

| Field | Type | Default | |-------|------|---------| | initiator | Address | internal inactive sentinel | | counterparty | Address | internal inactive sentinel | | amount | u128 | 0 | | pending | bool | False |

Settlement entrypoints

python
@tx
def propose(counterparty: Address, amount: u128)
    # Records trade terms and sets pending=True.
    # require not pending

@tx
def cancel()
    # Clears pending state.
    # require pending; require ctx.caller == self.initiator

@tx
def settle()
    # Executes the transfer via send(self.amount, self.initiator, self.counterparty).
    # Clears pending state.
    # require pending

`std.credit.ReceivableContract`

Accounts-receivable lifecycle: recognize, settle, and write-off. Uses explicit lines_generator with the generic kind for posting effects.

Receivable storage

| Field | Type | Default | |-------|------|---------| | originator | Address | internal inactive sentinel | | debtor | Address | internal inactive sentinel | | outstanding | u128 | 0 | | recognized | bool | False |

Receivable entrypoints

python
@tx
def recognize(originator: Address, debtor: Address, amount: u128)
    # Records the receivable (outstanding=amount, recognized=True).
    # Emits posting lines for receivable recognition.
    # require not recognized

@tx
def settle(amount: u128)
    # Reduces outstanding by amount.
    # Emits posting lines for cash receipt.
    # require recognized; require amount <= outstanding

@tx
def write_off(amount: u128)
    # Reduces outstanding by amount (bad debt).
    # Emits posting lines for write-off.
    # require recognized; require amount <= outstanding

`std.rwa.RwaVault`

Fixed-income RWA vault for issuance, legal transfer, and maturity-gated redemption. Legal metadata such as ISIN, governing law, and custody reference lives in the ledger RWA registry (PublishRwaAsset).

python
@construct
def initialize(issuer: Address, maturity: u128)

@tx
def issue(recipient: Address, amount: u128)

@tx
def transfer_legal(to: Address, amount: u128)

@tx
def redeem(amount: u128)

issue and transfer_legal reject calls after maturity_date; redeem requires maturity.

`std.rwa.RwaToken`

Fungible token backed by a registered real-world asset. It tracks backing value, share supply, holder balances, and returns NAV scaled by 1_000_000.

python
@construct
def initialize(issuer: Address, asset_ref: String)

@tx
def issue(holder: Address, shares: u128, backing_value: u128)

@tx
def redeem(shares: u128)

@view
def nav() -> u128

issue and redeem emit ProductReceipt events and accounting posts for the backing value movement.

`std.rwa.RwaFund`

Pooled vehicle holding multiple RWA ids. Deposits and withdrawals update fund holdings, investor units, and NAV; rebalancing moves exposure between RWA ids.

python
@construct
def initialize(manager: Address)

@tx
def deposit(rwa_id: String, amount: u128, nav_value: u128)

@tx
def withdraw(rwa_id: String, amount: u128, nav_value: u128)

@tx
def rebalance(from_rwa: String, to_rwa: String, amount: u128)

deposit generates a generic double-entry post and a ProductReceipt event, which makes it suitable for pre-deploy dry-runs and audit dashboards.

`std.credit.TermLoan`

Fixed-term loan with origination, partial amortization, explicit outstanding balance, and balanceOf(borrower) compatibility for wallet-style views.

python
@tx
def originate(lender: Address, borrower: Address, amount: u128, rate_ppm: u128, term_end: u128)

@tx
def amortize(amount: u128)

@tx
def accrue_interest(amount: u128)

@view
def balanceOf(account: Address) -> u128

originate, amortize, and accrue_interest use canonical loan.* posting intrinsics and emit ProductReceipt events.

`std.credit.RevolvingCredit`

Reusable credit limit with draw and repayment cycles.

python
@tx
def open(lender: Address, borrower: Address, credit_limit: u128)

@tx
def draw(amount: u128)

@tx
def repay(amount: u128)

@view
def available_credit() -> u128

Draws are posted as loan origination lines; repayments use loan repayment lines. Both emit ProductReceipt events and are safe to simulate before submission.

`std.asset.FungibleAsset`

Generic fungible asset implemented with Balance[Symbol], credit, debit, and amount_of. Unlike legacy BasicToken examples, this module uses native financial balance tracking instead of raw integer maps.

python
@tx
def mint(to: Address, amount: u128)

@tx
def transfer(to: Address, amount: u128)

@tx
def transfer_from(owner: Address, to: Address, amount: u128)

@tx
def burn(amount: u128)

Use it when the value is money-like and should be visible to ledger-aware analysis. Plain u128 remains just a number.

`std.asset.UniqueAsset`

Unique asset / certificate lifecycle based on Claim[Asset]. Claims are non-ABI storage values: contracts expose views and controlled transfers, not raw claim copying.

`std.asset.CustodyVault`

Custody vault that tracks reserve or escrowed positions using Balance[Asset]. It is intended for products where the contract must prove that value is held by the product instance, not by an informal off-chain convention.

`std.asset.EscrowAgreement`

Escrow lifecycle for locked funds and controlled release. The escrow balance is modeled as tracked financial state, which keeps release and refund effects auditable.

`std.asset.DelegationPolicy`

Delegated spending policy separating holder and delegate. Allowances are explicit and decrement on use, avoiding unbounded "approval as informal permission" patterns.

`std.asset.SpendingVault`

Deposited card-style spending vault. A card key signs PaymentIntentV1, while the contract enforces balance, nonce, limits, merchant policy, expiry, and revocation before moving funds.

See Spending Vaults And Card Authorization.

`std.asset.AuthorizedSpendingVault`

Card-style authorization that can spend from an owner path without pre-funding a vault. This is more powerful than SpendingVault and should be surfaced as a direct spending authority in wallet warnings and AI Audit.

`std.asset.CreditCardVault`

Issuer-funded credit card vault. Payments create cardholder debt tracked as Balance[CREDIT]; repayments reduce that outstanding balance. When deployed as a child of ProductTemplate, bind_lineage records parent_template_id, origin_request_id, and approved_terms_hash.

`std.factory.ProductTemplate`

Governed parent contract for on-demand child contracts. It accepts product requests, issuer approvals, deterministic child id derivation, and child binding by artifact/hash allowlist.

See On-Demand Contract Factory.

Composing Multiple Modules

Modules compose without conflict as long as they do not declare the same storage field:

python
import std.token.BasicToken
import std.access.Ownable
import std.token.Pausable

contract PausableToken impl BasicToken, Ownable, Pausable:
    # Flattened storage: total, owner, paused, + child fields

BasicToken + Ownable + Pausable is the canonical triple for regulated tokens. See Institution Token and Pausable Institution Token for complete examples.