A Trustless Local Exchange Trading System

Translation temporarily unavailable. Showing original English.
Amitabh Saxena

29 de mayo de 2019

A Local Exchange Trading System (LETS) is aimed at developing local economy and is usually used by people of a locality in the vicinity of each other. For a brief overview of LETS see this link, which also describes an ErgoScript implementation of a committee managed LETS. We call such a system a managed or permissioned, since it depends on a committee of trusted members to enroll new members into the LETS.
Here we describe a trustless LETS, i.e., one where there is no management committee needed for enrolment.

Overview

LETS involves several parties that agree to use some form of "local currency", usually pegged to the country's main currency at a 1:1 rate. Assume that our LETS is based in a European country where the currency is Euros, and the exchange is done in "local Euros", which are considered to be equivalent to national Euros.

Each user in LETS has an account, which contains the LETS balance of that user (in Local Euros). On joining, each user has a balance of zero. The balance is stored in a (possibly decentralized) ledger. An interesting feature of LETS is that a user with zero balance can also "withdraw" money, but only for paying another LETS user. At any time the sum of LETS balances of all the users is zero.

As an example, Alice with zero balance wishes to purchase one liter of milk for 2 Euros from Bob who is also a member of LETS with zero balance. She transfers 2 Euros from her account to Bob's, making her balance -2 and Bob's +2. Bob can then transfer some or all of his balance to another LETS user in exchange for goods or services.

Trustless LETS

Since we desire a trustless LETS, we cannot depend on any trusted group of people to admit users. Note that we will still have a committee to perform some tasks such as setting up the LETS parameters (local currency, the maximum number of members, etc) and consuming any joining fee.

We will only assume a trusted pricing oracle that gives the current rate of euros to ergs identified by some global id (rateTokenID) and a singleton box containing exactly one token with this id. A singleton box, described here, is a box containing a singleton token, i.e., a token with only one quantity in existence. This box also contains the rate of ergs to euros at any given period of time. The rate is updated by spending this box and creating another singleton box with the new rate.

At any instance, our LETS is uniquely defined by a global token box that contains some membership tokens with id letsTokenID. This box defines the LETS parameters such as the location, the currency unit, rateTokenID, etc. The token box is initially started with, say, 10000 membership tokens. Users can spend this box and create their individual LETS boxes as outputs of the transaction, such that each such output has exactly one membership token and the balance membership tokens are put in a newly created token box.

A LETS box represents a LETS member and must be used in every transaction. For simplicity, this article restricts all LETS transaction to involve exactly two members, one being the sender and the other the receiver, such that the sender transfers some positive amount of the LETS currency (local euros) to the receiver. Such a transaction consumes the member's boxes and recreates them as output with the updated balance.

The Basic Variant

To prevent spam and DDoS attacks, we require at least some minimum number of ergs (minErgsToJoin) to be locked in the newly created member's box. The ergs will be locked until at least minWithdrawTime number of blocks have been mined. A box is allowed to have a negative LETS balance upto the amount that can be covered by the locked ergs (using the rate at the time of trade).

// a tokenBox stores the membership tokens and has this script
val tokenBox = OUTPUTS(0) // the first output must also be a tokenBox
// first output contains remaining LETS tokens

def isLets(b:Box) = { // returns true if b is a LETS box
   // A LETS box must have exactly 1 membership token in tokens(0)
   b.tokens(0)._1 == letsTokenID && b.tokens(0)._2 == 1 &&
   blake2b256(b.propositionBytes) == memberBoxScriptHash &&
   SELF.R4[Long].get == 0 && // start the box with zero LETS balance
   b.value >= minErgsToJoin && // the box must contain some minimum ergs
   b.R6[Long].get <= HEIGHT // store the creation height in R6
}

// how many lets boxes creared in the tx
val numLetsBoxes = OUTPUTS.filter({(b:Box) => isLets(b)}).size

// In the transaction following is preserved for the token box ...
tokenBox.tokens(0)._1 == SELF.tokens(0)._1 &&                //  token id
tokenBox.tokens(0)._2 == SELF.tokens(0)._2 - numLetsBoxes && //  quantity
tokenBox.propositionBytes == SELF.propositionBytes           //  script

