Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ jobs:
workspaces: |
contracts/stellar-cctp-wrapper -> target
contracts/stellar-cctp-wrapper-v2 -> target
contracts/stellar-batch-router -> target

# v1 is the retired wrapper; v2 below inherits its suite. These tests cover the fee
# arithmetic, the parameter ceilings a compromised admin cannot exceed, and the no-hang
Expand All @@ -115,6 +116,9 @@ jobs:
# v2 is the forwarding wrapper (docs/forwarding-wrapper.md), live on mainnet. It inherits v1's
# suite and adds the tests that bound the one new risk: Circle charges the whole `max_fee`.
- run: cargo test --manifest-path contracts/stellar-cctp-wrapper-v2/Cargo.toml
# Batch router: many transfers through the v2 wrapper in one signature, all or nothing. Runs
# against the wrapper WASM fetched from mainnet (contracts/stellar-batch-router/wasm/).
- run: cargo test --manifest-path contracts/stellar-batch-router/Cargo.toml
- run: cargo test --manifest-path contracts/stellar-soroban/Cargo.toml

evm:
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ contracts/stellar-cctp-wrapper/target/
contracts/stellar-cctp-wrapper/test_snapshots/
contracts/stellar-cctp-wrapper-v2/target/
contracts/stellar-cctp-wrapper-v2/test_snapshots/
contracts/stellar-batch-router/target/
contracts/stellar-batch-router/test_snapshots/

# solana
test-ledger/
Expand Down
26 changes: 26 additions & 0 deletions apps/docs/content/docs/changelog.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ description: What changed in the Xebra API and SDK, newest first.

**API**:

