Skip to content
Merged
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
47 changes: 0 additions & 47 deletions sdk/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,50 +176,3 @@ ILNError.InvoiceNotCancellable = InvoiceNotCancellable;
ILNError.InvalidAddress = InvalidAddress;
ILNError.InvalidTransfer = InvalidTransfer;
ILNError.InsufficientAmount = InsufficientAmount;

/**
* insurance_pool has its own `InsuranceError` enum
* (contracts/insurance_pool/src/lib.rs) whose numeric codes are NOT the same
* as invoice_liquidity's `ContractError` codes above (e.g. code 2 is
* AlreadyClaimed here, but AlreadyFunded there). Issue #461 asked to add
* insurance error codes to `ILNErrorCode` (sdk/src/signers/FreighterSigner.ts)
* — that enum is unrelated (wallet-connection UX codes like WalletNotInstalled/
* UserRejected), so adding contract error codes there would be incorrect.
* This class follows the same dedicated-mapper pattern used for
* GovernanceContractError (sdk/src/methods/governance.ts).
*/
export class InsuranceContractError extends Error {
constructor(message: string, public readonly code?: number) {
super(message);
this.name = "InsuranceContractError";
}

static NotInitialized = class NotInitialized extends InsuranceContractError {
constructor(msg = "Insurance pool not initialized") { super(msg, 1); }
};
static AlreadyClaimed = class AlreadyClaimed extends InsuranceContractError {
constructor(msg = "Claim already processed for this invoice") { super(msg, 2); }
};
static InvalidAmount = class InvalidAmount extends InsuranceContractError {
constructor(msg = "Premium or coverage amount must be positive") { super(msg, 3); }
};
static PoolEmpty = class PoolEmpty extends InsuranceContractError {
constructor(msg = "Insurance pool has no balance available") { super(msg, 4); }
};
static AlreadyInitialized = class AlreadyInitialized extends InsuranceContractError {
constructor(msg = "Insurance pool already initialized") { super(msg, 5); }
};

static fromError(error: unknown): Error {
const match = String(error).match(/Error\(Contract, (\d+)\)/);
if (!match) return error instanceof Error ? error : new Error(String(error));
switch (parseInt(match[1] || "", 10)) {
case 1: return new InsuranceContractError.NotInitialized();
case 2: return new InsuranceContractError.AlreadyClaimed();
case 3: return new InsuranceContractError.InvalidAmount();
case 4: return new InsuranceContractError.PoolEmpty();
case 5: return new InsuranceContractError.AlreadyInitialized();
default: return new InsuranceContractError(`insurance_pool error: ${String(error)}`);
}
}
}
8 changes: 7 additions & 1 deletion sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export type {
CreateProposalResult,
} from "./types/governance.js";

