EXCOIN / CASE STUDY 03

An Ethereum contract for crypto-backed loans

A completed, anonymised crypto lending engagement. The study examines the architecture and security of an Ethereum contract without disclosing the client, contract address, assets, amounts or protected implementation.

01 / ENGINEERINGCS · EN · ES
01 / 27

Verified engagement and public technical analysis

EXCOIN completed an engagement involving an Ethereum contract for crypto-backed loans. Contractual limits prevent publication of the client, contract address, exact parameters, assets, volumes or audit report. This page instead explains the safe design space and engineering decisions typical of such a system. It does not disclose production code, and individual patterns should not automatically be attributed to the confidential client.

The business question is how to provide liquidity against digital assets without selling them while making the risks clear to borrower, lender and operator. This study addresses contract design on Ethereum and EVM networks. The technical principles are general; they neither reveal nor substantiate the confidential client's exact implementation.

02 / 27

Roles, economic promises and contract boundaries

Before Solidity, define borrower, lender or pool, parameter administrator, price source, liquidator and interface operator. Each role needs an exact set of actions. The commercial agreement determines when the loan begins, the repayment currency, fees and default. Code can automate only rules expressible and verifiable with available on-chain information.

The contract should not pretend to settle off-chain ownership, customer identity or legal enforcement. Those matters need contracts and operations outside the chain. The architecture spells out the relationship among interface, signed transaction, contract, indexer, oracle and any off-chain claim register. Without this boundary, the product creates a dangerous illusion that the contract alone governs everything.

03 / 27

Loan model and state machine

Request, offer, posted collateral, drawn principal, accrued interest, repayment and collateral release are distinct states. Allowed transitions enforce invariants: collateral is not released before full settlement, principal is not paid twice, a cancelled offer cannot be accepted and liquidation cannot continue after final repayment. Both emitted events and stored state must allow an operator to reconstruct the sequence.

Partial repayment needs an allocation order among fees, interest and principal. Integer arithmetic must handle rounding and dust; decimal values in the interface cannot obscure on-chain units. Variable interest adds control over who may change a parameter and when it takes effect. Block timestamps are useful but not a perfect clock, so time-dependent rules need explicit tolerances.

04 / 27

Assets, tokens and units

The contract must know which tokens can serve as collateral and which fund the loan. An ERC-20 interface does not guarantee conventional behaviour: a token may charge transfer fees, restrict addresses, rebase balances or return unusual values. Asset admission therefore needs an allowlist, tests against the actual implementation and a rule for received-versus-requested amounts. Sending an unknown token must not make it eligible collateral.

Each asset's precision and each feed's decimals come from the real source. Collateral value is computed in one defined accounting unit, with conservative operation order so rounding cannot inflate borrowing power. Nominal balance and economically available value remain distinct. A stablecoin can lose its peg and cannot be treated as a risk-free dollar merely because of its name.

05 / 27

Collateral and loan-to-value

Initial maximum LTV, warning threshold and liquidation threshold are separate parameters. Their values depend on asset volatility, market liquidity and liquidation mechanism; no client numbers are disclosed here. Adding, withdrawing or replacing collateral is permitted only if the resulting position satisfies the approved safety invariant.

In a sharp market fall, collateral may not be saleable at the oracle price. The model includes slippage, fees and delay between price observation and execution. The interface distinguishes an informative warning from a condition actually enforced by the contract. Email or push alerts help users, but successful delivery cannot be the sole safety control.

06 / 27

Oracles and price failure

A lending contract should not derive market value from a single easily manipulated spot trade. The oracle policy checks the market represented, decimal precision, age, positivity and outage behaviour. If data is stale or anomalous, the protocol must not blindly permit new borrowing or liquidation. Rules for stale prices belong to the economic specification, not an incident-time improvisation.