A LETS member's box is protected by the script below, whose hash memberBoxScriptHash is used above. The script requires exactly one (sender, receiver) pair per transaction.

val validRateOracle = CONTEXT.dataInputs(0).tokens(0)._1 == rateTokenID
val rate = CONTEXT.dataInputs(0).R4[Int].get
val inBalance = SELF.R4[Long].get    // LETS balance of current input
val pubKey = SELF.R5[SigmaProp].get  // owner of the current input
val createdAt = SELF.R6[Long].get    // height at which current input was mined

val index = getVar[Int](0).get       // index of the corresponding output
val out = OUTPUTS(index)
val outBalance = out.R4[Long].get    // LETS balance of the output

// A LETS box is one that has the same script as the current box
val isMemberBox = {(b:Box) => b.propositionBytes == SELF.propositionBytes}
val letsInputs = INPUTS.filter(isMemberBox)    // all LETS input boxes
val letsOutputs = OUTPUTS.filter(isMemberBox)  // all LETS output boxes

// The current input belongs to the receiver if its LETS balance increases
// There may be some ergs in receiver's input box. We need to ensure that
// the receiver's output box also contains the same amount of ergs as input
val receiver = outBalance > inBalance && out.value == SELF.value

val getBalance = {(b:Box) => b.R4[Long].get} // returns LETS balance of a box

val letsBalIn = letsInputs.map(getBalance).fold(0L, {(l:Long, r:Long) => l + r})
val letsBalOut = letsOutputs.map(getBalance).fold(0L, {(l:Long, r:Long) => l + r})

// sender box can contain less amount of ergs (sender may withdraw ergs provided 
// that any negative LETS balance of sender in out is backed by sufficient ergs)
val correctErgs = out.value >= -outBalance * rate && (
  out.value >= SELF.value || SELF.R6[Long].get + minWithdrawTime > HEIGHT
)

// for the receiver, we don't touch the erg balance, 
// since a receiver is not actively involved in the transaction

inBalance != outBalance && // some transaction should occur; balance must change
SELF.tokens(0)._1 == letsTokenID && // the current input has the right token
out.tokens(0)._1 == letsTokenID && // corresponding output has the right token
validRateOracle &&          // oracle providing rate has the correct "rate token"
letsBalIn == letsBalOut &&  // total LETS balance is preserved in the transaction
letsInputs.size == 2 && letsOutputs.size == 2 &&  // only two LETS inputs, outputs
out.propositionBytes == SELF.propositionBytes &&  // out is a LETS box ...
out.R5[SigmaProp].get == pubKey &&                // ... with the right pub key
out.R6[Long].get == SELF.R6[Long].get &&          // ... and creation height
(receiver ||              // either current input belongs to receiver ...
  (pubKey && correctErgs) // ... or out has correct ergs and tx has signature
)

The transaction spending a box with the above script requires:

  • The sum of the LETS balance of inputs and outputs is preserved
  • There are two LETS inputs and two LETS outputs
  • The public keys (stored in R5) is preserved in the corresponding output
  • The creation height (stored in R6) be preserved in the corresponding output

We say that some public key is the receiver if the LETS balance of its output is higher than that of its input.

The last condition requires that either the input and output boxes belong to the receiver (so that the ergs are preserved), or, in case they belong to the sender, a signature is provided and the output is backed by the required number of ergs if its LETS balance is negative. Furthermore, it requires that the sender's ergs balance cannot be reduced until at least minWithdrawTime number of blocks have been mined after the ergs were locked.

Compared to the managed LETS, the above system has the following differences:

  • No membership record: Unlike the managed LETS, We don't store any membership information here.
  • Multiple-boxes: A person can create multiple membership boxes, which is permitted. We only require that any negative balance be backed by the corresponding number of ergs locked in it.

LETS-1: Zero Sum, Collateral

The above is the basic variant, which we call LETS-1. It has the following features:

  • Time-locked Joining-Fee: To prevent spam attacks, a member has to pay a certain minimum fee in ergs at the time of joining. This fee is refundable but only after a predefined number of blocks.
  • Zero Sum: The sum of the LETS balances of all member boxes is zero. Member boxes are allowed to have a negative balance as long as it is within a certain limit.
  • Collateral: For the sender's output, ergs are used as collateral to cover negative LETS balance at the current exchange rate.

