Para desarrolladores / SENDIT

SenditBank

Un solo contrato guarda el dinero de todas las cuentas de SENDIT. Una billetera deposita una vez y registra una clave; a partir de ahí la clave firma las operaciones, y cada venue la resuelve de vuelta a la cuenta de la billetera.

El modelo

  • Cuentas. Una cuenta es una dirección de billetera (o cualquier contrato que actúe como su propia cuenta). Los saldos son balanceOf[account][asset], nunca indexados por una clave.
  • Activos. pUSD, ETH como address(0), y los tokens de un launcher que el operador haya añadido (isAsset). Cualquier otro token se rechaza. totalHeld[asset] es la suma exacta de todos los saldos y nunca supera lo que tiene el banco.
  • Claves. Direcciones que una cuenta registró con una prueba firmada por la propia clave. Una clave gasta el saldo de la cuenta en los venues, envía, retira a la billetera de la propia cuenta, recarga su propio gas y revoca. No puede registrar claves, cambiar los límites ni hacer withdrawTo hacia otra dirección.
  • Venues. Los contratos autorizados a debitar cuentas: el motor, el libro de órdenes, la bóveda, la fábrica de copias, el router spot y el cambio de pUSD. Cada uno llama a bank.pull(msg.sender, asset, amount) con su propio llamante, así que un venue no puede elegir de quién es el dinero que toma. Cada pago vuelve con bank.push(account, ...), nunca al firmante.

No hay receive(), ni barrido, ni edición de saldos, ni actualización, ni comisión. El ETH solo entra por deposit y push.

Cuentas y accountOf

accountOf(sender) es la cuenta en nombre de la cual actúa un remitente: el propietario mientras sender sea una clave registrada bajo el keyEpoch actual de la cuenta y el globalEpoch actual, y el propio sender en caso contrario. Así, una billetera se resuelve a sí misma y todos los venues funcionan también con firma de billetera. Las posiciones, las participaciones de la bóveda, las cuentas de copia y todos los eventos nombran la cuenta, nunca la clave.

Una clave está caducada cuando accountOf(keyOf(account)) != account. Aquí no hay playerOf: ese es el nombre que da el banco del arcade a la misma idea.

La prueba de clave

La clave consiente en servir a la cuenta firmando un digest:

Solidity
keyDigest(account, key) = keccak256(abi.encode(
  "SENDIT/key-proof/v1", block.chainid, address(bank), account, key,
  keyEpoch[account], globalEpoch))

La prueba es la firma EIP-191 de la clave sobre esos 32 bytes ("\x19Ethereum Signed Message:\n32" || digest): 65 bytes, s baja, v 27 o 28 (se aceptan 0 y 1). Después la billetera la envía con setKey(key, proof) o dentro de deposit(pusdAmount, gasToKey, key, proof), que además puede financiar el gas de la clave en la misma transacción.

viem
import { encodeAbiParameters, parseAbiParameters, keccak256 } from "viem";
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";

const key = privateKeyToAccount(generatePrivateKey()); // keep the private key safe

// ADD a key under the epochs in force: the bank computes the digest for you.
const digest = await client.readContract({
  address: bank, abi: bankAbi, functionName: "keyDigest", args: [account, key.address],
});
const proof = await key.signMessage({ message: { raw: digest } }); // EIP-191, 32 bytes

// REPLACE every key of the account: the same digest under keyEpoch + 1.
const [epoch, global] = await Promise.all([
  client.readContract({ address: bank, abi: bankAbi, functionName: "keyEpoch", args: [account] }),
  client.readContract({ address: bank, abi: bankAbi, functionName: "globalEpoch" }),
]);
const nextDigest = keccak256(encodeAbiParameters(
  parseAbiParameters("string, uint256, address, address, address, uint64, uint64"),
  ["SENDIT/key-proof/v1", 78270n, bank, account, key.address, epoch + 1n, global],
));
const replaceProof = await key.signMessage({ message: { raw: nextDigest } });
Cómo crea la aplicación su clave

El propio front end de SENDIT deriva la clave de una firma de la billetera sobre un mensaje EIP-4361 fijo ("Unlock my SENDIT trading key...", ligado al dominio, la cadena, el banco y las dos épocas), de modo que cada dispositivo vuelve a derivar la misma clave. Un bot no lo necesita: cualquier clave que usted controle sirve, siempre que su prueba sea correcta.

Épocas: añadir o sustituir

Una prueba se comprueba contra uno de dos pares de épocas, y cuál de ellos decide lo que ocurre:

  • Épocas actuales: AÑADIR. La clave se suma a las claves vigentes de la cuenta; todas las demás siguen vigentes (una clave por dispositivo).
  • keyEpoch + 1: SUSTITUIR. El banco revoca primero (la época avanza, todas las claves terminan, KeyRevoked) y luego registra la clave bajo la nueva época.

revokeKey() termina todas las claves de la cuenta; rotateKey(newKey, proof) revoca y registra en una sola transacción, con una prueba bajo la nueva época. invalidateAllKeys() mueve globalEpoch y termina todas las claves del banco. keyOf(account) es solo la última clave registrada, la que recibe el gas del depósito.