A backup feed is not automatically safe: it may differ in precision, price definition or timing. Switching requires a decision rule and a pause for risky actions when sources disagree. Tests include fast markets, stale data, thin liquidity and provider outages. Precision must be checked for the feed actually chosen rather than assumed from a familiar default.

07 / 27

Principal disbursement and operation ordering

Loan drawdown moves value and needs checks before transfer: offer state, collateral, fresh price, principal limit, caller authorisation and available liquidity. Contract state must be updated safely around external token calls so re-entry or repeated calls cannot pay twice. A duplicate request either fails predictably or returns an already recorded result.

A transaction can sit in the mempool, be included, be reorganised or become sufficiently confirmed under the network policy. Off-chain services cannot tell a user that a drawdown is final merely because a wallet submitted a signature. They track transaction hash, network and confirmations. A UI error must not trigger automatic re-signing of an economic action before on-chain state is checked.

08 / 27

Repayment, early close and collateral return

Repayment calculates the debt at a defined moment, accepts an authorised asset and allocates it according to agreed rules. Partial repayment reduces debt but does not necessarily unlock collateral. Early settlement needs clear interest and fee treatment, while an overpayment requires an explicit return path instead of disappearing in rounding.

After full settlement, a borrower withdraws collateral or the contract returns it according to the design. External transfer failure must not permanently trap the loan in an inconsistent state. An event and stored state record amount and recipient. Lost-key recovery is a product and legal question: a contract cannot independently determine who is the rightful replacement owner of a wallet.

09 / 27

Liquidation and protection of both sides

Liquidation is more than a numeric comparison. The design defines who may trigger it, how price is checked, how much collateral can be sold, debt settlement, treatment of surplus and shortfall. Excessively aggressive liquidation harms the borrower; a slow path can leave the lender uncovered. Partial liquidation, auction and other models each require adverse-market testing.

Simulations cover price gaps, zero liquidity, high gas, front-running and oracle outages. Each should show whether invariants hold and what losses are possible. An emergency pause specifies which functions stop and whether repayment and safe withdrawal remain possible. A switch that freezes every user protection can create a new systemic risk.

10 / 27

Access rights, upgrades and parameter governance

Privileges for risk parameters, pause, upgrades and fee withdrawal are separated. Key holders, rotation and compromise response matter as much as Solidity. Multisignature control, time delays and visible change proposals may be appropriate. The right to replace a feed must not implicitly include the right to move collateral.

Upgradeable contracts permit repair but also allow economic rules to change after a loan begins. Decide whether changes affect only new loans or existing ones. Immutable contracts need a migration and closure path; upgradeable ones need approval, notice, storage compatibility checks, independent review and a rollback plan where technically possible.

11 / 27

Security review and test matrix

Tests cover reentrancy, unauthorised drawdown, double repayment, rounding errors, nonstandard tokens, stale oracle, price manipulation and races between repayment and liquidation. Invariant and fuzz tests check properties over many action sequences, not just happy paths. An independent review is another layer but cannot guarantee a contract has no defects.

The test environment should match real token, feed and network versions. Fork tests expose differences from mocks; economic simulations stress liquidation. Each audit finding needs severity, fix, retest and residual-risk decision. Because the report for this confidential engagement is not public, we do not claim a specific third-party audit or certification.

12 / 27

Indexing, operations and incidents

An indexer consumes on-chain events to build fast loan views. It processes events idempotently and can roll back a chain reorganisation. The contract remains the source of truth for financial state; the database may lag and must show its last confirmed block. Monitoring covers prices, feed age, RPC health, pending transactions, at-risk positions and index-chain discrepancies.

Incident response distinguishes UI bugs, RPC outages, compromised administrator keys, bad prices and contract exploits. A pause has activation and release conditions and named key holders. User communication cannot claim funds are safe before verification. Backing up off-chain data is not equivalent to recovering on-chain assets; both recovery responsibilities must be assigned.

13 / 27

Loan agreement and on-chain state