The following are some variations of LETS-1.

LETS-2: Zero Sum, No collateral

This is a slight variation of LETS-1 as follows:

  • Non-refundable joining fee: Similar to LETS-1, a joining fee is needed to prevent spam attacks. However, unlike LETS-1, this fee is non-refundable and must be sent to some predefined management committee.
  • Zero Sum: As in LETS-1.

LETS-3: Positive-Sum, Collateral

The above two variants require the total LETS balance to be always zero. Here we consider a positive value for this sum. In particular, this variant has the following properties:

  • Time-locked Joining Fee: As in LETS-1.
  • Positive Sum: The LETS balance of every member must always be non-negative. This ensures that the sum of the LETS balances of all member boxes is positive. The initial LETS balance is set to a positive value based on the joining fee at the current rate, capped to some maximum value.
  • Collateral: Any reduction in ergs balance of the sender must be accompanied by a reduction of the corresponding LETS balance at the current exchange rate.

We can also allow topping up the LETS balance during a transaction by adding the equivalent amount of ergs.

LETS-4: Positive-Sum, No collateral

This is similar to LETS-3 but with some small variations:

  • Non-refundable Joining Fee: As in LETS-2
  • Positive-Sum: As in LETS-3

The following table summarizes the variants:

Zero SumPositive Sum
CollateralLETS-1LETS-3
No collateralLETS-2LETS-4

We considered LETS transactions involving a single sender-receiver pair. More advanced models can allow multiple senders and receivers, and need not be in pairs.

Share post

Ergo Infrastructure DAO: Descentralizando la columna vertebral del ecosistema Ergo

Ergo Infrastructure DAO: Descentralizando la columna vertebral del ecosistema Ergo

La misión de Ergo siempre ha estado arraigada en la descentralización, no solo en la capa de consenso, sino en toda la pila.

Ergo Platform

13 de agosto de 2025

Mew Finance: Un Kit de Herramientas DeFi Divertido para el Ecosistema Ergo

Mew Finance: Un Kit de Herramientas DeFi Divertido para el Ecosistema Ergo

Mew Finance es un conjunto de aplicaciones descentralizadas en la Blockchain de Ergo.

Ergo Platform

12 de agosto de 2025

Lithos: Descentralizando la Minería con Pools On-Chain

Lithos: Descentralizando la Minería con Pools On-Chain

Lithos es un nuevo protocolo diseñado para reformar cómo funcionan los pools de minería al trasladarlos a la cadena, dando a los m.

Ergo Platform

24 de julio de 2025

Sigma 6.0: Un Ergo Más Inteligente y Flexible

Sigma 6.0: Un Ergo Más Inteligente y Flexible

Sigma 6.0 es una importante actualización propuesta para la blockchain de Ergo.

Ergo Platform

23 de julio de 2025

Dando forma al futuro de Rosen: Una llamada comunitaria sobre cinco propuestas clave del Tesoro

Dando forma al futuro de Rosen: Una llamada comunitaria sobre cinco propuestas clave del Tesoro

El cofundador de Rosen, Armeanio, ha presentado cinco nuevas propuestas al Tesoro de Rosen.

Ergo Platform

9 de julio de 2025

El UTXO Ampliado de Ergo y el Auge de la Inteligencia Económica Artificial

El UTXO Ampliado de Ergo y el Auge de la Inteligencia Económica Artificial

Una Visión Práctica para Agentes Económicos Autónomos Los agentes económicos autónomos en la blockchain de Ergo realizan trabajos.

Ergo Platform

12 de mayo de 2025

ErgoHACK X: Inteligencia Artificial en la Blockchain de Ergo

ErgoHACK X: Inteligencia Artificial en la Blockchain de Ergo

Celebrando una Década de Innovación Descentralizada ¡Únete al décimo aniversario de ErgoHACK y sé parte de la revolución de la IA .

Ergo Platform

10 de abril de 2025

Introduccion a Privacidad y Seguridad en la Blockchain

Introduccion a Privacidad y Seguridad en la Blockchain

Luego del primer whitepaper que apareció en Internet en el 2008, la tecnología blockchain evoluciono enormemente.

Ergo Platform

17 de febrero de 2022

