Skip to main content

Flows in code

A flow that moves money or changes a contract comes back from the service as a step for one key to sign. line.steps.sign(step, signer, terms) checks the step against your terms, signs it and submits it. Steps and terms has the details.

FlowMake the stepTermsSigner
Fund a payoutpayins.prepare{ kind: 'advance', face, reference, receiver }PO operations key
Releasepayins.release{ kind: 'release', receiver, amount }PO operations key
Repay allrepayments.create{ kind: 'repay', max }PO operations key
Repay partrepayments.create{ kind: 'repay', amount }PO operations key
Withdraw coverwithdrawals.create{ kind: 'withdraw', asset, amount }PO operations key
PO cancels a take-overtakeovers.cancelByPo{ kind: 'takeover-cancel-po', number }PO operations key
Liquidationliquidations.create{ kind: 'liquidate', asset, repay, asset_amount }Liquidator
Queue a take-overtakeovers.queue{ kind: 'takeover-queue', asset, repay, asset_amount }Untangled admin
Admin cancels a take-overtakeovers.cancel{ kind: 'takeover-cancel', number }Untangled admin
Market settingmarket.step{ kind: 'market', action, address?, enabled? }Market admin

Each example reads its keys from .env (Quick start). Every example on this page typechecks against @crediolabs/payfi-sdk 0.2.2.

Fund a payout​

payins.prepare sends the payout's terms: your reference, the face, the corridor, the receiver and when the fiat should clear. The service screens the receiver, checks the limits and returns the advance as a step for the operations key. Nothing is recorded until the signed step comes back.