The user agreement and contract must describe the same economic events in different language. Both define principal, maturity, interest, collateral, liquidation and oracle outage. A clause-to-state map identifies on-chain conditions, off-chain evidence and owner. A rule that cannot be automated has an explicit manual process rather than a hidden gap.

Before signing, borrowers see the parameters the contract will store, not just a marketing summary. A signature does not always mean immediate drawdown or final collateral lock. The interface shows each transition and cancellation options. Qualified client counsel assesses enforceability and consumer information; engineers supply exact data and audit links.

14 / 27

Lender funding and liquidity

Offered liquidity and funds actually available to pay are distinct. If a lender may withdraw, a cancelled offer cannot be accepted. A pool needs share accounting, reserves, withdrawal priority and loss allocation. The product cannot promise instant disbursement when capital is still moving or awaiting confirmation.

Tests include two borrowers competing for the last funds, a failed token transfer and lender withdrawal during liquidation. Contract balance, recorded obligations and available liquidity must satisfy a defined invariant. A mismatch is a safety incident rather than merely a dashboard error.

15 / 27

Interest mathematics and time

Interest may be simple, compounded or follow a contracted formula. Every choice defines time unit, precision, rounding and treatment of partial periods. Solidity's integer arithmetic means multiplication and division order matter. An independent reference calculation helps testing but cannot replace contract state as the actual outcome.

Tests cover just before maturity, the boundary itself, after maturity, long duration and repeated partial payments. A rate change states whether it reprices existing debt or only a future interval. If an administrator can set rates, the agreement must describe that power and the borrower must be able to discover changes before further borrowing.

16 / 27

Token intake and unusual behaviour

Receiving a token is not merely calling transferFrom. Some ERC-20 assets have transfer fees, blacklists, rebasing or unusual return values. The contract compares balances where appropriate, while an allowlist restricts assets to reviewed implementations. Different token decimals can radically change collateral calculations.

Approval permits future spending but does not move funds immediately. The interface should request a reasonable allowance, explain the spender and support revocation. A new token version needs tests across deposit, drawdown, repayment, surplus return and liquidation.

17 / 27

Risk parameters and market stress

No single collateral ratio works for every token. Depth, concentration, volatility, oracle availability and liquidation speed all matter. Parameters are approved with a hypothesis and simulation. A deteriorating market cannot be evaluated solely from historical price volatility.

Scenarios include overnight gaps, mass liquidation, stablecoin depeg, high gas and a major venue outage. The result is a range of possible losses and conditions for stopping new loans, not a promotional safety number. Existing positions need a policy on retroactive threshold changes.

18 / 27

Liquidator incentives and auctions

Liquidators need enough incentive to pay gas and market risk. Excessive bonuses harm borrowers; insufficient rewards can leave debt uncovered. The contract computes sale limits, price, bonus and remaining collateral explicitly. Partial liquidation is checked to ensure the position improves.

Auctions can discover price but add time and attack surface. Rules cover start, end, bidding, cancellation and no-buyer outcomes. Tests include MEV, front-running and competing liquidators. Sending a liquidation transaction is not proof the lender received sufficient value.

19 / 27

Oracle fallback and emergency mode

A primary feed is checked for round, timestamp, positive value and units. Stale data stops borrowing and risky liquidation according to an agreed rule. A backup can represent a different market or precision, so switching needs deviation checks and controlled permission. One key able to replace feed and liquidation threshold instantly is concentrated risk.

Emergency mode restricts new loans while preserving safe repayment where possible. Tests simulate oracle failure at maturity and during a price crash. The team knows who activates the mode, what evidence permits release and how participants are informed. Any manual price is a highly privileged exception.

20 / 27

Upgrades and existing loans

An upgrade can fix a bug but also alter economics after a loan begins. Decide whether new code governs only new positions or must preserve original terms. Storage layout, permissions and migration transactions are tested against realistic historical states.