Límites

Las salidas de pUSD y ETH de una clave hacia terceros (send, refuel y los pulls de un venue con límite, que hoy es el router spot) cuentan contra unos límites diarios por cuenta, sobre una ventana fija de 24 horas que empieza con la primera salida contabilizada. Los perps, la bóveda y la copia no tienen límite, los tokens lanzados tampoco, y las llamadas firmadas por la billetera nunca se contabilizan. Los valores por defecto del contrato son 10.000 pUSD y 5 ETH al día; el despliegue de la testnet los desactivó (UNCAPPED, lea defaultCaps()). Una cuenta fija los suyos con setKeyCaps desde su billetera: 0 significa el valor por defecto.

Pausa

setPaused(true) detiene pull y move de los venues, y send y refuel firmados por una clave. Nunca detiene withdraw, withdrawTo, push (así que las posiciones se siguen cerrando y los pagos llegan), los depósitos, el registro y la revocación de claves, ni el send propio de una billetera o de un contrato (una cuenta de copia paga a su copiador mediante send). El cambio de pUSD respeta la pausa del banco en sus dos puertas.

Venues y el plazo de 24 horas

Un venue puede debitar cualquier cuenta a través del remitente que transmite, así que los venues son la raíz de confianza del banco. Añadir uno es proposeVenue y después activateVenue pasado VENUE_DELAY (24 horas): un evento VenueProposed da a cada cuenta un día para retirar antes. listVenueNow se salta la espera solo antes del primerísimo crédito del banco. removeVenue es inmediato, y un venue retirado todavía puede hacer push.

Funciones y eventos

Where every SENDIT account's money lives: pUSD, ETH (address(0)) and launched tokens, keyed by the account (the wallet), never by a key. Venues debit it with pull and credit it with push.

Wallet

FunctionWhat it does
deposit(uint256 pusdAmount, uint256 gasToKey, address key, bytes keyProof) payableThe one wallet transaction: pulls pUSD with no approve, credits msg.value - gasToKey as ETH, registers key when non-zero, and sends gasToKey to the account's key. Every argument may be zero.
depositToken(address token, uint256 amount)Deposits a launched token (or pUSD) already in the wallet. A launched token needs an approve to the bank first; pUSD does not.
setKey(address key, bytes keyProof)Registers a key. A proof under the current epochs ADDS it; a proof under keyEpoch + 1 REPLACES every key of the account.
setKeyCaps(uint128 pusdPerDay, uint128 ethPerDay)The account's own daily caps on its keys' sends, spot buys and launches. 0 means the default, UNCAPPED means none. Wallet only.
withdrawTo(address asset, uint256 amount, address to)Wallet only: pays another address, for a smart account with no receive(). Never paused, never capped.

Wallet or key

FunctionWhat it does
withdraw(address asset, uint256 amount)Pays accountOf(msg.sender), the wallet, whoever signs. Never paused, never capped.
send(address to, address asset, uint256 amount, bool toWallet)From the signer's account to `to`: credited in the bank (toWallet false; a live key named as `to` credits its account) or paid out as the asset. Key-signed pUSD and ETH count against the caps and stop while paused.
revokeKey()Ends every key of the account: keyEpoch moves on, so every device derives a new key.
rotateKey(address newKey, bytes keyProof)revokeKey, then registers newKey with a proof under the NEW account epoch, in one transaction.
refuel() returns (uint256 amount)A live key below REFUEL_BELOW tops itself up to REFUEL_TO from its account's ETH, once per REFUEL_EVERY. Stops while paused.

Venues

FunctionWhat it does
pull(address sender, address asset, uint256 amount) returns (address account)A venue debits accountOf(sender) and receives the asset. The venue passes its own msg.sender, so it never names whose money it takes. Stops while paused.
push(address account, address asset, uint256 amount) payableA venue credits `account` with what it hands over in this call. Never paused, and a removed venue can still push, so payouts in flight land.
move(address sender, address to, address asset, uint256 amount) returns (address account)A venue debits accountOf(sender) and credits `to` with no token moving (how a copy account is funded). Stops while paused.

Reading an account

FunctionWhat it does
accountOf(address sender) view returns (address)The account behind a sender: the owner while sender is one of its live keys, sender itself otherwise.
balanceOf(address account, address asset) view returns (uint256)One balance. asset address(0) is ETH.
keyOf(address account) view returns (address)The key registered last (address(0) after a revoke). Not proof that it is live: compare accountOf(keyOf(account)) with account.
ownerOfKey(address key) view returns (address)The account a key was registered for, live or not.
keyEpoch(address account) view returns (uint64)The account's key epoch. A revoke adds one.
keyAccountEpochOf(address key) view returns (uint64)The account epoch a key was registered under.
keyGlobalEpochOf(address key) view returns (uint64)The global epoch a key was registered under.
globalEpoch() view returns (uint64)The bank-wide epoch. invalidateAllKeys adds one.
keyDigest(address account, address key) view returns (bytes32)What the key signs (EIP-191) to consent to serving the account under the epochs in force now.
keyCapsOf(address account) view returns (uint256 pusdPerDay, uint256 ethPerDay, uint256 pusdSpent, uint256 ethSpent, uint64 windowEnds)The caps in force and what the keys spent in the current 24-hour window (zeros once it ended).
lastRefuelAt(address key) view returns (uint64)When a key last refuelled.
totalHeld(address asset) view returns (uint256)The sum of every balance of an asset. Never more than the bank holds.
isAsset(address asset) view returns (bool)ETH, pUSD, or a token launched by a launcher the operator added.