Método híbrido de calcular costes de Ergo

Método híbrido de calcular costes de Ergo

Introducción Verificar la validez de los contratos inteligentes en una blockchain de Prueba de trabajo (PoW) tiene costos, tanto.

Ergo Platform (Translated by Darkkknight, original version will always prevail)

9 de febrero de 2022

Ergo: una respuesta a los fallos de la teoría monetaria moderna

Ergo: una respuesta a los fallos de la teoría monetaria moderna

En 2008, un grupo o persona desconocida lanzó un depósito de valor peer-to-peer y lo llamó Bitcoin.

Ergo Platform (Translated by Comet Community, original version will always prevail)

8 de febrero de 2022

Summit de Ergo : Evento para la privacidad

Summit de Ergo : Evento para la privacidad

Únase a nosotros del 17 al 23 de febrero de 2022 para este evento.

Ergo Foundation (translated by Daniu, original version will always prevail)

5 de febrero de 2022

Finanza descentralizada y privacidad opcional en Ergo

Finanza descentralizada y privacidad opcional en Ergo

Privacidad financial y blockchains públicas Bitcoin es una red de contabilidad distribuida pública a la que pueden acceder todos.

Ergo Platform (translated by Daniu, original version will always prevail)

1 de febrero de 2022

Alquiler por almacenamiento y el futuro de la minería

Alquiler por almacenamiento y el futuro de la minería

Terminología Storage Rent: Alquiler por almacenamiento (se entenderá más adelante) Introducción Los mineros son la capa de con.

Ergo Platform (translated by Daniu, original version will always prevail)

27 de enero de 2022

ErgoHack III: Construyendo la privacidad y seguridad del mañana

ErgoHack III: Construyendo la privacidad y seguridad del mañana

Ergo es una plataforma PoW de contratos inteligentes de código abierto basada en principios económicos de base.

Ergo Foundation (translated by Daniu, original version will always prevail)

20 de enero de 2022

Ergo & Blockchain: Escalabilidad y adopción

Ergo & Blockchain: Escalabilidad y adopción

En este episodio de la serie Ergo & Blockchain, veremos varios aspectos de escalabilidad y por qué son cruciales para la adopció.

Ergo Platform (translated by Daniu, original version will always prevail)

18 de enero de 2022

ErgoHack III Información para registrarse

ErgoHack III Información para registrarse

ErgoHack III tendrá lugar en Febrero 11-13, 2022 Registros abiertos hasta el 31 de Enero, 2022 Con el registro ya abierto, exi.

Ergo Foundation (translated by Daniu, original version will always prevail)

6 de enero de 2022

Ergo Rewards de minería: primera reducción de la emisión

Ergo Rewards de minería: primera reducción de la emisión

Las recompensas de la minería Ergo experimentaron su primera caída en el calendario de emisiones el 2 de enero de 2022 con el bl.

Ergo Platform (translated by Daniu, original version will always prevail)

4 de enero de 2022

¡Hola! soy nuevo, ¿por qué es Ergo un buen proyecto?

¡Hola! soy nuevo, ¿por qué es Ergo un buen proyecto?

¿Qué encontrarás en este artículo? Son numerosas las veces que un nuevo ergonauta en potencia entra a uno de los grupos en españo.

Daniu

1 de enero de 2022

Ergo Platform 2021: Resumen de este año

Ergo Platform 2021: Resumen de este año

A medida que el mundo intenta recuperarse de los efectos de Covid y las diferentes etapas de las restricciones de bloqueo, las c.

Ergo Platform (translated by Daniu, original version will always prevail)

30 de diciembre de 2021

Ergo y Blockchain: Tecnología e Innovación

Ergo y Blockchain: Tecnología e Innovación

La idea inicial detrás de Bitcoin se basó en la promesa de un comercio protegido de puntos centralizados de falla.

Ergo Platform (translated by Daniu, original version will always prevail)

28 de diciembre de 2021

Minería en Ergo: Herramientas de descentralización

Minería en Ergo: Herramientas de descentralización

Ergo es una cadena de bloques PoW (Prueba de trabajo) en el modelo de consenso llamado Autolykos.

Ergo Platform (translated by Daniu, original version will always prevail)

23 de diciembre de 2021