Review, approval, notice and failure planning precede upgrade. Rollback may be impossible after economic transactions. Tests cover repayment and liquidation of open positions across versions, not only bytecode and storage. A transparent process reduces the trust users must place in administrators.

21 / 27

Signatures, wallets and user protection

Token approval, collateral deposit, loan acceptance and repayment are different signatures. The interface checks chain ID and contract address. Off-chain offers carry nonce and expiry so an old signature cannot be reused after terms change.

Lost wallets and compromised keys are operating scenarios. Collateral recovery cannot be promised without a secure and legally approved route. Support must not gain blanket power to transfer customer value merely to simplify recovery. Critical facts appear before signing and remain available afterward.

22 / 27

Events and off-chain index

The contract emits events for opening, drawing, collateral change, repayment, liquidation and closure. Events provide history but may not fully represent current state; an indexer also reads contract storage. Block, transaction hash and log order form the key. Reorganisations require rollback and replay.

The operator view shows the last confirmed block and lag. If the indexer falls behind, the UI labels stale data and stops risky actions dependent on projections. The contract remains the financial source of truth. Rebuilding the database from chain history and checkpoints must be rehearsed.

23 / 27

Audit evidence and reproducible builds

Verified source, compiler version, optimizer settings, libraries and dependency addresses form a reproducible artefact. Without these, a repository cannot prove it matches deployed bytecode. Release records hashes, approvals and deployment parameters. A proxy or implementation change is another auditable event.

Audit documentation lists economic invariants, trust boundaries, known exceptions and residual risk. A public claim of an external audit requires an actual report and permission; we make no such claim for this confidential engagement. Internal incident response should reconstruct contract version, price, administrator action and position at a given block.

24 / 27

Network load and transaction cost

Gas can make small loans uneconomic or prevent timely collateral top-ups. The design measures cost for deposit, drawdown, repayment and liquidation under realistic conditions. Batching can save fees but adds complexity and correlated failure. Network or L2 choice considers asset, oracle and user availability plus withdrawal paths.

During high fees a position may become liquidatable before a top-up lands. The product cannot promise a fixed confirmation time the network cannot deliver. Monitoring tracks pending transactions and execution prices. Operators may safely replace their own transaction under a runbook but cannot sign an economic action for users without authority.

25 / 27

Economic attacks and misaligned incentives

Attackers need not exploit Solidity. They can manipulate thin markets, exploit short price moves, create many small positions or farm liquidation bonuses. Threat modelling includes economic behaviour, MEV and coordinated transactions. Simulations compare attacker gains with costs and find dangerous parameter regions.

Legitimate incentives can also be wrong. A lender might benefit from default, or a liquidator from worsening price. Correct code can then produce poor outcomes. Product and security teams assess the full mechanism, including fees and treatment of leftover collateral.

26 / 27

Handover and long-term ownership

Handover includes addresses, ABIs, verified source, compiler, invariant tests, parameters, role holders, runbooks and incident process. A new team must be able to pause a risky function and assess open positions safely. After launch someone must monitor feeds, network, tokens and permissions.

Each new collateral asset or loan type gets fresh economic and security review. Operating metrics track feed age, at-risk positions, failed repayments and unresolved liquidations rather than only transaction count. Confidentiality prevents publishing client values, but the study provides questions a comparable system must answer.

27 / 27

Legal review and future development

Lending, custody, conversion and platform operation may receive different legal treatment by jurisdiction and role. MiCA and other rules cannot be settled in a marketing paragraph. Qualified counsel must assess the product, agreements, identity checks, consumer protection, tax and disputes. Technical deployment neither grants a licence nor creates legal enforceability.

Further versions may add collateral types, rates or lenders, but each reopens questions about economic design, oracle quality, liquidity and security. Clear module boundaries allow evolution without disguising new risks. The value of the study is the ability to explain each economic event, its on-chain evidence and the owner of each exception, rather than an unsupported claim about scale.

General technical references

These links explain general principles. They do not document the client's confidential implementation.

Discuss a project