Reading the bank

FunctionWhat it does
pusd() view returns (address)The pUSD token.
operator() view returns (address)The operator: pause, venues, default caps, launchers, the key brake.
paused() view returns (bool)Whether venue pulls and moves and key-signed sends and refuels are stopped.
everFunded() view returns (bool)Set by the first credit; closes listVenueNow for ever.
defaultCaps() view returns (uint128 pusdPerDay, uint128 ethPerDay)The caps an account gets when it set none.
isVenue(address) view returns (bool)Whether an address may pull and move.
isCappedVenue(address) view returns (bool)Whether a key's pUSD and ETH spent through this venue count against the caps (the spot router).
wasVenue(address) view returns (bool)Ever listed: may still push after a removal.
venueActiveAt(address) view returns (uint64)When a proposed venue may be activated; 0 when none is pending.
proposedCapped(address) view returns (bool)The capped flag a pending venue will be listed with.
isLauncher(address) view returns (bool)Whether a launcher's tokens are accepted.
launchers(uint256) view returns (address)The added launchers, by index.
launcherCount() view returns (uint256)How many launchers were added.

Operator

FunctionWhat it does
proposeVenue(address venue, bool capped)Starts the VENUE_DELAY wait before a venue can be listed.
activateVenue(address venue)Lists a proposed venue once its delay has passed.
listVenueNow(address venue, bool capped)Lists a venue at once, only while the bank has never been credited (how the deploy lists its own venues).
removeVenue(address venue)Immediate. The venue can no longer pull or move, but can still push.
setPaused(bool paused_)The pause (see the pause rules).
setDefaultCaps(uint128 pusdPerDay, uint128 ethPerDay)The default caps. Both must be non-zero.
addLauncher(address launcher)Add-only: a launcher's tokens stay accepted for ever.
invalidateAllKeys()Moves globalEpoch on: every key on the bank stops resolving at once. Moves no balance; costs every account one setKey.
setOperator(address next)Hands the operator role on.

Constants

FunctionWhat it does
VERSION() view returns (uint256)1.
ETH() view returns (address)address(0), the ETH asset.
VENUE_DELAY() view returns (uint64)24 hours between proposeVenue and activateVenue.
CAP_WINDOW() view returns (uint64)24 hours, from the first charged outflow.
UNCAPPED() view returns (uint128)type(uint128).max: a cap of this value is no cap.
REFUEL_BELOW() view returns (uint256)0.002 ETH: a key may refuel below this.
REFUEL_TO() view returns (uint256)0.01 ETH: what a refuel tops the key up to.
REFUEL_EVERY() view returns (uint256)1 hour between two refuels of one key.

Events

EventWhat it does
Deposited(address indexed account, address indexed asset, uint256 amount)A deposit credited, pUSD, ETH or a token.
GasSent(address indexed account, address indexed key, uint256 amount, bool fromBalance)ETH sent to a key: the deposit's gas seed (fromBalance false) or a refuel (true).
Withdrawn(address indexed account, address indexed asset, uint256 amount, address to, address by)A withdrawal; `by` is the signer, a key or the wallet.
Sent(address indexed from, address indexed to, address indexed asset, uint256 amount, bool toWallet, address by)A send, in the bank or paid out.
Pulled(address indexed venue, address indexed account, address indexed asset, uint256 amount, address by)A venue took money from an account; `by` is who signed.
Pushed(address indexed venue, address indexed account, address indexed asset, uint256 amount)A venue paid an account.
Moved(address indexed venue, address indexed from, address indexed to, address asset, uint256 amount, address by)A venue moved money between two accounts.
KeySet(address indexed account, address indexed key, uint64 accountEpoch, uint64 globalEpoch)A key registered.
KeyRevoked(address indexed account, address indexed key, uint64 nextEpoch, address by)Every key of an account ended.
KeysInvalidated(uint64 globalEpoch)The operator ended every key on the bank.
CapsSet(address indexed account, uint256 pusdPerDay, uint256 ethPerDay)Caps changed; account address(0) is the default.
VenueProposed(address indexed venue, bool capped, uint64 activeAt)A venue proposed; activeAt is when it can be listed.
VenueSet(address indexed venue, bool allowed, bool capped)A venue listed or removed.
Paused(bool paused)The pause switched.
OperatorSet(address indexed previous, address indexed next)The operator changed.
LauncherAdded(address indexed launcher)A launcher's tokens accepted.