Examples¶
All examples live in the examples/ directory and are built in CI; the quickstart and custom-mapper examples are also run there.
Quickstart¶
A complete replay and reconciliation against in-memory fakes — no servers required.
Replayed 5 Formance transactions into 7 Blnk transactions (2 ledgers, 3 balances)
Reconciliation: ok=true checked=5 matched=5
Second run wrote 0 transactions
// Quickstart runs a complete migration against in-memory fakes of Formance
// and Blnk, so you can see the whole flow without any servers:
//
// go run ./examples/quickstart
package main
import (
"context"
"fmt"
"log/slog"
"os"
"time"
"github.com/otyang/formance2blnk/blnk"
"github.com/otyang/formance2blnk/formance"
"github.com/otyang/formance2blnk/internal/fakes"
"github.com/otyang/formance2blnk/mapping"
"github.com/otyang/formance2blnk/migrator"
"github.com/otyang/formance2blnk/state"
)
func main() {
ctx := context.Background()
fm, bk := fakes.NewFormance(), fakes.NewBlnk()
defer fm.Close()
defer bk.Close()
// 1. A small Formance history: deposits, a payment with a fee, a
// refund (revert) and a withdrawal.
t0 := time.Date(2025, 1, 1, 9, 0, 0, 0, time.UTC)
post := func(h int, ps ...formance.Posting) uint64 {
return fm.Post("main", t0.Add(time.Duration(h)*time.Hour), ps, map[string]string{"description": "demo"})
}
usd := func(src, dst string, v int64) formance.Posting {
return formance.Posting{Source: src, Destination: dst, Amount: fakes.Amt(v), Asset: "USD/2"}
}
post(0, usd("world", "users:alice:wallet", 50_00))
post(1, usd("world", "users:bob:wallet", 20_00))
pay := post(2, usd("users:alice:wallet", "merchants:acme:main", 12_50), usd("users:alice:wallet", "platform:fees", 50))
fm.Revert("main", pay, t0.Add(3*time.Hour))
post(4, usd("users:bob:wallet", "world", 5_00))
// 2. Wire up clients, mapping and a state store.
src, _ := formance.New(formance.Options{BaseURL: fm.URL()})
dst, _ := blnk.New(blnk.Options{BaseURL: bk.URL()})
mapper, err := mapping.New(mapping.Config{Rules: []mapping.Rule{
{Match: "platform:fees", Indicator: "@Fees"},
{Match: "users:*:wallet", Ledger: "Customer Wallets"},
{Match: "merchants:**", Ledger: "Merchants"},
}})
if err != nil {
panic(err)
}
m, err := migrator.New(src, dst, migrator.Options{
Ledgers: []string{"main"},
Mapper: mapper,
Store: state.NewMemory(),
Logger: slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})),
})
if err != nil {
panic(err)
}
// 3. Plan-free replay, then reconcile.
st, err := m.Replay(ctx)
if err != nil {
panic(err)
}
fmt.Printf("Replayed %d Formance transactions into %d Blnk transactions (%d ledgers, %d balances)\n",
st.FormanceTxs, st.BlnkTxs, st.LedgersCreated, st.BalancesCreated)
rep, err := m.Reconcile(ctx, migrator.ReconcileOptions{CheckVolumes: true})
if err != nil {
panic(err)
}
fmt.Printf("Reconciliation: ok=%v checked=%d matched=%d\n", rep.OK(), rep.Checked, rep.Matched)
// 4. Re-running is safe: nothing is written twice.
again, _ := m.Replay(ctx)
fmt.Printf("Second run wrote %d transactions\n", again.BlnkTxs)
}
Production¶
Embedding the migrator in your own program: OAuth2 against Formance Cloud, a durable state file, graceful shutdown, structured logs, a progress callback and a strict reconciliation gate.
// Production shows how to embed the migrator in your own program against
// real servers, with a durable state file, graceful shutdown, a progress
// callback and a strict reconciliation gate.
//
// FORMANCE_URL=https://ORG.ENV.formance.cloud/api/ledger \
// FORMANCE_CLIENT_ID=... FORMANCE_CLIENT_SECRET=... \
// BLNK_URL=https://blnk.internal BLNK_API_KEY=... \
// go run ./examples/production -ledger main
package main
import (
"context"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"syscall"
"github.com/otyang/formance2blnk/blnk"
"github.com/otyang/formance2blnk/formance"
"github.com/otyang/formance2blnk/mapping"
"github.com/otyang/formance2blnk/migrator"
"github.com/otyang/formance2blnk/state"
)
func main() {
ledger := flag.String("ledger", "main", "Formance ledger to migrate")
statePath := flag.String("state", "migration-state.json", "state file")
flag.Parse()
logger := slog.New(slog.NewJSONHandler(os.Stderr, nil))
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := run(ctx, logger, *ledger, *statePath); err != nil {
logger.Error("migration failed", "err", err)
os.Exit(1)
}
}
func run(ctx context.Context, logger *slog.Logger, ledger, statePath string) error {
src, err := formance.New(formance.Options{
BaseURL: os.Getenv("FORMANCE_URL"),
ClientID: os.Getenv("FORMANCE_CLIENT_ID"),
ClientSecret: os.Getenv("FORMANCE_CLIENT_SECRET"),
PageSize: 100,
RequestsPerSecond: 20, // be gentle with the source
})
if err != nil {
return err
}
dst, err := blnk.New(blnk.Options{BaseURL: os.Getenv("BLNK_URL"), APIKey: os.Getenv("BLNK_API_KEY")})
if err != nil {
return err
}
mapper, err := mapping.New(mapping.Config{
Rules: []mapping.Rule{
{Match: "platform:fees", Indicator: "@Fees"},
{Match: "platform:float:*", Indicator: "@Float-{1}"},
{Match: "users:*:wallet", Ledger: "Customer Wallets"},
{Match: "merchants:**", Ledger: "Merchants"},
},
})
if err != nil {
return err
}
store, err := state.OpenFile(statePath)
if err != nil {
return err
}
defer store.Close() // flushes and releases the lock, also on Ctrl-C
m, err := migrator.New(src, dst, migrator.Options{
Ledgers: []string{ledger},
Mapper: mapper,
Store: store,
Logger: logger,
CopyAccountMetadata: true,
Progress: func(s migrator.Stats) {
logger.Info("progress", "ledger", s.Ledger, "formance_txs", s.FormanceTxs, "blnk_txs", s.BlnkTxs)
},
})
if err != nil {
return err
}
stats, err := m.Replay(ctx)
logger.Info("replay finished", "stats", stats)
if err != nil {
return err // re-run the program to resume from the checkpoint
}
report, err := m.Reconcile(ctx, migrator.ReconcileOptions{CheckVolumes: true})
if err != nil {
return err
}
if !report.OK() {
for _, mm := range report.Mismatches {
logger.Error("mismatch", "target", mm.Target, "accounts", mm.Accounts, "field", mm.Field,
"expected", mm.Expected, "actual", mm.Actual)
}
return fmt.Errorf("%d reconciliation mismatches", len(report.Mismatches))
}
logger.Info("ledgers match", "checked", report.Checked)
return nil
}
Custom mapper¶
Implementing mapping.Mapper to route accounts to a Blnk ledger per country, falling back to the rules mapper.
// Custom-mapper shows how to plug your own account-routing logic into the
// migrator by implementing mapping.Mapper. Here, accounts are routed to a
// Blnk ledger per country taken from the address, and any asset ending in
// "_TEST" is mapped to a sandbox currency.
//
// go run ./examples/custom-mapper
package main
import (
"context"
"fmt"
"strings"
"time"
"github.com/otyang/formance2blnk/blnk"
"github.com/otyang/formance2blnk/formance"
"github.com/otyang/formance2blnk/internal/fakes"
"github.com/otyang/formance2blnk/mapping"
"github.com/otyang/formance2blnk/migrator"
)
// countryMapper routes "users:<country>:<id>" to "Wallets <COUNTRY>" and
// falls back to the rules mapper for everything else.
type countryMapper struct {
fallback *mapping.Rules
}
func (c countryMapper) Account(ledger, address string) (mapping.Target, error) {
parts := strings.Split(address, ":")
if len(parts) == 3 && parts[0] == "users" {
return mapping.Target{Kind: mapping.KindBalance, Ledger: "Wallets " + strings.ToUpper(parts[1])}, nil
}
return c.fallback.Account(ledger, address)
}
func (c countryMapper) Asset(asset string) (mapping.Asset, error) {
a, err := c.fallback.Asset(asset)
if err == nil && strings.HasSuffix(a.Currency, "_TEST") {
a.Currency = "SANDBOX"
}
return a, err
}
func main() {
fm, bk := fakes.NewFormance(), fakes.NewBlnk()
defer fm.Close()
defer bk.Close()
now := time.Now()
fm.Post("main", now, []formance.Posting{{Source: "world", Destination: "users:ng:1", Amount: fakes.Amt(500000), Asset: "NGN/2"}}, nil)
fm.Post("main", now, []formance.Posting{{Source: "world", Destination: "users:gh:7", Amount: fakes.Amt(9000), Asset: "GHS/2"}}, nil)
rules, _ := mapping.New(mapping.Config{})
src, _ := formance.New(formance.Options{BaseURL: fm.URL()})
dst, _ := blnk.New(blnk.Options{BaseURL: bk.URL()})
m, err := migrator.New(src, dst, migrator.Options{Ledgers: []string{"main"}, Mapper: countryMapper{rules}})
if err != nil {
panic(err)
}
st, err := m.Replay(context.Background())
if err != nil {
panic(err)
}
fmt.Printf("created %d ledgers and %d balances\n", st.LedgersCreated, st.BalancesCreated)
}
Configuration files¶
{
"formance": {
"url": "http://localhost:3068",
"ledgers": ["main"],
"page_size": 100
},
"blnk": {
"url": "http://localhost:5001",
"api_key": "${BLNK_API_KEY:-}"
},
"mapping": {
"rules": [
{ "match": "platform:fees", "indicator": "@Fees" },
{ "match": "users:*:wallet", "ledger": "Customer Wallets" },
{ "match": "merchants:**", "ledger": "Merchants" }
]
},
"migration": {
"mode": "replay",
"batch_size": 50,
"copy_account_metadata": true
},
"state_file": "formance2blnk-state/replay.json"
}
{
"formance": {
"url": "http://localhost:3068",
"ledgers": ["main", "payouts"]
},
"blnk": {
"url": "http://localhost:5001",
"api_key": "${BLNK_API_KEY:-}"
},
"mapping": {
"default_ledger": "Formance {ledger}",
"rules": [
{ "match": "platform:**", "indicator": "@Platform" }
]
},
"migration": {
"mode": "snapshot",
"opening_indicator": "@OpeningBalances",
"include_zero_balances": true
},
"state_file": "formance2blnk-state/snapshot.json"
}
{
"formance": {
"url": "https://${FORMANCE_ORG}.${FORMANCE_ENV:-eu.sandbox}.formance.cloud/api/ledger",
"ledgers": ["main"],
"client_id": "${FORMANCE_CLIENT_ID}",
"client_secret": "${FORMANCE_CLIENT_SECRET}",
"scopes": ["ledger:read"],
"requests_per_second": 20
},
"blnk": {
"url": "${BLNK_URL}",
"api_key": "${BLNK_API_KEY}",
"requests_per_second": 50
},
"mapping": {
"world_indicator": "@World",
"rules": [
{ "match": "platform:fees", "indicator": "@Fees" },
{ "match": "banks:*", "indicator": "@Bank-{1}" },
{ "match": "users:*:wallet", "ledger": "Customer Wallets" },
{ "match": "sandbox:**", "skip": true }
],
"assets": {
"COIN": { "currency": "NGN", "decimals": 2 }
}
},
"migration": {
"mode": "hybrid",
"cutoff": "2026-01-01T00:00:00Z",
"reverts": "skip",
"on_skipped_account": "drop"
},
"state_file": "formance2blnk-state/hybrid.json"
}
Recipes¶
Migrate several Formance ledgers into one Blnk ledger¶
{
"formance": { "url": "...", "ledgers": ["eu", "us"] },
"mapping": { "default_ledger": "Customers" }
}
References include the Formance ledger name, so transactions from different ledgers never collide. Balances stay separate per Formance ledger.
One Blnk ledger per account prefix¶
{
"mapping": {
"rules": [
{ "match": "world", "indicator": "@World" },
{ "match": "*:**", "ledger": "{1}" }
]
}
}
users:1:wallet → ledger users, merchants:9 → ledger merchants. The explicit world rule is needed because ** matches zero segments, so *:** would otherwise also catch world (rules are checked before the world_indicator default).
Run in Docker with a mounted state directory¶
docker run --rm \
-v "$PWD:/work" \
-e BLNK_API_KEY \
ghcr.io/otyang/formance2blnk:latest migrate -config /work/formance2blnk.json -state /work/state/state.json
Gate a pipeline on reconciliation¶
formance2blnk migrate -log-format json
formance2blnk reconcile -volumes -format json -out report.json
reconcile exits with code 2 on any difference, failing the job.
Re-run with one-at-a-time writes¶
If your Blnk deployment does not support atomic bulk writes, set "migration": { "batch_size": 1 }. Each Formance posting is then sent individually (multi-posting Formance transactions lose atomicity across postings, but references keep re-runs safe).