@ringssol/sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/launch.js ADDED
@@ -0,0 +1,92 @@
1
+ import { SOL } from "./chain.js";
2
+ const DONE = ["done", "failed", "refunded"];
3
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
4
+ // Beyond the first buy and any shield fee, a launch costs the rent of the coin's accounts and its network fees.
5
+ const MAX_COSTS = 60000000n;
6
+ const lamportsText = (v) => `${v / 1000000000n}.${(v % 1000000000n).toString().padStart(9, "0")}`;
7
+ export class Launch {
8
+ api;
9
+ payer;
10
+ constructor(api, payer) {
11
+ this.api = api;
12
+ this.payer = payer;
13
+ }
14
+ /** Whether a coin launched on Rings in the last few days shields this name or ticker, and the fee to launch over it. */
15
+ async shield(name, symbol) {
16
+ const r = await this.api.get(`/api/launch/shield?name=${encodeURIComponent(name)}&symbol=${encodeURIComponent(symbol)}`);
17
+ return { shield: r.shield, fee: BigInt(r.fee), hours: r.hours };
18
+ }
19
+ /** Launches a coin, paid privately, and waits until it trades. Rings launches it from a one-time key: nothing on chain names you. */
20
+ async create(input, opts = {}) {
21
+ const firstBuy = input.firstBuy ?? 0n;
22
+ const made = await this.api.post("/api/launch/jobs", {
23
+ mode: input.mode ?? "standard",
24
+ name: input.name,
25
+ symbol: input.symbol,
26
+ description: input.description ?? "",
27
+ website: input.website ?? "",
28
+ x: input.x ?? "",
29
+ telegram: input.telegram ?? "",
30
+ image: Buffer.from(input.image).toString("base64"),
31
+ pair: input.pair ?? "SOL",
32
+ venue: input.venue ?? "meteora",
33
+ firstBuy: lamportsText(firstBuy),
34
+ deliverTo: this.payer.address,
35
+ holdersBps: input.holdersBps ?? 0,
36
+ creatorBps: input.creatorBps ?? 0,
37
+ burnBps: input.burnBps ?? 0,
38
+ overShield: input.overShield ?? false,
39
+ });
40
+ const price = BigInt(made.price);
41
+ const shield = input.overShield ? (await this.shield(input.name, input.symbol)).fee : 0n;
42
+ if (price < firstBuy || price > firstBuy + shield + MAX_COSTS)
43
+ throw new Error(`Rings asked ${price} lamports for this launch, more than expected. Nothing was paid.`);
44
+ const have = await this.payer.holds(SOL);
45
+ if (have < price)
46
+ throw new Error(`The private balance holds ${have} lamports, the launch costs ${price}. Nothing was paid.`);
47
+ const sent = await this.payer.pay(made.payTo, SOL, price);
48
+ for (let i = 1;; i++) {
49
+ try {
50
+ await this.api.post(`/api/launch/jobs/${made.id}`, { action: "paid", signature: sent.signature, slot: String(sent.slot) });
51
+ break;
52
+ }
53
+ catch (e) {
54
+ if (e.status !== 409 || i >= 30)
55
+ throw e;
56
+ await sleep(1500);
57
+ }
58
+ }
59
+ return this.wait(made.id, opts.timeoutMs);
60
+ }
61
+ async status(id) {
62
+ const j = await this.api.get(`/api/launch/jobs/${id}`);
63
+ return { id, state: j.state, error: j.error, mint: j.mint, tokens: j.tokens == null ? null : BigInt(j.tokens), launchSignature: j.launchSig };
64
+ }
65
+ async wait(id, timeoutMs = 300_000) {
66
+ const end = Date.now() + timeoutMs;
67
+ for (;;) {
68
+ const s = await this.status(id);
69
+ if (DONE.includes(s.state) || Date.now() > end)
70
+ return s;
71
+ await sleep(3000);
72
+ }
73
+ }
74
+ /** Before the coin exists, a paid launch can be called off: the payment comes back to the private balance. */
75
+ async refund(id) {
76
+ await this.api.post(`/api/launch/jobs/${id}`, { action: "refund" });
77
+ }
78
+ /** The creator's share of a coin's fees, when this account launched it. Anyone else is only told it isn't theirs. */
79
+ async rewards(mint) {
80
+ const r = await this.api.get(`/api/launch/rewards/${mint}`);
81
+ if (!r.isCreator)
82
+ return { isCreator: false };
83
+ const big = (k) => (typeof r[k] === "string" ? BigInt(r[k]) : undefined);
84
+ return { ...r, claimable: big("claimable"), claiming: big("claiming"), claimed: big("claimed"), minClaim: big("minClaim") };
85
+ }
86
+ /** Asks for the creator's share; Rings pays it into the private balance kept at launch, within minutes. */
87
+ async claim(mint) {
88
+ const r = await this.api.post(`/api/launch/rewards/${mint}`, { action: "claim" });
89
+ return { id: r.id, lamports: BigInt(r.lamports) };
90
+ }
91
+ }
92
+ //# sourceMappingURL=launch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"launch.js","sourceRoot":"","sources":["../src/launch.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAGjC,MAAM,IAAI,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC;AAC5C,MAAM,KAAK,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AACpE,gHAAgH;AAChH,MAAM,SAAS,GAAG,SAAW,CAAC;AAuD9B,MAAM,YAAY,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,WAAc,IAAI,CAAC,CAAC,GAAG,WAAc,CAAC,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC;AAEhH,MAAM,OAAO,MAAM;IAEE;IACA;IAFnB,YACmB,GAAQ,EACR,KAAY;QADZ,QAAG,GAAH,GAAG,CAAK;QACR,UAAK,GAAL,KAAK,CAAO;IAC5B,CAAC;IAEJ,wHAAwH;IACxH,KAAK,CAAC,MAAM,CAAC,IAAY,EAAE,MAAc;QACvC,MAAM,CAAC,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,GAAG,CAA2D,2BAA2B,kBAAkB,CAAC,IAAI,CAAC,WAAW,kBAAkB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACnL,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC;IAClE,CAAC;IAED,q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AAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QAC3F,OAAO,EAAE,GAAG,CAAC,EAAE,SAAS,EAAE,GAAG,CAAC,WAAW,CAAC,EAAE,QAAQ,EAAE,GAAG,CAAC,UAAU,CAAC,EAAE,OAAO,EAAE,GAAG,CAAC,SAAS,CAAC,EAAE,QAAQ,EAAE,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;IAC9H,CAAC;IAED,2GAA2G;IAC3G,KAAK,CAAC,KAAK,CAAC,IAAY;QACtB,MAAM,CAAC,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,IAAI,CAAmC,uBAAuB,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC;QACpH,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC;IACpD,CAAC;CACF"}
@@ -0,0 +1,48 @@
1
+ import { Api } from "./api.js";
2
+ import { type Client, type Network, type Sent } from "./chain.js";
3
+ import { Dex } from "./dex.js";
4
+ import { Launch } from "./launch.js";
5
+ import { Bridge } from "./bridge.js";
6
+ export interface ConnectOptions {
7
+ /** The wallet that owns the account: its 64-byte Solana secret key, as bytes or base58. It never leaves this process. */
8
+ secretKey: Uint8Array | string;
9
+ /** Your Helius API key: the private balance is read and proven through it. Rings never sees it. */
10
+ heliusKey: string;
11
+ network?: Network;
12
+ /** The Rings API. A devnet copy of Rings runs elsewhere; mainnet is rings.run. */
13
+ api?: string;
14
+ }
15
+ export interface Holding {
16
+ mint: string;
17
+ amount: bigint;
18
+ }
19
+ /** A Rings account, signed in with its wallet's key: the same account and private balance the wallet has on rings.run. */
20
+ export declare class Rings {
21
+ readonly wallet: string;
22
+ private readonly seed;
23
+ private readonly account;
24
+ readonly api: Api;
25
+ readonly client: Client;
26
+ readonly network: Network;
27
+ readonly dex: Dex;
28
+ readonly launch: Launch;
29
+ readonly bridge: Bridge;
30
+ private constructor();
31
+ static connect(o: ConnectOptions): Promise<Rings>;
32
+ /** The private address other Rings accounts pay this one at. */
33
+ get address(): string;
34
+ /** The account key: the public address that owns the private balance and pays its network fees. */
35
+ get accountKey(): string;
36
+ /** What the private balance holds; `mints` are looked up even when the balance holds none yet. SOL is always listed. */
37
+ balance(mints?: string[]): Promise<Holding[]>;
38
+ /** Coins from the wallet into the private balance. The deposit itself is public: it shows the wallet paying in. */
39
+ add(mint: string, amount: bigint): Promise<Sent>;
40
+ /** Pays another Rings account from the private balance. Nothing on chain links the two. */
41
+ send(mint: string, amount: bigint, to: string): Promise<Sent>;
42
+ /** Coins out of the private balance to a public address, the wallet by default. */
43
+ withdraw(mint: string, amount: bigint, to?: string): Promise<Sent>;
44
+ decimals(mint: string): Promise<number>;
45
+ private payPrivately;
46
+ private mustHold;
47
+ private keepFees;
48
+ }
package/dist/rings.js ADDED
@@ -0,0 +1,115 @@
1
+ import { ed25519 } from "@noble/curves/ed25519";
2
+ import { address } from "@solana/kit";
3
+ import { ShieldedAddress } from "@heliuslabs/spr";
4
+ import { Api } from "./api.js";
5
+ import { b64, base58, fromB64, fromBase58, utf8 } from "./codec.js";
6
+ import { accountKeys, keyHostOf, keyMessage, loginMessage } from "./keys.js";
7
+ import { FEE_FLOAT, SOL, addressOf, connect, decimalsOf, deposit, keypairOf, privateTransfer, publicSol, sendSol, sync, withdraw } from "./chain.js";
8
+ import { Dex } from "./dex.js";
9
+ import { Launch } from "./launch.js";
10
+ import { Bridge } from "./bridge.js";
11
+ /** A Rings account, signed in with its wallet's key: the same account and private balance the wallet has on rings.run. */
12
+ export class Rings {
13
+ wallet;
14
+ seed;
15
+ account;
16
+ api;
17
+ client;
18
+ network;
19
+ dex;
20
+ launch;
21
+ bridge;
22
+ constructor(wallet, seed, account, api, client, network) {
23
+ this.wallet = wallet;
24
+ this.seed = seed;
25
+ this.account = account;
26
+ this.api = api;
27
+ this.client = client;
28
+ this.network = network;
29
+ const payer = {
30
+ address: this.address,
31
+ wallet,
32
+ holds: async (mint) => (await this.balance([mint])).find((h) => h.mint === mint)?.amount ?? 0n,
33
+ pay: (to, mint, amount) => this.payPrivately(to, mint, amount),
34
+ };
35
+ this.dex = new Dex(api, network, payer);
36
+ this.launch = new Launch(api, payer);
37
+ this.bridge = new Bridge(api, network, payer);
38
+ }
39
+ static async connect(o) {
40
+ const secret = typeof o.secretKey === "string" ? fromBase58(o.secretKey) : o.secretKey;
41
+ if (secret.length !== 64)
42
+ throw new Error("secretKey must be a 64-byte Solana secret key");
43
+ const seed = secret.slice(0, 32);
44
+ const wallet = base58(ed25519.getPublicKey(seed));
45
+ if (wallet !== base58(secret.slice(32)))
46
+ throw new Error("secretKey's two halves don't match");
47
+ const network = o.network ?? "mainnet";
48
+ const api = new Api(o.api ?? "https://rings.run");
49
+ const keySignature = ed25519.sign(utf8(keyMessage(keyHostOf(api.host), wallet)), seed);
50
+ const keys = accountKeys(wallet, keySignature);
51
+ keySignature.fill(0);
52
+ // The wallet and the account key both sign in: Rings binds only an account key its holder signed for.
53
+ const { nonce, issuedAt } = await api.post("/api/auth/nonce");
54
+ const message = loginMessage({ domain: api.host, wallet, nonce, issuedAt, x25519: b64(keys.x25519Public), ed25519: b64(keys.edPublic), account: addressOf(keys.account) });
55
+ await api.post("/api/auth/verify", {
56
+ message,
57
+ signature: base58(ed25519.sign(utf8(message), seed)),
58
+ accountSignature: base58(ed25519.sign(utf8(message), keys.account)),
59
+ });
60
+ return new Rings(wallet, seed, keys.account, api, await connect(network, o.heliusKey), network);
61
+ }
62
+ /** The private address other Rings accounts pay this one at. */
63
+ get address() {
64
+ return b64(keypairOf(this.account).shieldedAddress().toBytes());
65
+ }
66
+ /** The account key: the public address that owns the private balance and pays its network fees. */
67
+ get accountKey() {
68
+ return addressOf(this.account);
69
+ }
70
+ /** What the private balance holds; `mints` are looked up even when the balance holds none yet. SOL is always listed. */
71
+ async balance(mints = []) {
72
+ const { wallet } = await sync(this.client, this.account, mints.map((m) => address(m)));
73
+ const held = wallet.balances(true).map((b) => ({ mint: String(b.mint), amount: b.amount }));
74
+ for (const m of [SOL, ...mints])
75
+ if (!held.some((h) => h.mint === m))
76
+ held.push({ mint: m, amount: 0n });
77
+ return held;
78
+ }
79
+ /** Coins from the wallet into the private balance. The deposit itself is public: it shows the wallet paying in. */
80
+ async add(mint, amount) {
81
+ await this.keepFees();
82
+ return deposit(this.client, { fromSeed: this.seed, to: keypairOf(this.account).shieldedAddress(), mint: address(mint), amount });
83
+ }
84
+ /** Pays another Rings account from the private balance. Nothing on chain links the two. */
85
+ async send(mint, amount, to) {
86
+ return this.payPrivately(to, mint, amount);
87
+ }
88
+ /** Coins out of the private balance to a public address, the wallet by default. */
89
+ async withdraw(mint, amount, to = this.wallet) {
90
+ await this.mustHold(mint, amount);
91
+ await this.keepFees();
92
+ return withdraw(this.client, { seed: this.account, to: address(to), mint: address(mint), amount });
93
+ }
94
+ decimals(mint) {
95
+ return decimalsOf(this.client, mint);
96
+ }
97
+ async payPrivately(to, mint, amount) {
98
+ await this.mustHold(mint, amount);
99
+ await this.keepFees();
100
+ return privateTransfer(this.client, { seed: this.account, to: ShieldedAddress.fromBytes(fromB64(to)), mint: address(mint), amount });
101
+ }
102
+ async mustHold(mint, amount) {
103
+ const have = (await this.balance([mint])).find((h) => h.mint === mint)?.amount ?? 0n;
104
+ if (have < amount)
105
+ throw new Error(`The private balance holds ${have} of ${mint}, this needs ${amount}. Nothing was sent.`);
106
+ }
107
+ // The account key pays the network fees of private transactions: refilled from the wallet when it runs low.
108
+ async keepFees() {
109
+ const key = addressOf(this.account);
110
+ const have = await publicSol(this.client, key);
111
+ if (have < FEE_FLOAT / 2n)
112
+ await sendSol(this.client, this.seed, key, FEE_FLOAT - have);
113
+ }
114
+ }
115
+ //# sourceMappingURL=rings.js.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AAO,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;IACvI,CAAC;IAEO,KAAK,CAAC,QAAQ,CAAC,IAAY,EAAE,MAAc;QACjD,MAAM,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,EAAE,MAAM,IAAI,EAAE,CAAC;QACrF,IAAI,IAAI,GAAG,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,IAAI,OAAO,IAAI,gBAAgB,MAAM,qBAAqB,CAAC,CAAC;IAC9H,CAAC;IAED,4GAA4G;IACpG,KAAK,CAAC,QAAQ;QACpB,MAAM,GAAG,GAAG,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpC,MAAM,IAAI,GAAG,MAAM,SAAS,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAC/C,IAAI,IAAI,GAAG,SAAS,GAAG,EAAE;YAAE,MAAM,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE,SAAS,GAAG,IAAI,CAAC,CAAC;IAC1F,CAAC;CACF"}
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@ringssol/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Private balances, swaps, launches and bridging on Rings, from Node.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "src"
18
+ ],
19
+ "engines": {
20
+ "node": ">=20"
21
+ },
22
+ "scripts": {
23
+ "build": "tsc",
24
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.dev.json",
25
+ "test": "node --import tsx --test test/*.test.ts"
26
+ },
27
+ "dependencies": {
28
+ "@heliuslabs/spr": "0.9.0-alpha",
29
+ "@noble/curves": "^1.9.7",
30
+ "@noble/hashes": "^1.8.0",
31
+ "@solana/kit": "8.3.0"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^24",
35
+ "tsx": "^4.20.6",
36
+ "typescript": "^5.9.3"
37
+ },
38
+ "homepage": "https://rings.run",
39
+ "repository": "github:RingsSolana/rings-sdk",
40
+ "keywords": [
41
+ "solana",
42
+ "privacy",
43
+ "rings",
44
+ "swap"
45
+ ]
46
+ }
package/src/api.ts ADDED
@@ -0,0 +1,44 @@
1
+ export class RingsError extends Error {
2
+ constructor(
3
+ message: string,
4
+ readonly status: number,
5
+ readonly body?: unknown,
6
+ ) {
7
+ super(message);
8
+ this.name = "RingsError";
9
+ }
10
+ }
11
+
12
+ const json = (value: unknown) => JSON.stringify(value, (_, v) => (typeof v === "bigint" ? v.toString() : v));
13
+
14
+ /** The Rings API, holding the session cookie the way a browser would. */
15
+ export class Api {
16
+ private cookie = "";
17
+
18
+ constructor(readonly base: string) {}
19
+
20
+ get host() {
21
+ return new URL(this.base).host;
22
+ }
23
+
24
+ get<T>(path: string): Promise<T> {
25
+ return this.call<T>("GET", path);
26
+ }
27
+
28
+ post<T>(path: string, body: unknown = {}): Promise<T> {
29
+ return this.call<T>("POST", path, body);
30
+ }
31
+
32
+ private async call<T>(method: string, path: string, body?: unknown): Promise<T> {
33
+ const res = await fetch(this.base + path, {
34
+ method,
35
+ headers: { "content-type": "application/json", ...(this.cookie && { cookie: this.cookie }) },
36
+ body: body === undefined ? undefined : json(body),
37
+ });
38
+ const cookie = res.headers.get("set-cookie");
39
+ if (cookie) this.cookie = cookie.split(";")[0]!;
40
+ const data = (await res.json().catch(() => ({}))) as { error?: string };
41
+ if (!res.ok) throw new RingsError(data.error ?? `Rings answered ${res.status}`, res.status, data);
42
+ return data as T;
43
+ }
44
+ }
package/src/bridge.ts ADDED
@@ -0,0 +1,175 @@
1
+ import type { Api } from "./api.js";
2
+ import { SOL, type Network } from "./chain.js";
3
+ import type { Payer } from "./dex.js";
4
+
5
+ const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
6
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
7
+ // A bridge-out's own costs on Solana (its accounts and fees); what they don't use comes back.
8
+ const MAX_COSTS = 50_000_000n;
9
+
10
+ export interface BridgeOutInput {
11
+ /** What leaves the private balance. */
12
+ coin: "SOL" | "USDC";
13
+ amount: bigint;
14
+ /** The chain it goes to, as listed by routes(). */
15
+ toChain: number | string;
16
+ /** The coin it arrives as, by its address on that chain. */
17
+ toToken: string;
18
+ /** Your address on that chain. */
19
+ to: string;
20
+ slippageBps?: number;
21
+ }
22
+
23
+ export interface BridgeInInput {
24
+ /** The chain it comes from, as listed by routes(). */
25
+ fromChain: number | string;
26
+ fromToken: string;
27
+ amount: bigint;
28
+ /** EVM chains: the wallet that sends it. */
29
+ from?: string;
30
+ /** NEAR and Zcash: where it goes back if the bridge can't deliver. */
31
+ refundTo?: string;
32
+ /** What arrives in the private balance. */
33
+ arrive: "SOL" | "USDC";
34
+ slippageBps?: number;
35
+ }
36
+
37
+ export interface BridgeQuote {
38
+ toAmount: bigint;
39
+ toAmountMin?: bigint;
40
+ seconds: number | null;
41
+ feesUsd: number;
42
+ gasUsd: number;
43
+ tool?: string;
44
+ }
45
+
46
+ export interface BridgeIn {
47
+ id: string;
48
+ /** The one-time Solana key the coins arrive at before Rings moves them into the private balance. */
49
+ key: string;
50
+ /** EVM chains: the transaction for your wallet there to send, after the approval when the coin needs one. */
51
+ tx?: unknown;
52
+ approval?: unknown;
53
+ /** NEAR and Zcash: send exactly this, to this address, before the deadline. */
54
+ deposit?: { address: string; memo?: string | null; amount: string; symbol: string; decimals: number; deadline: string };
55
+ quote: BridgeQuote;
56
+ }
57
+
58
+ export interface BridgeState {
59
+ id: string;
60
+ state: string;
61
+ error: string | null;
62
+ [field: string]: unknown;
63
+ }
64
+
65
+ const quoteOf = (q: { toAmount?: string; toAmountMin?: string; durationS?: number; feesUsd?: number; gasUsd?: number; tool?: string }): BridgeQuote => ({
66
+ toAmount: BigInt(q.toAmount ?? "0"),
67
+ toAmountMin: q.toAmountMin ? BigInt(q.toAmountMin) : undefined,
68
+ seconds: q.durationS ?? null,
69
+ feesUsd: q.feesUsd ?? 0,
70
+ gasUsd: q.gasUsd ?? 0,
71
+ tool: q.tool,
72
+ });
73
+
74
+ export class Bridge {
75
+ constructor(
76
+ private readonly api: Api,
77
+ private readonly network: Network,
78
+ private readonly payer: Payer,
79
+ ) {}
80
+
81
+ /** The chains and coins Rings bridges from and to. */
82
+ routes(): Promise<{ chains: unknown[]; dests: string[] }> {
83
+ return this.api.get("/api/dex/bridge");
84
+ }
85
+
86
+ async quoteOut(o: BridgeOutInput): Promise<BridgeQuote> {
87
+ return quoteOf(await this.api.post("/api/dex/bridge/out/quote", this.outBody(o)));
88
+ }
89
+
90
+ /** Sends coins from the private balance to another chain, paid privately, and waits until they're delivered there. */
91
+ async out(o: BridgeOutInput, opts: { timeoutMs?: number } = {}): Promise<BridgeState> {
92
+ const made = await this.api.post<{ id: string; payTo: string; payments: { mint: string; amount: string }[]; fee?: string }>("/api/dex/bridge/out", {
93
+ ...this.outBody(o),
94
+ deliverTo: this.payer.address,
95
+ });
96
+ const total = new Map<string, bigint>();
97
+ for (const p of made.payments) total.set(p.mint, (total.get(p.mint) ?? 0n) + BigInt(p.amount));
98
+ const sol = total.get(SOL) ?? 0n;
99
+ const costs = sol - (o.coin === "SOL" ? o.amount : 0n);
100
+ const fee = BigInt(made.fee ?? "0");
101
+ // USDC: the one coin besides SOL, exactly the amount (devnet's USDC is a test mint of its own).
102
+ const coins = [...total.keys()].filter((m) => m !== SOL);
103
+ const coinOk = o.coin === "SOL" ? coins.length === 0 : coins.length === 1 && total.get(coins[0]!) === o.amount && (this.network !== "mainnet" || coins[0] === USDC);
104
+ if (!coinOk || costs < 0n || costs > fee + MAX_COSTS) throw new Error("Rings asked for an unexpected payment. Nothing was paid.");
105
+ for (const [m, amount] of total) {
106
+ const have = await this.payer.holds(m);
107
+ if (have < amount) throw new Error(`The private balance holds ${have} of ${m}, the payment needs ${amount}. Nothing was paid.`);
108
+ }
109
+ const paid: { signature: string; slot: string }[] = [];
110
+ for (const p of [...made.payments].sort((a, b) => Number(b.mint === SOL) - Number(a.mint === SOL))) {
111
+ const sent = await this.payer.pay(made.payTo, p.mint, BigInt(p.amount));
112
+ paid.push({ signature: sent.signature, slot: String(sent.slot) });
113
+ }
114
+ for (let i = 1; ; i++) {
115
+ try {
116
+ await this.api.post(`/api/dex/bridge/out/${made.id}`, { action: "paid", payments: paid });
117
+ break;
118
+ } catch (e) {
119
+ if ((e as { status?: number }).status !== 409 || i >= 30) throw e;
120
+ await sleep(1500);
121
+ }
122
+ }
123
+ return this.wait(`/api/dex/bridge/out/${made.id}`, ["done", "delivered", "refunded", "failed", "expired"], opts.timeoutMs);
124
+ }
125
+
126
+ outStatus(id: string): Promise<BridgeState> {
127
+ return this.api.get<BridgeState>(`/api/dex/bridge/out/${id}`).then((s) => ({ ...s, id }));
128
+ }
129
+
130
+ /**
131
+ * Starts bringing coins in from another chain. Nothing moves yet: send `tx` from your wallet on that chain (or the
132
+ * deposit, from NEAR or Zcash), then call sent() with its hash.
133
+ */
134
+ async in(i: BridgeInInput): Promise<BridgeIn> {
135
+ const r = await this.api.post<BridgeIn & { quote: Parameters<typeof quoteOf>[0] }>("/api/dex/bridge", {
136
+ fromChain: i.fromChain,
137
+ fromToken: i.fromToken,
138
+ amount: i.amount,
139
+ fromAddress: i.from,
140
+ refundTo: i.refundTo,
141
+ dest: i.arrive,
142
+ slippageBps: i.slippageBps ?? 50,
143
+ deliverTo: this.payer.address,
144
+ });
145
+ return { ...r, quote: quoteOf(r.quote) };
146
+ }
147
+
148
+ /** Tells Rings the source chain's transaction went out, so it follows it. */
149
+ async sent(id: string, txHash: string): Promise<void> {
150
+ await this.api.post(`/api/dex/bridge/${id}`, { action: "sent", txHash });
151
+ }
152
+
153
+ inStatus(id: string): Promise<BridgeState> {
154
+ return this.api.get<BridgeState>(`/api/dex/bridge/${id}`);
155
+ }
156
+
157
+ /** Waits until a bridge-in has reached the private balance, or ended otherwise. */
158
+ waitIn(id: string, timeoutMs?: number): Promise<BridgeState> {
159
+ return this.wait(`/api/dex/bridge/${id}`, ["done", "failed", "refunded", "expired"], timeoutMs);
160
+ }
161
+
162
+ private outBody(o: BridgeOutInput) {
163
+ return { coin: o.coin, amount: o.amount, toChain: o.toChain, toToken: o.toToken, toAddress: o.to, slippageBps: o.slippageBps ?? 50 };
164
+ }
165
+
166
+ private async wait(path: string, done: string[], timeoutMs = 900_000): Promise<BridgeState> {
167
+ const end = Date.now() + timeoutMs;
168
+ const id = path.split("/").pop()!;
169
+ for (;;) {
170
+ const s = { ...(await this.api.get<BridgeState>(path)), id };
171
+ if (done.includes(s.state) || Date.now() > end) return s;
172
+ await sleep(5000);
173
+ }
174
+ }
175
+ }