- Market-maker rebalances: `GET /v1/quote` and `POST /v1/transfers` take an optional
`product`, `"transfer"` (the default) or `"rebalance"`. A rebalance with an API key that Xebra
has set up for market-maker rebalances is priced at 0.01% capped at 2 USDC a move, plus
0.01 USDC: 100,000 USDC costs 2.01 instead of 10.01, 1,000 USDC still 0.11. Without such a key it
is priced as a transfer. Every other price is
unchanged. See [Fees](/docs/concepts/fees#market-maker-rebalances).
- Quotes (and the quote in a build) carry `feeRule`, the fee rule that priced Xebra's fee:
`"default"`, `"rebalance-capped"`, or null where a Xebra contract prices it on-chain (Stellar
sources, EVM sources through Xebra's contract).

- Every route without a Xebra fee contract carries Xebra's fee: 0.01 USDC plus 0.01% of the
amount, whether the transfer arrives by itself (Circle's Forwarding Service, or Xebra's relayer
into Stellar) or the recipient claims it. `fees.xebra` shows it; `amount` is what leaves the wallet
Expand All @@ -26,6 +36,22 @@ description: What changed in the Xebra API and SDK, newest first.

**SDK**, `@xebra/sdk`:

- CommonJS code on Node 22.12 or later can `require("@xebra/sdk")` and its subpaths; before, only
`import` resolved them.
- `createRebalancer({ oneClick: { jwt } })` (additive): a 1Click partner JWT works for the
withdrawal, as an API key does. It is sent as `Authorization: Bearer`.
- `createRebalancer` asks for the rebalance price: its quotes and builds send
`product: "rebalance"`, and with a market-maker API key on the Xebra client
(`createXebraClient({ apiKey })`) a move costs Xebra 0.01% capped at 2 USDC, plus 0.01. `estimate` returns `feeRule`.
- `QuoteRequest` and `TransferRequest` take `product`; `Quote` has `feeRule` (optional, so answers
from an older server still parse). `ProductSchema`.
- `@xebra/sdk/core` (additive): the fee table, `FEE_TABLE`, and the function that prices from it,
`priceFee(amount, { product, partner, from, to })`, which returns the fee and the rule's id. Also
`feeRuleFor`, `feeUnder`, `amountForBurnUnder`, `checkFeeTable`, and `withRebalancePartners`,
which adds the market-maker price for the key ids a server names (the shipped table names none). `flatFeeFor` and
`amountForBurn` now price through the table's default rule, with the same results.
- The intents router's `buildDeposit` takes `product`.

- `planEvmFee` takes `xebraFee`; `FeePlan` gains `burn`. `XEBRA_FLAT_FEE`, `flatFeeFor`,
`flatFeeKind`, `CLAIM_ONLY_DOMAINS`; `buildEvmFeeStep`, `buildAptosFeeStep`.
- `TransferStep.id` can be `"fee"`; `UnsignedTx` can be `aptos_call`.
Expand Down
21 changes: 21 additions & 0 deletions apps/docs/content/docs/concepts/fees.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,27 @@ smallest amount is about 1.0102.
Out of Arc, while Xebra's fee contract there is switched on for the site, the contract's own rule
applies, the same as Stellar's above, and there is no flat fee.

### Market-maker rebalances

A market maker moving its own USDC between chains (the SDK's
[rebalancer](/docs/sdk/intents)) pays **0.01% capped at 2 USDC a move, plus 0.01 USDC**, on these
same routes. It is never free.

```text
xebra = 0.01 + min(0.01% × amount, 2)
```

The capped price needs both: the request says `product: "rebalance"` (on `GET /v1/quote` and
`POST /v1/transfers`), and it carries an [API key](/docs/guides/api-keys) that Xebra has set up
for market-maker rebalances. Ask for that when you ask for the key. A rebalance without such a key,
including one sent with an ordinary integration key, is priced as any other transfer. 100,000 USDC costs 2.01 instead of 10.01; up to
20,000 USDC the two prices are the same.

Every quote names the rule that priced Xebra's fee in `feeRule` (`"default"` or
`"rebalance-capped"`; null where a Xebra contract prices it), and the build charges the fee the
same request is quoted. Pass `maxTotalFee` to refuse a build whose fees rose above what you were
shown.

## Circle's delivery fee

Circle's Forwarding Service charges for minting on the destination and paying the gas there. It
Expand Down
7 changes: 5 additions & 2 deletions apps/docs/content/docs/guides/api-keys.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@ own, higher limit and is not counted with everyone else's.
| No key | 60 requests | The calling address |
| With a key | 600 requests | The key |

Both limits apply to every `/v1` endpoint. A key changes the limit and nothing else: the API stays
non-custodial, still builds unsigned transactions, and never asks for or accepts a private key.
Both limits apply to every `/v1` endpoint. A key changes the limit. A key that Xebra sets up for a
market maker also changes the price of that market maker's rebalances (`product: "rebalance"`):
0.01% capped at 2 USDC a move, plus 0.01 (see [Fees](/docs/concepts/fees#market-maker-rebalances)).
Say so when you ask for the key; other keys pay the ordinary price. Nothing else: the API stays non-custodial,
still builds unsigned transactions, and never asks for or accepts a private key.

## Get a key

Expand Down
26 changes: 23 additions & 3 deletions apps/docs/content/docs/sdk/intents.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import { createXebraClient } from "@xebra/sdk";
import { createRebalancer } from "@xebra/sdk/intents";

const rb = createRebalancer({
xebra: createXebraClient(),
// A Xebra market-maker key earns the rebalance price (below).
xebra: createXebraClient({ apiKey: "xk_live_your Xebra key" }),
oneClick: { apiKey: "your 1Click partner key" },
});
```
Expand All @@ -39,6 +40,23 @@ The withdrawal is the only step that needs a 1Click partner API key: `generate-i
`oneClick.apiKey` and only ever sent to 1Click. Quotes, estimates and the deposit step work
without it.

## What Xebra charges

Every quote and burn the rebalancer asks Xebra for says `product: "rebalance"`. With a
[Xebra API key](/docs/guides/api-keys) that Xebra has set up for market-maker rebalances on the
client, Xebra prices it as a rebalance: **0.01% of the amount capped at 2 USDC a move, plus 0.01
USDC**. Without one it is an ordinary transfer, 0.01% plus 0.01 with no cap.

| Move | With a market-maker key | Without |
|---|---|---|
| 100,000 USDC | 2.01 | 10.01 |
| 50,000 USDC | 2.01 | 5.01 |
| 1,000 USDC | 0.11 | 0.11 |

That is Xebra's part of `fees.cctp`; Circle's delivery fee and NEAR Intents' withdrawal are on top.
`estimate` names the rule that priced it in `feeRule`: `"rebalance-capped"` with a key,
`"default"` without. See [Fees](/docs/concepts/fees#market-maker-rebalances).

## The request

`estimate`, `startWithdrawal` and `prepareDeposit` all take the same `RebalanceRequest`.
Expand All @@ -49,8 +67,9 @@ without it.

| Option | Type | Meaning |
|---|---|---|
| `xebra` | `Pick<XebraClient, "routes" \| "quote" \| "createTransfer">` | A client from `createXebraClient()`. Its `routes()` decides whether the route is offered. |
| `xebra` | `Pick<XebraClient, "routes" \| "quote" \| "createTransfer">` | A client from `createXebraClient()`. Its `routes()` decides whether the route is offered; its API key earns the rebalance price. |
| `oneClick.apiKey` | `string` | Your 1Click partner key. Needed to withdraw, and only sent to 1Click. |
| `oneClick.jwt` | `string` | A 1Click partner JWT, sent as `Authorization: Bearer`. Works for the withdrawal in place of `apiKey`. |
| `oneClick.baseUrl` | `string` | Where 1Click answers. Default `https://1click.chaindefuser.com`. |
| `oneClick.referral` | `string` | The distribution-channel tag in NEAR Intents' records. Default `"xebra"`. |
| `fetch` | `typeof fetch` | A fetch to use instead of the global one, for tests or a custom agent. |
Expand Down Expand Up @@ -80,6 +99,7 @@ const e = await rb.estimate(req);

console.log(`${e.amount} out of ${e.to}, ${e.arrives} back on ${e.to}`);
console.log(`withdrawal ${e.fees.withdraw}, CCTP ${e.fees.cctp}, total ${e.fees.total}`);
console.log(`Xebra's fee priced by the ${e.feeRule} rule`);
console.log(`about ${Math.round(e.seconds / 60)} minutes end to end, ${e.better} is cheaper`);

if (e.direct.arrives === null) console.log(`no market maker quotes it: ${e.direct.reason}`);
Expand Down Expand Up @@ -266,7 +286,7 @@ exists, so a fix costs nothing but another call.

`startWithdrawal` and `submitWithdrawal` also refuse to run without a key:

`OneClickError: Withdrawing from NEAR Intents needs a 1Click partner API key (oneClick.apiKey).`,
`OneClickError: Withdrawing from NEAR Intents needs a 1Click partner API key (oneClick.apiKey or oneClick.jwt).`,
with `status` `0`. Nothing is signed; the withdrawal cannot go ahead without the partner key that
`generate-intent` and `submit-intent` require. `estimate` and `prepareDeposit` do not need it.

Expand Down
22 changes: 22 additions & 0 deletions apps/web/app/api/sui-stellar/last-burn/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { notFound, suiStellarEnabled } from "../../../../lib/sui-stellar/config";
import { SUI_ADDRESS, lastBurn } from "../../../../lib/sui-stellar/last-burn";

/**
* The newest CCTP burn a Sui address has sent: `{ burn: { digest, destinationDomain } | null }`.
* The Sui page reads it before signing and again after a wallet error, to tell a transfer that went
* through anyway from one that did not. Public data; 502 when Sui does not answer.
*/
export const dynamic = "force-dynamic";

export async function GET(request: Request): Promise<Response> {
if (!suiStellarEnabled()) return notFound();
const sender = new URL(request.url).searchParams.get("sender")?.trim() ?? "";
if (!SUI_ADDRESS.test(sender)) {
return Response.json({ error: "That is not a Sui address." }, { status: 400 });
}
try {
return Response.json({ burn: await lastBurn(sender) });
} catch {
return Response.json({ error: "Sui did not answer" }, { status: 502 });
}
}
109 changes: 81 additions & 28 deletions apps/web/app/sui/sui-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,21 @@ import { ArrowRight, Check } from "../../components/ui/icons";
import { Notice } from "../../components/ui/notice";
import { useWallets } from "../../components/wallet/wallet-provider";
import { reportError } from "../../lib/format-error";
import {
findBurnAfterFailure,
isDeclined,
lastSuiBurn,
sendFailureMessage,
} from "../../lib/sui-send-check";
import { claimOnStellar } from "../../lib/sui-stellar/claim-client";
import { signAndExecuteSui } from "../../lib/wallets/sui";
import { type SuiDestination, SuiDestinationPicker, SuiForwarded, recallSuiEvm } from "./sui-evm";
import {
RecoveredNotice,
type SuiDestination,
SuiDestinationPicker,
SuiForwarded,
recallSuiEvm,
} from "./sui-evm";

/**
* Sui to Stellar: connect a Sui wallet, burn USDC, and watch it arrive.
Expand All @@ -29,6 +41,8 @@ import { type SuiDestination, SuiDestinationPicker, SuiForwarded, recallSuiEvm }
const STORAGE_KEY = "xebra.sui-stellar.digest";
const POLL_MS = 4000;
const DIGEST = /^[1-9A-HJ-NP-Za-km-z]{32,64}$/;
/** Stellar's CCTP domain: the only burn this form follows itself. */
const STELLAR_DOMAIN = 27;

export type Delivery =
| { kind: "idle" }
Expand Down Expand Up @@ -66,12 +80,9 @@ const short = (s: string) => `${s.slice(0, 6)}...${s.slice(-4)}`;

type Problem = { text: string; declined: boolean };

// Wallets word a declined request differently ("User rejected the request", "Cancelled", ...).
const DECLINED = /reject|declin|den(y|ied)|cancel|closed|dismiss/i;

function problem(label: string, err: unknown): Problem {
const text = reportError(label, err);
return { text, declined: DECLINED.test(text) };
return { text, declined: isDeclined(text) };
}

/** The standalone `/sui` page: a heading around the same transfer the bridge screen embeds. */
Expand Down Expand Up @@ -147,8 +158,10 @@ export function SuiTransfer({
}) {
const [amount, setAmount] = useState("");
const [recipient, setRecipient] = useState("");
const [step, setStep] = useState<"idle" | "preparing" | "signing">("idle");
const [step, setStep] = useState<"idle" | "preparing" | "signing" | "checking">("idle");
const [error, setError] = useState<Problem | null>(null);
// The wallet reported an error, but the burn was on Sui anyway.
const [recovered, setRecovered] = useState(false);
const [to, setTo] = useState<SuiDestination>("stellar");
const forwardedKey = [...evmDestinations, ...(solana ? ["solana"] : [])].join(",");

Expand Down Expand Up @@ -208,7 +221,11 @@ export function SuiTransfer({
async function send() {
if (!wallet || !account) return;
setError(null);
setRecovered(false);
setStep("preparing");
// The newest burn before this one, read alongside the build, to recognise this one after an error.
const before = lastSuiBurn(account.address);
let signing = false;
try {
const res = await fetch("/api/sui-stellar/build", {
method: "POST",
Expand All @@ -224,23 +241,53 @@ export function SuiTransfer({
setError({ text: body.error ?? "Could not prepare the transfer.", declined: false });
return;
}
await before;
setStep("signing");
signing = true;
const tx = await signAndExecuteSui(wallet, account, body.transaction);
remember(tx);
setAttest("unknown");
setDelivery({ kind: "idle" });
setDigest(tx);
follow(tx);
} catch (err) {
setError(problem("sui burn failed", err));
const p = problem("sui burn failed", err);
if (!signing) {
setError(p);
return;
}
// Nothing is said until Sui has been checked: the wallet may have sent it before failing.
setStep("checking");
const check = await findBurnAfterFailure(account.address, await before, {
// A decline is checked twice, not once: some wallets report one after sending anyway.
...(p.declined ? { delaysMs: [0, 3000] } : {}),
});
if (check.kind === "found" && check.burn.destinationDomain === STELLAR_DOMAIN) {
setRecovered(true);
follow(check.burn.digest);
return;
}
const outcome = check.kind === "none" ? "none" : "unknown";
setError(
p.declined && outcome === "none"
? p
: { text: sendFailureMessage(p.text, outcome), declined: false },
);
} finally {
setStep("idle");
}
}

function follow(tx: string) {
remember(tx);
setAttest("unknown");
setDelivery({ kind: "idle" });
setDigest(tx);
}

// Follow a burn: ask Circle until it attests, then ask the relayer to finish the mint.
// The loop restarts only when the transfer settles, not on every delivery change: restarting on
// "completing" dropped the relayer's answer and posted the mint a second time.
const completing = useRef(false);
const settled = delivery.kind === "done" || delivery.kind === "stuck";
useEffect(() => {
if (!digest || delivery.kind === "done" || delivery.kind === "stuck") return;
if (!digest || settled) return;
let cancelled = false;
let timer: ReturnType<typeof setTimeout>;

Expand Down Expand Up @@ -310,7 +357,7 @@ export function SuiTransfer({
cancelled = true;
clearTimeout(timer);
};
}, [digest, delivery.kind, relayerEnabled]);
}, [digest, settled, relayerEnabled]);

function startOver() {
remember(null);
Expand All @@ -321,6 +368,7 @@ export function SuiTransfer({
setError(null);
setClaimError(null);
setRecipientSeen(null);
setRecovered(false);
}

async function claim() {
Expand All @@ -339,28 +387,33 @@ export function SuiTransfer({
}

const progress = digest ? (
<Progress
digest={digest}
attest={attest}
delivery={delivery}
relayerEnabled={relayerEnabled}
recipient={recipientSeen}
stellarAddress={stellarAddress}
claiming={claiming}
claimError={claimError}
onClaim={claim}
onConnectStellar={() => openWallets(["stellar"])}
onRetry={() => setDelivery({ kind: "idle" })}
onReset={startOver}
/>
<>
{recovered && <RecoveredNotice className="mb-5" />}
<Progress
digest={digest}
attest={attest}
delivery={delivery}
relayerEnabled={relayerEnabled}
recipient={recipientSeen}
stellarAddress={stellarAddress}
claiming={claiming}
claimError={claimError}
onClaim={claim}
onConnectStellar={() => openWallets(["stellar"])}
onRetry={() => setDelivery({ kind: "idle" })}
onReset={startOver}
/>
</>
) : null;

const burnLabel =
step === "preparing"
? "Preparing"
: step === "signing"
? "Confirm in your wallet"
: "Burn on Sui";
: step === "checking"
? "Checking Sui"
: "Burn on Sui";

const walletSection = (
<WalletSection
Expand Down
Loading
Loading