Sign within about a minute. The terms come from your own record: the service books the payout with them, and the release later pays that receiver. The advance borrows 90% of the face on the beta lines (advance_bps 9000 in the line's summary); the PO's custody tops up the rest.

fund.ts
// Fund a payout: the service prepares the advance as a step, and the PO's
// operations key signs it.
// bun run fund.ts INV-0001 10
import { createClient } from '@crediolabs/payfi-sdk/api'
import { keypairSigner } from '@crediolabs/payfi-sdk/signing'

function env(name: string): string {
const value = process.env[name]
if (!value) throw new Error(`Set ${name} in .env`)
return value
}

const [reference, face] = process.argv.slice(2)
if (!reference || !face) throw new Error('Usage: bun run fund.ts <reference> <face>')
const receiver = env('PAYFI_RECEIVER')

const url = process.env.PAYFI_URL ?? 'https://payfi-beta.untangled.finance'
const apiKey = keypairSigner(env('PAYFI_API_SECRET'))
const ops = keypairSigner(env('PAYFI_OPS_SECRET'))
const line = createClient({ baseUrl: url, signer: apiKey }).line(env('PAYFI_LINE'))

// The fiat must be due inside the line's overdue window; a day at most here.
const { limits } = await line.get()
const overdue = limits?.overdue_window_seconds ?? 86_400
const expected_settlement_at = Math.floor(Date.now() / 1000) + Math.min(86_400, overdue - 30)

// 1. Prepare: the service screens the receiver and checks the terms and
// limits. It records nothing yet.
const prepared = await line.payins.prepare({
reference,
face,
corridor: 'GB-NG',
receiver,
expected_settlement_at,
})
const { step } = prepared
console.log(`Step ${step.id} for ${step.signer}, valid to ledger ${step.expires_ledger}`)

// 2. Sign within about a minute. steps.sign first checks the step against
// your own record of the payout.
const terms = { kind: 'advance', face, reference, receiver } as const
const funded = await line.steps.sign(step, ops, terms)
console.log(`Advance ${funded.step.status}: tx ${funded.step.tx}`)
console.log(`Payout ${reference} is ${funded.payin?.status}`)
if (funded.release_problem) console.log(`Release problem: ${funded.release_problem}`)

The expected settlement must fall inside the line's overdue window, limits.overdue_window_seconds in the line view. After an advance the payout normally waits as release_proposed.

Release​

The release is a transaction the PO's operations key sends as its source, in which the settlement account pays the receiver. State the receiver and amount from your own record: the service answers only when they are the payout's, with the same 404 otherwise. The operations key signs the whole transaction; the SDK first checks that its source is the signer, that it holds exactly one operation and that its fee is at most 10 XLM.

release.ts
// Release a funded payout to its receiver: a transaction from the PO's
// operations account, signed whole.
// bun run release.ts INV-0001 10
import { createClient } from '@crediolabs/payfi-sdk/api'
import { PayfiError } from '@crediolabs/payfi-sdk/core'
import { keypairSigner } from '@crediolabs/payfi-sdk/signing'

function env(name: string): string {
const value = process.env[name]
if (!value) throw new Error(`Set ${name} in .env`)
return value
}

const [reference, amount] = process.argv.slice(2)
if (!reference || !amount) throw new Error('Usage: bun run release.ts <reference> <amount>')
const receiver = env('PAYFI_RECEIVER')

const url = process.env.PAYFI_URL ?? 'https://payfi-beta.untangled.finance'
const apiKey = keypairSigner(env('PAYFI_API_SECRET'))
const ops = keypairSigner(env('PAYFI_OPS_SECRET'))
const line = createClient({ baseUrl: url, signer: apiKey }).line(env('PAYFI_LINE'))

// The service answers only when the receiver and amount are the payout's own.
async function releaseStep(ref: string) {
for (let asked = 0; ; asked++) {
try {
return await line.payins.release(ref, { receiver, amount: amount! })
} catch (e) {
if (!(e instanceof PayfiError) || e.code !== 'STATE_CONFLICT') throw e
// The payout's advance is still settling on chain, or its release changed
// while the step was built: wait as the service asks, then ask again.
if ((e.detail?.settling || e.detail?.changed) && asked < 40) {
await Bun.sleep(Number(e.detail.retry_after_s ?? 3) * 1000)
continue
}
// A release stays valid for a fixed number of ledgers. Renew a lapsed one.
if (!e.message.includes('renew') || asked > 40) throw e
await line.payins.renewRelease(ref)
}
}
}

const { step } = await releaseStep(reference)
const paid = await line.steps.sign(step, ops, { kind: 'release', receiver, amount })
console.log(`Release ${paid.step.status}: tx ${paid.step.tx}`)
console.log(`Payout ${reference} is ${paid.payin?.status}`)

A release stays valid for a fixed number of ledgers. When it lapses, payins.release answers STATE_CONFLICT; the example then calls payins.renewRelease and asks again.

Right after the advance, its release may not be ready: while the advance is still settling on chain, payins.release answers STATE_CONFLICT with detail.settling and a Retry-After (also in detail.retry_after_s). Wait that long and ask again; renewing does not help. A release that changed while its step was built answers with detail.changed, and means the same.

Testnet: the fiat arrives​

On testnet the service's desk stands in for the fiat side. authorize-receiver authorises a receiver's TUSD trustline before its first payout, and settle pays a payout's fiat into the PO's custody, so a repayment has something to pull. Both are signed by the PO's API key and carry its read grant. A production line has neither.

testnet.ts
// Testnet only: the desk stands in for the fiat side of a payout.
// bun run testnet.ts authorize-receiver G... lets the receiver hold TUSD
// bun run testnet.ts settle INV-0001 pays the fiat into custody
import { createClient, signRequest } from '@crediolabs/payfi-sdk/api'
import { keypairSigner } from '@crediolabs/payfi-sdk/signing'

function env(name: string): string {
const value = process.env[name]
if (!value) throw new Error(`Set ${name} in .env`)
return value
}

const [action, value] = process.argv.slice(2)
const body =
action === 'settle' && value ? { reference: value }
: action === 'authorize-receiver' && value ? { receiver: value }
: null
if (!body) throw new Error('Usage: bun run testnet.ts settle <reference> | authorize-receiver <address>')

const url = process.env.PAYFI_URL ?? 'https://payfi-beta.untangled.finance'
const lineId = env('PAYFI_LINE')
const apiKey = keypairSigner(env('PAYFI_API_SECRET'))
const line = createClient({ baseUrl: url, signer: apiKey }).line(lineId)

// Signed by the PO's API key. The desk holds no PO key, so it reads the
// payout with the PO's read grant.
const path = `/api/lines/${lineId}/testnet/${action}`
const text = JSON.stringify(body)
const headers = {
...(await signRequest(apiKey, { method: 'POST', path, body: text })),
'payfi-grant': await line.grant(),
'content-type': 'application/json',
}
const res = await fetch(`${url}${path}`, { method: 'POST', headers, body: text })
console.log(res.status, await res.json())
if (!res.ok) process.exit(1)

Repay all​

A full repayment pays the debt at the second its ledger closes, so the batch carries one candidate amount for each second of its window. delay_s sets when the window opens: 30 seconds by default, at most 120. A server can pass 0. The service sends the transaction inside the window and closes every open advance; max caps what it may pull from custody.

The service refuses a repayment while any advance is still unreleased: closing it would leave its funds in the settlement account. Release it first.

repay-all.ts
// Repay the whole debt, pulling at most `max` from the PO's custody, and
// close every open advance.
// bun run repay-all.ts 100
import { createClient } from '@crediolabs/payfi-sdk/api'
import { keypairSigner } from '@crediolabs/payfi-sdk/signing'

function env(name: string): string {
const value = process.env[name]
if (!value) throw new Error(`Set ${name} in .env`)
return value
}

const max = process.argv[2]
if (!max) throw new Error('Usage: bun run repay-all.ts <max>')

const url = process.env.PAYFI_URL ?? 'https://payfi-beta.untangled.finance'
const apiKey = keypairSigner(env('PAYFI_API_SECRET'))
const ops = keypairSigner(env('PAYFI_OPS_SECRET'))
const line = createClient({ baseUrl: url, signer: apiKey }).line(env('PAYFI_LINE'))

// delay_s is when the repayment's window opens: 30 s by default, time for a
// person to sign in a wallet. A server signs at once.
const { step } = await line.repayments.create({ max, delay_s: 0 })
const plan = step.summary
console.log(`Debt ${plan.debt}, pull ${plan.pull}, closes ${plan.references}`)

const done = await line.steps.sign(step, ops, { kind: 'repay', max })
for (const c of done.closed ?? []) console.log(`${c.reference}: ${c.outcome}`)
console.log(`Repayment ${done.step.status}: tx ${done.step.tx}`)
console.log(`Debt left: ${done.debt}`)

Repay part​

repayments.create({ amount }) repays exactly amount. It closes the oldest released advances it covers whole and pays the rest towards the next released one. Each open advance owes its loan left plus a share of the interest in proportion to that loan.

The settlement account's repay rule lets a repayment pull at most the POT it withdraws and burns, and only a closed advance's POT is withdrawn. So a partial repayment must close at least one advance whole, and the most it can pay towards the next one is:

spill <= sum(face) - sum(loan + interest share)    over the advances it closes
  • face is the payout's face, the POT minted for it;
  • loan is what the advance borrowed, 90% of the face here, less any earlier partial payment towards it;
  • interest share is that advance's part of the interest owed.

With three advances of face 100 that each owe 91: 91 closes the oldest, 100 closes it and pays 9 towards the next, and 150 is refused with LIMIT_EXCEEDED and the amounts that would pass, "repay at most 100, or 182 or more to repay B as well".

repay-part.ts
// Repay exactly `amount`: it closes the oldest released advances it covers
// whole and pays the rest towards the next one.
// bun run repay-part.ts 9.5
import { createClient } from '@crediolabs/payfi-sdk/api'
import { PayfiError } from '@crediolabs/payfi-sdk/core'
import { keypairSigner } from '@crediolabs/payfi-sdk/signing'

function env(name: string): string {
const value = process.env[name]
if (!value) throw new Error(`Set ${name} in .env`)
return value
}

const amount = process.argv[2]
if (!amount) throw new Error('Usage: bun run repay-part.ts <amount>')

const url = process.env.PAYFI_URL ?? 'https://payfi-beta.untangled.finance'
const apiKey = keypairSigner(env('PAYFI_API_SECRET'))
const ops = keypairSigner(env('PAYFI_OPS_SECRET'))
const line = createClient({ baseUrl: url, signer: apiKey }).line(env('PAYFI_LINE'))

try {
const { step } = await line.repayments.create({ amount })
const plan = step.summary
console.log(`Pull ${plan.pull}, closes ${plan.closes}, debt after ${plan.debt_after}`)

const done = await line.steps.sign(step, ops, { kind: 'repay', amount })
for (const c of done.closed ?? []) console.log(`${c.reference}: ${c.outcome}`)
const part = done.partial
if (part) console.log(`${part.paid} towards ${part.reference}, which owes ${part.remaining_due}`)
console.log(`Repayment ${done.step.status}: tx ${done.step.tx}`)
} catch (e) {
// Over the onchain limit: the service names the amounts that would pass.
if (!(e instanceof PayfiError && e.code === 'LIMIT_EXCEEDED')) throw e
console.log(e.message)
for (const reason of e.reasons) console.log(` ${reason}`)
process.exit(1)
}

Withdraw cover​

A withdrawal moves a basket asset, XLM or USDC on the beta lines, from the settlement account back to the PO's custody. The service checks that the cover stays above the line's required level after it, and the chain's rules check it again.

withdraw.ts
// Withdraw cover: move a basket asset from the settlement account back to
// the PO's custody, within the line's cover limits.
// bun run withdraw.ts XLM 1
import { createClient } from '@crediolabs/payfi-sdk/api'
import { keypairSigner } from '@crediolabs/payfi-sdk/signing'

function env(name: string): string {
const value = process.env[name]
if (!value) throw new Error(`Set ${name} in .env`)
return value
}

const [asset, amount] = process.argv.slice(2)
if (!asset || !amount) throw new Error('Usage: bun run withdraw.ts <asset> <amount>')

const url = process.env.PAYFI_URL ?? 'https://payfi-beta.untangled.finance'
const apiKey = keypairSigner(env('PAYFI_API_SECRET'))
const ops = keypairSigner(env('PAYFI_OPS_SECRET'))
const line = createClient({ baseUrl: url, signer: apiKey }).line(env('PAYFI_LINE'))

const { step } = await line.withdrawals.create({ asset, amount })
const done = await line.steps.sign(step, ops, { kind: 'withdraw', asset, amount })
console.log(`Withdrew ${amount} ${asset}: ${done.step.status}, tx ${done.step.tx}`)

Read the lists​

The payouts, receivers, decisions, events and take-overs are private to the line's keys. With a signer, the client reads them with a read grant. Lists come in pages of 50 by default and at most 200; payins.all() and the other all() calls walk every page.

lists.ts
// The line's private lists, read with a read grant: the client signs one
// request for the grant, then reuses it for 15 minutes.
// bun run lists.ts
import { createClient } from '@crediolabs/payfi-sdk/api'
import { keypairSigner } from '@crediolabs/payfi-sdk/signing'

function env(name: string): string {
const value = process.env[name]
if (!value) throw new Error(`Set ${name} in .env`)
return value
}

const url = process.env.PAYFI_URL ?? 'https://payfi-beta.untangled.finance'
const apiKey = keypairSigner(env('PAYFI_API_SECRET'))
const line = createClient({ baseUrl: url, signer: apiKey }).line(env('PAYFI_LINE'))

const me = await line.whoami()
console.log(`${me.key} acts as ${me.role} on ${me.line}`)

const receivers = await line.receivers.list()
for (const r of receivers.items) {
console.log(`Receiver ${r.address} (${r.name ?? 'no name'}): ${r.payouts} payouts`)
}

const payins = await line.payins.list({ limit: 5 })
for (const p of payins.items) console.log(`Payout ${p.reference}: ${p.face}, ${p.status}`)

const decisions = await line.decisions.list({ limit: 5 })
for (const d of decisions.items) console.log(`Decision ${d.id}: ${d.kind} ${d.outcome}`)

// Events are a feed from the start: keep next_cursor to poll from there.
const events = await line.events.list({ limit: 5 })
for (const e of events.items) console.log(`Event ${e.id}: ${e.type} at ${e.at}`)
console.log(`Next cursor: ${events.next_cursor}`)

The PO cancels a take-over​

Untangled may queue a take-over of the PO's cover when the PO defaults. Once the PO's debt is 0, the PO can cancel a queued take-over itself with takeovers.cancelByPo, signed by its operations key.

cancel-takeover.ts
// The PO cancels a queued take-over of its cover, once its debt is 0.
// bun run cancel-takeover.ts 3
import { createClient } from '@crediolabs/payfi-sdk/api'
import { keypairSigner } from '@crediolabs/payfi-sdk/signing'

function env(name: string): string {
const value = process.env[name]
if (!value) throw new Error(`Set ${name} in .env`)
return value
}

const number = Number(process.argv[2])
if (!Number.isInteger(number) || number < 0) throw new Error('Usage: bun run cancel-takeover.ts <number>')

const url = process.env.PAYFI_URL ?? 'https://payfi-beta.untangled.finance'
const apiKey = keypairSigner(env('PAYFI_API_SECRET'))
const ops = keypairSigner(env('PAYFI_OPS_SECRET'))
const line = createClient({ baseUrl: url, signer: apiKey }).line(env('PAYFI_LINE'))

const { takeover: t } = await line.takeovers.get(number)
console.log(`Take-over ${t.number}: ${t.repay} for ${t.asset_amount} ${t.asset}, ${t.status}`)

const { step } = await line.takeovers.cancelByPo(number)
const done = await line.steps.sign(step, ops, { kind: 'takeover-cancel-po', number })
console.log(`Cancel ${done.step.status}: tx ${done.step.tx}`)

Liquidation​

Anyone may liquidate a line whose cover is under its maintenance level. liquidations.quote gives the most the liquidator may repay and the least asset it receives for it. The liquidator signs the step with those amounts as its terms, so a worse price than the quote is refused before it signs.

The step is the liquidator's own transaction, five calls through the line's gate-free execution contract: steps.sign checks it, the liquidator signs it once as its source, and the service only sends it. No key of Untangled's signs a liquidation.

The liquidator needs no service at all. chain.liquidations.buildLiquidation builds the same transaction from chain reads: the quote on the debt as the market reads it now, with about a minute of interest left below half of it and the asset 0.5% under the rule's 105% edge, so a small price rise before it runs still passes; the five calls; and the liquidator's stablecoin transfer with source-account credentials, so nothing it signs can be copied into another batch. A quote the chain would refuse throws REFUSED, with one code per check of the rule in detail.refusals. The line's records pick up the liquidation from the chain's events and list it in the line view's liquidations.

liquidate.ts
// Liquidate a line whose cover is under its maintenance level, with no service
// at all: the SDK builds the liquidator's own transaction from chain reads, the
// liquidator signs it once as its source, and it goes straight to the network.
// bun run liquidate.ts XLM [repay]
import { connect } from '@crediolabs/payfi-sdk/chain'
import { lineFromRegistry } from '@crediolabs/payfi-sdk/core'
import { TESTNET_REGISTRY } from '@crediolabs/payfi-sdk/api'
import { NETWORKS } from '@crediolabs/payfi-sdk/networks'
import { keypairSigner } from '@crediolabs/payfi-sdk/signing'

function env(name: string): string {
const value = process.env[name]
if (!value) throw new Error(`Set ${name} in .env`)
return value
}

const [asset, repay] = process.argv.slice(2)
if (!asset) throw new Error('Usage: bun run liquidate.ts <asset> [repay]')

const line = lineFromRegistry(TESTNET_REGISTRY, env('PAYFI_LINE'))
const liquidator = keypairSigner(env('PAYFI_LIQUIDATOR_SECRET'))
const chain = connect(NETWORKS[line.network])

// The quote reads the debt as the market sees it now, interest included.
const quote = await chain.liquidations.quote(line, { asset, ...(repay ? { repay } : {}) })
if (!quote.ok) {
console.log(`Nothing to liquidate: ${quote.reasons.join('; ')}`)
process.exit(0)
}

// The liquidator is the transaction's source: its TUSD transfer carries
// source-account credentials, so no entry it signs can be lifted elsewhere.
const built = await chain.liquidations.buildLiquidation(line, {
liquidator: await liquidator.address(),
asset,
...(repay ? { repay } : {}),
})
console.log(`Repay ${built.terms.repay} for ${built.terms.asset_amount} of ${asset} (base units)`)

const signed = await liquidator.signTransaction(built.xdr, {
network: line.network,
purpose: 'liquidate',
summary: { asset, repay: String(built.terms.repay) },
expiresLedger: built.expiresLedger,
})
const sent = await chain.rpc.send(signed, { maxLedger: built.expiresLedger })
console.log(`Liquidation ${sent.status}: tx ${sent.hash}`)

Admin: freeze and lift​

Untangled's admin freezes a line with a reason, and lifts the freeze later. Both are signed requests with no step. freeze.get() is public.

freeze.ts
// Untangled's admin freezes a line, or lifts the freeze. A frozen line funds
// no new payout.
// bun run freeze.ts set "Fiat partner outage"
// bun run freeze.ts lift
import { createClient } from '@crediolabs/payfi-sdk/api'
import { keypairSigner } from '@crediolabs/payfi-sdk/signing'

function env(name: string): string {
const value = process.env[name]
if (!value) throw new Error(`Set ${name} in .env`)
return value
}

const url = process.env.PAYFI_URL ?? 'https://payfi-beta.untangled.finance'
const admin = keypairSigner(env('PAYFI_ADMIN_SECRET'))
const line = createClient({ baseUrl: url, signer: admin }).line(env('PAYFI_LINE'))

const [action, reason] = process.argv.slice(2)
if (action === 'set' && reason) await line.freeze.set(reason)
else if (action === 'lift') await line.freeze.lift()
else throw new Error('Usage: bun run freeze.ts set <reason> | lift')

const { freeze } = await line.freeze.get()
console.log(freeze.frozen ? `Frozen since ${freeze.since}: ${freeze.reason}` : 'Not frozen')

Admin: take-over​

Untangled's admin queues a take-over of a basket asset for an amount of debt: one call stored on the line's gated execution contract for the line's wait. It runs it with takeovers.run once it is due; the service checks the price and the debt again, and Untangled's recovery account sends the run as the transaction's source, paying that debt and taking the asset. The chain judges the price and the debt again at the run, so a repayment or a price move during the wait makes it fail. The admin cancels a queued one with takeovers.cancel(number) and the terms { kind: 'takeover-cancel', number }.

takeover.ts
// Untangled's admin queues a take-over of the PO's cover for its debt, then
// runs it once it is due.
// bun run takeover.ts queue XLM 10 "Overdue since 12 October"
// bun run takeover.ts run 3
import { createClient } from '@crediolabs/payfi-sdk/api'
import { keypairSigner } from '@crediolabs/payfi-sdk/signing'

function env(name: string): string {
const value = process.env[name]
if (!value) throw new Error(`Set ${name} in .env`)
return value
}

const url = process.env.PAYFI_URL ?? 'https://payfi-beta.untangled.finance'
const admin = keypairSigner(env('PAYFI_ADMIN_SECRET'))
const line = createClient({ baseUrl: url, signer: admin }).line(env('PAYFI_LINE'))

const [action, a, b, reason] = process.argv.slice(2)
if (action === 'queue' && a && b) {
const { step } = await line.takeovers.queue({ asset: a, repay: b, ...(reason ? { reason } : {}) })
// What recovery takes for the repayment, at par: read it before signing; the SDK checks the step gives exactly that.
const takes = String(step.summary.asset_amount)
console.log(`The take-over repays ${b} and takes ${takes} ${a}`)
const done = await line.steps.sign(step, admin, { kind: 'takeover-queue', asset: a, repay: b, asset_amount: takes })
const t = done.takeover
console.log(`Queued take-over ${t?.number}, runs from ledger ${t?.runnable_ledger}`)
} else if (action === 'run' && a) {
const { takeover: t } = await line.takeovers.run(Number(a))
console.log(`Take-over ${t.number} ${t.status}: tx ${t.tx}`)
} else {
throw new Error('Usage: bun run takeover.ts queue <asset> <repay> [reason] | run <number>')
}

Admin: market settings and limits​

market.get() reads the line's market: its settings, totals and oracle, and whether each admin action can run now. market.step({ action, address?, enabled? }) makes the change as a transaction step, asked for with the admin's signed request and signed by the market admin with the terms { kind: 'market', action, address?, enabled? }.

The admin also sets the line's overdue window and line cap with limits.setOverdueWindow(seconds) and limits.setLineCap(amount), signed requests with no step. The line cap may be at most the payout rule's cap on chain.