export { ILNError, InsuranceContractError } from "./errors.js";
export { ILNError } from "./errors.js";
export { disputeInvoice, sha256Hex } from "./methods/disputeInvoice.js";
export type { DisputeInvoiceParams, DisputeInvoiceResult } from "./methods/disputeInvoice.js";
export { resolveDispute, DisputeRuling } from "./methods/resolveDispute.js";
Expand Down Expand Up @@ -113,6 +113,12 @@ export { submitInvoicesBatch } from "./methods/submitInvoicesBatch.js";
export type { BatchInvoiceItem, SubmitInvoicesBatchResult } from "./methods/submitInvoicesBatch.js";
export { joinFundQueue, resolveFundQueue } from "./methods/fundQueue.js";
export type { JoinFundQueueResult, ResolveFundQueueResult } from "./methods/fundQueue.js";
export { pause, unpause } from "./methods/adminControls.js";
export type { PauseResult } from "./methods/adminControls.js";
export { transferInvoice } from "./methods/transferInvoice.js";
export type { TransferInvoiceResult } from "./methods/transferInvoice.js";
export { convertInvoiceToken } from "./methods/convertInvoiceToken.js";
export type { ConvertInvoiceTokenResult } from "./methods/convertInvoiceToken.js";
export { TokenRegistry, tokenRegistry } from "./utils/tokenRegistry.js";
export type { TokenInfo, NetworkName } from "./utils/tokenRegistry.js";
export {
Expand Down
85 changes: 85 additions & 0 deletions sdk/src/methods/adminControls.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { vi, describe, it, expect, beforeEach } from "vitest";
import { ILNError } from "../errors.js";
import { ILNClient } from "../client.js";
import { Account } from "@stellar/stellar-sdk";

vi.mock("@stellar/stellar-sdk", async () => {
const actual = await vi.importActual<typeof import("@stellar/stellar-sdk")>("@stellar/stellar-sdk");
return {
...actual,
SorobanRpc: { ...actual.SorobanRpc, assembleTransaction: vi.fn(() => ({ build: () => ({}) })) },
};
});

import { pause, unpause } from "./adminControls.js";

const ADMIN = "GBR7RT4MZTLKK2JNZPOSWVY74VFDR4HVR24QZNH2WONHPQFJZPKHWOTP";
const CONTRACT = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4";
const PASS = "Test SDF Network ; September 2015";

function makeClient(withSigner = true) {
return ILNClient.custom({
rpcUrl: "https://fake-rpc.example.org",
networkPassphrase: PASS,
contractId: CONTRACT,
...(withSigner ? { signer: { publicKey: ADMIN, signTransaction: vi.fn().mockResolvedValue("signed-xdr") } } : {}),
});
}

function mockRpc(overrides: Record<string, unknown> = {}) {
return {
getAccount: vi.fn().mockResolvedValue(new Account(ADMIN, "1")),
simulateTransaction: vi.fn().mockResolvedValue({ result: { retval: {} } }),
sendTransaction: vi.fn().mockResolvedValue({ status: "PENDING", hash: "txPAUSE" }),
...overrides,
};
}

describe("pause", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("submits and returns txHash", async () => {
const client = makeClient(true);
Object.assign(client, { rpc: mockRpc() });

const res = await pause(client);
expect(res.txHash).toBe("txPAUSE");
});

it("throws ILNError.Unauthorized when caller is not admin", async () => {
const client = makeClient(true);
Object.assign(client, {
rpc: mockRpc({
simulateTransaction: vi.fn().mockResolvedValue({ error: "Error(Contract, 5)", _parsed: true }),
}),
});

await expect(pause(client)).rejects.toBeInstanceOf(ILNError.Unauthorized);
});

it("throws when no signer is configured", async () => {
const client = makeClient(false);
await expect(pause(client)).rejects.toThrow("pause requires a client configured with a signer");
});
});

describe("unpause", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("submits and returns txHash", async () => {
const client = makeClient(true);
Object.assign(client, { rpc: mockRpc() });

const res = await unpause(client);
expect(res.txHash).toBe("txPAUSE");
});

it("throws when no signer is configured", async () => {
const client = makeClient(false);
await expect(unpause(client)).rejects.toThrow("unpause requires a client configured with a signer");
});
});
70 changes: 70 additions & 0 deletions sdk/src/methods/adminControls.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// @ts-nocheck
/**
* pause / unpause — SDK helpers for the contract's emergency admin
* controls (issue #470).
*/
import { Contract, SorobanRpc, TransactionBuilder, BASE_FEE } from "@stellar/stellar-sdk";
import type { ILNClient } from "../client.js";
import { ILNError } from "../errors.js";
import { retry } from "../utils/retry.js";

export interface PauseResult {
txHash: string;
}

async function callAdminOp(client: ILNClient, methodName: string): Promise<PauseResult> {
if (!client.signer) {
throw new Error(`${methodName} requires a client configured with a signer (the contract admin)`);
}

const contract = new Contract(client.contractId);
const op = contract.call(methodName);

const account = await retry(() => client.rpc.getAccount(client.signer!.publicKey));
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: client.networkPassphrase,
})
.addOperation(op)
.setTimeout(30)
.build();

const sim = await retry(() => client.rpc.simulateTransaction(tx));
if (SorobanRpc.Api.isSimulationError(sim)) {
throw ILNError.fromError(sim.error);
}

const assembledTx = SorobanRpc.assembleTransaction(tx, sim).build();
const signed = await client.signer.signTransaction(assembledTx, client.rpc);
const sendResult = await retry(() => client.rpc.sendTransaction(signed));
if (sendResult.errorResult) {
throw new Error(`Transaction failed: ${sendResult.errorResult}`);
}

return { txHash: sendResult.hash };
}

/**
* Pause the contract, blocking all state-mutating calls (submissions,
* funding, payments, etc.) until {@link unpause} is called.
*
* Wraps `pause()`. Requires the contract admin's signature —
* `client.signer` must be the stored admin.
*
* @throws {ILNError.Unauthorized} If `client.signer` is not the contract admin
*/
export async function pause(client: ILNClient): Promise<PauseResult> {
return callAdminOp(client, "pause");
}

/**
* Unpause the contract, resuming normal operation.
*
* Wraps `unpause()`. Requires the contract admin's signature —
* `client.signer` must be the stored admin.
*
* @throws {ILNError.Unauthorized} If `client.signer` is not the contract admin
*/
export async function unpause(client: ILNClient): Promise<PauseResult> {
return callAdminOp(client, "unpause");
}
101 changes: 101 additions & 0 deletions sdk/src/methods/convertInvoiceToken.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { vi, describe, it, expect, beforeEach } from "vitest";
import { ILNError } from "../errors.js";
import { ILNClient } from "../client.js";
import { Account } from "@stellar/stellar-sdk";

vi.mock("@stellar/stellar-sdk", async () => {
const actual = await vi.importActual<typeof import("@stellar/stellar-sdk")>("@stellar/stellar-sdk");
return {
...actual,
scValToNative: vi.fn(),
SorobanRpc: { ...actual.SorobanRpc, assembleTransaction: vi.fn(() => ({ build: () => ({}) })) },
};
});

import { scValToNative } from "@stellar/stellar-sdk";
import { convertInvoiceToken } from "./convertInvoiceToken.js";

const mockScValToNative = scValToNative as unknown as vi.Mock;

const FREELANCER = "GBR7RT4MZTLKK2JNZPOSWVY74VFDR4HVR24QZNH2WONHPQFJZPKHWOTP";
const CONTRACT = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4";
const NEW_TOKEN = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA";
const PASS = "Test SDF Network ; September 2015";

function rawInvoice(status: string) {
return {
id: "42",
freelancer: FREELANCER,
payer: FREELANCER,
token: CONTRACT,
amount: "1000",
due_date: "1700000000",
discount_rate: "300",
status: { tag: status },
amount_funded: "0",
amount_paid: "0",
submitter_reputation: "50",
};
}

function makeClient(withSigner = true) {
return ILNClient.custom({
rpcUrl: "https://fake-rpc.example.org",
networkPassphrase: PASS,
contractId: CONTRACT,
...(withSigner ? { signer: { publicKey: FREELANCER, signTransaction: vi.fn().mockResolvedValue("signed-xdr") } } : {}),
});
}

function mockRpc(overrides: Record<string, unknown> = {}) {
return {
getAccount: vi.fn().mockResolvedValue(new Account(FREELANCER, "1")),
simulateTransaction: vi.fn().mockResolvedValue({ result: { retval: {} } }),
sendTransaction: vi.fn().mockResolvedValue({ status: "PENDING", hash: "txCONVERT" }),
...overrides,
};
}

describe("convertInvoiceToken", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("submits a token change for a Pending invoice", async () => {
mockScValToNative.mockReturnValue(rawInvoice("Pending"));
const client = makeClient(true);
Object.assign(client, { rpc: mockRpc() });

const res = await convertInvoiceToken(client, FREELANCER, 42n, NEW_TOKEN);
expect(res.txHash).toBe("txCONVERT");
});

it("throws when the invoice is not Pending", async () => {
mockScValToNative.mockReturnValue(rawInvoice("Funded"));
const client = makeClient(true);
Object.assign(client, { rpc: mockRpc() });

await expect(convertInvoiceToken(client, FREELANCER, 42n, NEW_TOKEN)).rejects.toThrow("not Pending");
});

it("maps an unapproved-token simulation error through ILNError.fromError", async () => {
mockScValToNative.mockReturnValueOnce(rawInvoice("Pending"));
const client = makeClient(true);
Object.assign(client, {
rpc: mockRpc({
simulateTransaction: vi.fn().mockResolvedValue({ error: "Error(Contract, 5)", _parsed: true }),
}),
});

await expect(convertInvoiceToken(client, FREELANCER, 42n, NEW_TOKEN)).rejects.toBeInstanceOf(
ILNError.Unauthorized
);
});

it("throws when no signer is configured", async () => {
const client = makeClient(false);
await expect(convertInvoiceToken(client, FREELANCER, 42n, NEW_TOKEN)).rejects.toThrow(
"convertInvoiceToken requires a client configured with a signer"
);
});
});
Loading
Loading