@sorandomains/owner 0.6.0 → 0.8.0-migration.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.
@@ -0,0 +1,137 @@
1
+ import { expectedRegistrarCode } from "./native-code-policy.js";
2
+ import { Contract, Operation, Transaction, TransactionBuilder, rpc, scValToNative, xdr } from "@stellar/stellar-sdk";
3
+ import { NativeClaimError, address, hex, namespaceNode, sc, unhex } from "./native-codec.js";
4
+ import { assertSignedBodyUnchanged, validateEligibilityAuthorization, validateNativeTransaction } from "./native-auth.js";
5
+ /** This published legacy code has owner-only issuance. Missing RPC data is never legacy detection. */
6
+ const LEGACY_REGISTRAR_HASH = "ed06b3374ff4342b4a2316fc546505132cd8fd35be6666571cf088710af9bbc6";
7
+ /** Historical reads must not trust an upgraded Registrar that can fabricate receipts. Resolver changes do not block this Registrar-only check. */
8
+ export async function verifyRegistrarProvenance(context, registrar, namespace) {
9
+ const node = sc.bytes(unhex(namespace));
10
+ const [attested, tainted, templates, instance] = await Promise.all([
11
+ context.read(context.registryId, "registrar_of", [node]), context.read(context.registryId, "registrar_tainted", [node]),
12
+ expectedRegistrarCode(context, namespace), context.server.getContractInstance(registrar),
13
+ ]);
14
+ if (attested !== registrar || tainted !== false || instance.executable.type !== "contractExecutableWasm")
15
+ throw new NativeClaimError("Registrar provenance is unavailable or tainted; refusing authoritative claim/receipt reads", "unavailable");
16
+ if (templates !== hex(instance.executable.wasmHash.value))
17
+ throw new NativeClaimError("Registrar executable differs from Registry-approved code", "unavailable");
18
+ }
19
+ export async function nativeCapability(context, namespace) {
20
+ const node = namespaceNode(namespace), nodeArg = sc.bytes(node);
21
+ const registrar = address(await context.read(context.registryId, "registrar_of", [nodeArg]), "contract", "namespace Registrar");
22
+ const instance = await context.server.getContractInstance(registrar);
23
+ if (instance.executable.type === "contractExecutableWasm" && hex(instance.executable.wasmHash.value) === LEGACY_REGISTRAR_HASH)
24
+ return { supported: false, registrar, reason: "legacy-template" };
25
+ await verifyRegistrarProvenance(context, registrar, hex(node));
26
+ const version = await context.read(registrar, "claim_version", []);
27
+ if (typeof version !== "number" || !Number.isInteger(version))
28
+ throw new NativeClaimError("malformed native claim capability", "unavailable");
29
+ if (version !== 1)
30
+ return { supported: false, registrar, reason: "unsupported-version" };
31
+ const [pair, epoch, owner, anchors] = await Promise.all([
32
+ context.read(context.registryId, "native_contracts", [nodeArg]), context.read(context.registryId, "owner_epoch", [nodeArg]),
33
+ context.read(context.registryId, "owner_of", [nodeArg]), context.read(registrar, "anchors", []),
34
+ ]);
35
+ if (!Array.isArray(pair) || pair.length !== 2 || pair[0] !== registrar)
36
+ throw new NativeClaimError("native contract binding does not match Registrar", "unavailable");
37
+ const resolver = address(pair[1], "contract", "native Resolver");
38
+ if (!Array.isArray(anchors) || anchors.length !== 2 || anchors[0] !== context.registryId || !(anchors[1] instanceof Uint8Array) || hex(anchors[1]) !== hex(node))
39
+ throw new NativeClaimError("Registrar anchors differ from selected namespace", "unavailable");
40
+ if (typeof epoch !== "bigint" || epoch < 1n)
41
+ throw new NativeClaimError("invalid namespace ownership epoch", "unavailable");
42
+ if (await context.read(resolver, "initialization_version", []) !== 1)
43
+ throw new NativeClaimError("unsupported native Resolver initializer", "unsupported");
44
+ return { supported: true, version: 1, registrar, resolver, registry: context.registryId, namespace, owner: address(owner, "identity", "namespace owner"), ownerEpoch: epoch };
45
+ }
46
+ export async function requireNative(context, namespace) {
47
+ const capability = await nativeCapability(context, namespace);
48
+ if (!capability.supported)
49
+ throw new NativeClaimError(`namespace has no supported native claim interface (${capability.reason})`, "unsupported");
50
+ return capability;
51
+ }
52
+ export async function prepareNative(context, plan, options = {}) {
53
+ const source = address(await context.signer.publicKey(), "account", "transaction signer");
54
+ if (source !== plan.source)
55
+ throw new NativeClaimError("wallet changed since the intent was reviewed", "authorization");
56
+ const raw = new TransactionBuilder(await context.server.getAccount(source), { fee: context.fee, networkPassphrase: context.passphrase })
57
+ .addOperation(new Contract(plan.contract).call(plan.method, ...plan.args)).setTimeout(context.timeoutSecs).build();
58
+ const simulate = async (tx) => {
59
+ const result = await context.server.simulateTransaction(tx, undefined, undefined, false);
60
+ if (rpc.Api.isSimulationRestore(result))
61
+ throw new NativeClaimError("native operation requires storage restoration; review and restore separately before resuming this intent", "unavailable");
62
+ if (rpc.Api.isSimulationError(result))
63
+ throw new NativeClaimError(`${plan.method}: ${result.error}`, "failed");
64
+ if (!rpc.Api.isSimulationSuccess(result) || !result.result)
65
+ throw new NativeClaimError("native simulation returned no result", "unavailable");
66
+ return result;
67
+ };
68
+ let transaction = rpc.assembleTransaction(raw, await simulate(raw)).build();
69
+ validateNativeTransaction(transaction, plan, false);
70
+ if (options.eligibilityAuthorization) {
71
+ if (options.eligibilityAuthorization.length > 32768)
72
+ throw new NativeClaimError("eligibility authorization is too large", "authorization");
73
+ if (!plan.eligibility)
74
+ throw new NativeClaimError("this native operation does not require an app approver", "authorization");
75
+ const signed = xdr.SorobanAuthorizationEntry.fromXDR(options.eligibilityAuthorization, "base64");
76
+ validateEligibilityAuthorization(signed, plan.eligibility);
77
+ const op = transaction.operations[0];
78
+ if (op.type !== "invokeHostFunction")
79
+ throw new NativeClaimError("unexpected prepared operation");
80
+ const auth = (op.auth ?? []).map(entry => entry.credentials.type === "sorobanCredentialsSourceAccount" ? entry : signed);
81
+ transaction = TransactionBuilder.cloneFrom(transaction, { networkPassphrase: context.passphrase }).clearOperations().addOperation(Operation.invokeHostFunction({ func: op.func, auth })).build();
82
+ transaction = rpc.assembleTransaction(transaction, await simulate(transaction)).build();
83
+ validateNativeTransaction(transaction, plan);
84
+ }
85
+ const op = transaction.operations[0];
86
+ if (op.type !== "invokeHostFunction")
87
+ throw new NativeClaimError("unexpected native operation");
88
+ const approval = (op.auth ?? []).find(entry => entry.credentials.type !== "sorobanCredentialsSourceAccount");
89
+ return { transaction, prepared: { transactionXdr: transaction.toXDR(), hash: hex(transaction.hash()), networkPassphrase: context.passphrase, feeStroops: BigInt(transaction.fee), eligibilityEntryXdr: approval?.toXDR("base64") ?? null } };
90
+ }
91
+ /** No automatic transaction retry, implicit restoration or hash-losing error path. */
92
+ export async function sendNative(context, plan, options = {}) {
93
+ const { transaction, prepared } = await prepareNative(context, plan, options);
94
+ validateNativeTransaction(transaction, plan);
95
+ await options.onPrepared?.(prepared);
96
+ if (await context.signer.publicKey() !== plan.source)
97
+ throw new NativeClaimError("wallet changed before signing", "authorization");
98
+ const result = await context.signer.signTransaction(prepared.transactionXdr, { networkPassphrase: context.passphrase });
99
+ const signed = assertSignedBodyUnchanged(transaction, typeof result === "string" ? result : result.signedTxXdr, context.passphrase);
100
+ try {
101
+ const sent = await context.server.sendTransaction(signed);
102
+ if (sent.hash !== prepared.hash)
103
+ throw new NativeClaimError("RPC returned a different transaction hash", "pending", prepared.hash);
104
+ if (sent.status === "ERROR" || sent.status === "TRY_AGAIN_LATER")
105
+ throw new NativeClaimError(`transaction was not accepted (${sent.status}); reconcile the original receipt and hash`, "pending", prepared.hash);
106
+ for (let attempt = 0; attempt < context.timeoutSecs + 5; attempt++) {
107
+ const receipt = await context.server.getTransaction(prepared.hash);
108
+ if (receipt.status === "SUCCESS" || receipt.status === "FAILED") {
109
+ // Status alone cannot identify the reviewed transaction or establish inclusion.
110
+ validateNativeTerminalReceipt(receipt, prepared.hash, context.passphrase);
111
+ if (receipt.status === "SUCCESS")
112
+ return { hash: prepared.hash, ledger: receipt.ledger, value: receipt.returnValue ? scValToNative(receipt.returnValue) : null };
113
+ throw new NativeClaimError("native transaction failed on chain", "failed", prepared.hash);
114
+ }
115
+ await new Promise(resolve => setTimeout(resolve, 1000));
116
+ }
117
+ throw new NativeClaimError("transaction outcome is unknown; recover the original receipt and hash before replacing the request", "pending", prepared.hash);
118
+ }
119
+ catch (error) {
120
+ if (error instanceof NativeClaimError && error.txHash)
121
+ throw error;
122
+ throw new NativeClaimError(`submission/confirmation interrupted: ${String(error)}; reconcile the original receipt`, "pending", prepared.hash);
123
+ }
124
+ }
125
+ /** Bind terminal RPC context before classifying success or failure. An incomplete response remains uncertain. */
126
+ export function validateNativeTerminalReceipt(receipt, expectedHash, passphrase) {
127
+ try {
128
+ if (receipt.txHash !== expectedHash || !Number.isInteger(receipt.ledger) || receipt.ledger <= 0 || receipt.ledger > 0xffff_ffff || !receipt.envelopeXdr)
129
+ throw new Error("missing or mismatched hash/ledger/envelope");
130
+ const included = TransactionBuilder.fromXDR(receipt.envelopeXdr, passphrase);
131
+ if (!(included instanceof Transaction) || hex(included.hash()) !== expectedHash)
132
+ throw new Error("different included envelope");
133
+ }
134
+ catch {
135
+ throw new NativeClaimError("terminal RPC response does not prove inclusion of the original reviewed transaction; reconcile its hash", "pending", expectedHash);
136
+ }
137
+ }
@@ -0,0 +1,166 @@
1
+ import { xdr } from "@stellar/stellar-sdk";
2
+ import { type PaymentDestination } from "./payment.js";
3
+ export type ClaimAdmission = {
4
+ type: "open";
5
+ } | {
6
+ type: "allowlist";
7
+ root: string;
8
+ } | {
9
+ type: "approval";
10
+ account: string;
11
+ };
12
+ export type ClaimSettings = {
13
+ mode: "manual" | "public";
14
+ enabled: boolean;
15
+ admission: ClaimAdmission;
16
+ feeToken: string;
17
+ feeAmount: bigint;
18
+ feeRecipient: string;
19
+ walletLimit: bigint;
20
+ approvalAllowance: bigint;
21
+ approvalRateLimit: bigint;
22
+ approvalWindowSecs: bigint;
23
+ approvalTtlSecs: bigint;
24
+ };
25
+ export type ClaimConfig = {
26
+ settings: ClaimSettings;
27
+ ownerEpoch: bigint;
28
+ policyVersion: bigint;
29
+ grantEpoch: bigint;
30
+ };
31
+ export type RequestContext = {
32
+ network: string;
33
+ registry: string;
34
+ registrar: string;
35
+ namespace: string;
36
+ requestId: string;
37
+ validAfter: bigint;
38
+ deadline: bigint;
39
+ };
40
+ export type ClaimIntent = {
41
+ context: RequestContext;
42
+ label: string;
43
+ claimant: string;
44
+ destination: PaymentDestination;
45
+ resolver: string;
46
+ expectedGeneration: bigint | null;
47
+ expectedExpiry: bigint | null;
48
+ termSecs: bigint;
49
+ ownerEpoch: bigint;
50
+ policyVersion: bigint;
51
+ grantEpoch: bigint;
52
+ feeToken: string;
53
+ feeAmount: bigint;
54
+ feeRecipient: string;
55
+ };
56
+ export type ReservedIntent = {
57
+ context: RequestContext;
58
+ label: string;
59
+ holder: string;
60
+ destination: PaymentDestination;
61
+ resolver: string;
62
+ expectedGeneration: bigint | null;
63
+ expectedExpiry: bigint | null;
64
+ termSecs: bigint;
65
+ ownerEpoch: bigint;
66
+ policyVersion: bigint;
67
+ };
68
+ export type TransferIntent = {
69
+ context: RequestContext;
70
+ label: string;
71
+ from: string;
72
+ to: string;
73
+ expectedGeneration: bigint;
74
+ expectedExpiry: bigint;
75
+ proposalExpires: bigint;
76
+ destination: PaymentDestination;
77
+ resolver: string;
78
+ };
79
+ export type RenewIntent = {
80
+ context: RequestContext;
81
+ label: string;
82
+ holder: string;
83
+ expectedGeneration: bigint;
84
+ expectedExpiry: bigint;
85
+ termSecs: bigint;
86
+ minNewExpiry: bigint;
87
+ maxNewExpiry: bigint;
88
+ };
89
+ export type ClaimReceipt = {
90
+ operation: "claim" | "reserved" | "transfer" | "renew";
91
+ intentHash: string;
92
+ node: string;
93
+ holder: string;
94
+ generation: bigint;
95
+ expiresAt: bigint;
96
+ feeAmount: bigint;
97
+ feeToken: string;
98
+ feeRecipient: string | null;
99
+ ledger: number;
100
+ timestamp: bigint;
101
+ };
102
+ export type ClaimResult = {
103
+ status: "fresh" | "replayed";
104
+ receipt: ClaimReceipt;
105
+ };
106
+ export type ClaimUsage = {
107
+ publicClaims: bigint;
108
+ reservedIssues: bigint;
109
+ };
110
+ export type ApprovalUsage = {
111
+ total: bigint;
112
+ windowUsed: bigint;
113
+ windowEnds: bigint;
114
+ };
115
+ export type ClaimQuote = {
116
+ network: string;
117
+ registry: string;
118
+ registrar: string;
119
+ namespace: string;
120
+ resolver: string;
121
+ label: string;
122
+ node: string;
123
+ claimant: string;
124
+ config: ClaimConfig | null;
125
+ ownerEpoch: bigint;
126
+ policyVersion: bigint;
127
+ available: boolean;
128
+ reserved: boolean;
129
+ generation: bigint | null;
130
+ expiresAt: bigint | null;
131
+ termSecs: bigint;
132
+ now: bigint;
133
+ usage: ClaimUsage;
134
+ approvalUsage: ApprovalUsage;
135
+ };
136
+ export type DestinationPreview = {
137
+ node: string;
138
+ holder: string;
139
+ generation: bigint;
140
+ expiresAt: bigint;
141
+ active: boolean;
142
+ destination: PaymentDestination;
143
+ };
144
+ export declare function claimSettingsToScVal(value: ClaimSettings): xdr.ScVal;
145
+ export declare const claimPolicyInputToScVal: typeof claimSettingsToScVal;
146
+ export declare const claimLabelToScVal: (value: string) => xdr.ScVal;
147
+ export declare const claimConfigFromNative: (value: unknown) => ClaimConfig;
148
+ export declare const claimQuoteFromNative: (value: unknown) => ClaimQuote;
149
+ export declare const claimUsageFromNative: (value: unknown) => ClaimUsage;
150
+ export declare const approvalUsageFromNative: (value: unknown) => ApprovalUsage;
151
+ export declare const destinationPreviewFromNative: (value: unknown) => DestinationPreview;
152
+ export declare const claimReceiptFromNative: (value: unknown) => ClaimReceipt;
153
+ export declare function claimIntentToScVal(value: ClaimIntent): xdr.ScVal;
154
+ export declare function reservedIntentToScVal(value: ReservedIntent): xdr.ScVal;
155
+ export declare function transferIntentToScVal(value: TransferIntent): xdr.ScVal;
156
+ export declare function renewIntentToScVal(value: RenewIntent): xdr.ScVal;
157
+ export declare const claimIntentFromNative: (value: unknown) => ClaimIntent;
158
+ export declare const transferIntentFromNative: (value: unknown) => TransferIntent;
159
+ export declare const renewIntentFromNative: (value: unknown) => RenewIntent;
160
+ export declare function claimResultFromNative(value: unknown): ClaimResult;
161
+ export declare function nativeIntentHash(method: "claim" | "issue_reserved_with_destination" | "accept_transfer_with_destination" | "renew_holder", value: xdr.ScVal): string;
162
+ /** Lossless public recovery JSON; only declared bigint fields receive the tagged encoding. */
163
+ export declare function stringifyNativeIntent(value: ClaimIntent | TransferIntent | RenewIntent | ReservedIntent): string;
164
+ export declare function parseNativeClaimIntent(json: string): ClaimIntent;
165
+ export declare function parseNativeTransferIntent(json: string): TransferIntent;
166
+ export declare function parseNativeRenewIntent(json: string): RenewIntent;
@@ -0,0 +1,98 @@
1
+ import { hash, scValToNative, xdr } from "@stellar/stellar-sdk";
2
+ import { destinationFromNative } from "./payment.js";
3
+ import { NativeClaimError, address, amount, bool, bytes32, exactObject, hex, hex32, label, paymentDestinationToScVal, sc, struct, u32, u64, unhex, utf8 } from "./native-codec.js";
4
+ const primitive = (validate, encode) => ({ encode: v => encode(validate(v)), decode: validate });
5
+ const U64 = primitive(v => u64(v, "u64 field"), sc.u64), U32 = primitive(v => u32(v, "u32 field"), sc.u32), AMOUNT = primitive(v => amount(v, "fee amount"), sc.i128), BOOL = primitive(v => bool(v, "boolean field"), sc.bool);
6
+ const ACCOUNT = primitive(v => address(v, "account", "account"), sc.address), CONTRACT = primitive(v => address(v, "contract", "contract"), sc.address), IDENTITY = primitive(v => address(v, "identity", "identity"), sc.address);
7
+ const HEX = { encode: v => sc.bytes(unhex(hex32(v, "bytes32 field"))), decode: v => hex(bytes32(v, "bytes32 field")) };
8
+ const LABEL = { encode: v => sc.bytes(utf8(label(v))), decode: v => { if (!(v instanceof Uint8Array))
9
+ throw new NativeClaimError("label must be on-chain Bytes"); return label(new TextDecoder("utf-8", { fatal: true }).decode(v)); } };
10
+ const DESTINATION = { encode: v => paymentDestinationToScVal(v), decode: destinationFromNative };
11
+ const optional = (inner) => ({ encode: v => v === null ? sc.option(null) : inner.encode(v), decode: v => v === null || v === undefined ? null : inner.decode(v) });
12
+ const enumeration = (mapping) => ({ encode: v => { if (typeof v !== "string" || !Object.hasOwn(mapping, v))
13
+ throw new NativeClaimError("unsupported enum value"); return xdr.ScVal.scvVec([sc.symbol(mapping[v])]); }, decode: v => { if (!Array.isArray(v) || v.length !== 1)
14
+ throw new NativeClaimError("invalid enum result"); const entry = Object.entries(mapping).find(([, tag]) => tag === v[0]); if (!entry)
15
+ throw new NativeClaimError("unknown enum tag"); return entry[0]; } });
16
+ const ADMISSION = { encode: v => { if (!v || typeof v !== "object")
17
+ throw new NativeClaimError("invalid admission"); const a = v; if (a.type === "open") {
18
+ exactObject(a, ["type"], "open admission");
19
+ return xdr.ScVal.scvVec([sc.symbol("Open")]);
20
+ } if (a.type === "allowlist") {
21
+ exactObject(a, ["type", "root"], "allowlist admission");
22
+ return xdr.ScVal.scvVec([sc.symbol("Allowlist"), HEX.encode(a.root)]);
23
+ } if (a.type === "approval") {
24
+ exactObject(a, ["type", "account"], "approval admission");
25
+ return xdr.ScVal.scvVec([sc.symbol("Approval"), ACCOUNT.encode(a.account)]);
26
+ } throw new NativeClaimError("unsupported admission"); }, decode: v => { if (!Array.isArray(v))
27
+ throw new NativeClaimError("invalid admission enum"); if (v.length === 1 && v[0] === "Open")
28
+ return { type: "open" }; if (v.length === 2 && v[0] === "Allowlist")
29
+ return { type: "allowlist", root: HEX.decode(v[1]) }; if (v.length === 2 && v[0] === "Approval")
30
+ return { type: "approval", account: ACCOUNT.decode(v[1]) }; throw new NativeClaimError("unknown admission enum"); } };
31
+ const snake = (s) => s.replace(/[A-Z]/g, c => "_" + c.toLowerCase());
32
+ function model(fields) { return { encode: v => { const value = exactObject(v, Object.keys(fields), "native input"); return struct(Object.fromEntries(Object.entries(fields).map(([name, codec]) => [snake(name), codec.encode(value[name])]))); }, decode: v => { const value = exactObject(v, Object.keys(fields).map(snake), "native result"); return Object.fromEntries(Object.entries(fields).map(([name, codec]) => [name, codec.decode(value[snake(name)])])); } }; }
33
+ const SETTINGS = model({ mode: enumeration({ manual: "Manual", public: "Public" }), enabled: BOOL, admission: ADMISSION, feeToken: CONTRACT, feeAmount: AMOUNT, feeRecipient: ACCOUNT, walletLimit: U64, approvalAllowance: U64, approvalRateLimit: U64, approvalWindowSecs: U64, approvalTtlSecs: U64 });
34
+ const CONFIG = model({ settings: SETTINGS, ownerEpoch: U64, policyVersion: U64, grantEpoch: U64 });
35
+ const CONTEXT = model({ network: HEX, registry: CONTRACT, registrar: CONTRACT, namespace: HEX, requestId: HEX, validAfter: U64, deadline: U64 });
36
+ const CLAIM = model({ context: CONTEXT, label: LABEL, claimant: ACCOUNT, destination: DESTINATION, resolver: CONTRACT, expectedGeneration: optional(U64), expectedExpiry: optional(U64), termSecs: U64, ownerEpoch: U64, policyVersion: U64, grantEpoch: U64, feeToken: CONTRACT, feeAmount: AMOUNT, feeRecipient: ACCOUNT });
37
+ const RESERVED = model({ context: CONTEXT, label: LABEL, holder: ACCOUNT, destination: DESTINATION, resolver: CONTRACT, expectedGeneration: optional(U64), expectedExpiry: optional(U64), termSecs: U64, ownerEpoch: U64, policyVersion: U64 });
38
+ const TRANSFER = model({ context: CONTEXT, label: LABEL, from: IDENTITY, to: ACCOUNT, expectedGeneration: U64, expectedExpiry: U64, proposalExpires: U64, destination: DESTINATION, resolver: CONTRACT });
39
+ const RENEW = model({ context: CONTEXT, label: LABEL, holder: ACCOUNT, expectedGeneration: U64, expectedExpiry: U64, termSecs: U64, minNewExpiry: U64, maxNewExpiry: U64 });
40
+ const USAGE = model({ publicClaims: U64, reservedIssues: U64 }), APPROVAL_USAGE = model({ total: U64, windowUsed: U64, windowEnds: U64 });
41
+ const CONFIG_STATE = { encode: v => v === null ? xdr.ScVal.scvVec([sc.symbol("Unconfigured")]) : xdr.ScVal.scvVec([sc.symbol("Configured"), CONFIG.encode(v)]), decode: v => { if (!Array.isArray(v))
42
+ throw new NativeClaimError("invalid claim config state"); if (v.length === 1 && v[0] === "Unconfigured")
43
+ return null; if (v.length === 2 && v[0] === "Configured")
44
+ return CONFIG.decode(v[1]); throw new NativeClaimError("invalid claim config state"); } };
45
+ const QUOTE = model({ network: HEX, registry: CONTRACT, registrar: CONTRACT, namespace: HEX, resolver: CONTRACT, label: LABEL, node: HEX, claimant: ACCOUNT, config: CONFIG_STATE, ownerEpoch: U64, policyVersion: U64, available: BOOL, reserved: BOOL, generation: optional(U64), expiresAt: optional(U64), termSecs: U64, now: U64, usage: USAGE, approvalUsage: APPROVAL_USAGE });
46
+ const RECEIPT = model({ operation: enumeration({ claim: "Claim", reserved: "Reserved", transfer: "Transfer", renew: "Renew" }), intentHash: HEX, node: HEX, holder: IDENTITY, generation: U64, expiresAt: U64, feeAmount: AMOUNT, feeToken: CONTRACT, feeRecipient: optional(ACCOUNT), ledger: U32, timestamp: U64 });
47
+ const PREVIEW = model({ node: HEX, holder: IDENTITY, generation: U64, expiresAt: U64, active: BOOL, destination: DESTINATION });
48
+ export function claimSettingsToScVal(value) {
49
+ const encoded = SETTINGS.encode(value);
50
+ if (value.admission.type === "approval") {
51
+ if (value.approvalAllowance === 0n || value.approvalRateLimit === 0n || value.approvalWindowSecs === 0n || value.approvalWindowSecs > 31536000n || value.approvalTtlSecs === 0n || value.approvalTtlSecs > 3600n)
52
+ throw new NativeClaimError("approval mode requires explicit bounded admission budgets, window and lifetime");
53
+ if (value.admission.account === value.feeRecipient)
54
+ throw new NativeClaimError("eligibility account must differ from fee treasury");
55
+ }
56
+ else if (value.approvalAllowance !== 0n || value.approvalRateLimit !== 0n || value.approvalWindowSecs !== 0n || value.approvalTtlSecs !== 0n)
57
+ throw new NativeClaimError("approval settings must be zero outside approval mode");
58
+ return encoded;
59
+ }
60
+ export const claimPolicyInputToScVal = claimSettingsToScVal;
61
+ export const claimLabelToScVal = (value) => LABEL.encode(value);
62
+ export const claimConfigFromNative = (value) => CONFIG.decode(value);
63
+ export const claimQuoteFromNative = (value) => QUOTE.decode(value);
64
+ export const claimUsageFromNative = (value) => USAGE.decode(value);
65
+ export const approvalUsageFromNative = (value) => APPROVAL_USAGE.decode(value);
66
+ export const destinationPreviewFromNative = (value) => PREVIEW.decode(value);
67
+ export const claimReceiptFromNative = (value) => RECEIPT.decode(value);
68
+ function validContext(c) { if (c.deadline <= c.validAfter || c.deadline - c.validAfter > 3600n)
69
+ throw new NativeClaimError("business intent lifetime must be positive and at most 3600 seconds"); }
70
+ export function claimIntentToScVal(value) { const result = CLAIM.encode(value); validContext(value.context); if ((value.expectedGeneration === null) !== (value.expectedExpiry === null))
71
+ throw new NativeClaimError("generation and expiry expectations must both be present or absent"); return result; }
72
+ export function reservedIntentToScVal(value) { const result = RESERVED.encode(value); validContext(value.context); if ((value.expectedGeneration === null) !== (value.expectedExpiry === null))
73
+ throw new NativeClaimError("generation and expiry expectations must both be present or absent"); return result; }
74
+ export function transferIntentToScVal(value) { const result = TRANSFER.encode(value); validContext(value.context); return result; }
75
+ export function renewIntentToScVal(value) { const result = RENEW.encode(value); validContext(value.context); if (value.termSecs === 0n || value.maxNewExpiry < value.minNewExpiry)
76
+ throw new NativeClaimError("invalid renewal bounds"); return result; }
77
+ export const claimIntentFromNative = (value) => CLAIM.decode(value);
78
+ export const transferIntentFromNative = (value) => TRANSFER.decode(value);
79
+ export const renewIntentFromNative = (value) => RENEW.decode(value);
80
+ export function claimResultFromNative(value) { if (!Array.isArray(value) || value.length !== 2 || !["Fresh", "Replayed"].includes(value[0]))
81
+ throw new NativeClaimError("invalid claim result"); return { status: value[0] === "Fresh" ? "fresh" : "replayed", receipt: claimReceiptFromNative(value[1]) }; }
82
+ export function nativeIntentHash(method, value) { return hex(hash(xdr.ScVal.scvVec([sc.symbol(method), value]).toXDR())); }
83
+ /** Lossless public recovery JSON; only declared bigint fields receive the tagged encoding. */
84
+ export function stringifyNativeIntent(value) { return JSON.stringify(value, (_key, v) => typeof v === "bigint" ? { $u64: v.toString() } : v); }
85
+ export function parseNativeClaimIntent(json) { if (json.length > 16384)
86
+ throw new NativeClaimError("claim recovery reference is too large"); const raw = JSON.parse(json, (_key, v) => { if (v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).join(",") === "$u64") {
87
+ if (typeof v.$u64 !== "string" || !/^(0|[1-9][0-9]*)$/.test(v.$u64))
88
+ throw new NativeClaimError("invalid recovery integer");
89
+ return BigInt(v.$u64);
90
+ } return v; }); return claimIntentFromNative(scValToNative(claimIntentToScVal(raw))); }
91
+ export function parseNativeTransferIntent(json) { return parseLifecycleIntent(json, TRANSFER, transferIntentToScVal); }
92
+ export function parseNativeRenewIntent(json) { return parseLifecycleIntent(json, RENEW, renewIntentToScVal); }
93
+ function parseLifecycleIntent(json, codec, encode) { if (json.length > 16384)
94
+ throw new NativeClaimError("lifecycle intent is too large"); const raw = JSON.parse(json, (_key, v) => { if (v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).join(",") === "$u64") {
95
+ if (typeof v.$u64 !== "string" || !/^(0|[1-9][0-9]*)$/.test(v.$u64))
96
+ throw new NativeClaimError("invalid recovery integer");
97
+ return BigInt(v.$u64);
98
+ } return v; }); return codec.decode(scValToNative(encode(raw))); }
@@ -0,0 +1,37 @@
1
+ /** Direct v1 and muxed v2 payment records. Kept identical in the independently published lookup
2
+ * and holder packages; the conformance tests exercise both copies. */
3
+ import { xdr } from "@stellar/stellar-sdk";
4
+ export declare const PAYMENT_RECORD_KEY = "payment";
5
+ export type PaymentMemo = {
6
+ type: "none";
7
+ } | {
8
+ type: "id";
9
+ value: string;
10
+ } | {
11
+ type: "text";
12
+ value: string;
13
+ } | {
14
+ type: "hash";
15
+ value: string;
16
+ };
17
+ export type PaymentDestination = {
18
+ address: string;
19
+ memo: PaymentMemo;
20
+ };
21
+ /** Reject invalid data without normalizing meaningful memo bytes. */
22
+ export declare function validatePaymentDestination(value: unknown): PaymentDestination;
23
+ export declare function encodePaymentRecord(value: PaymentDestination): string;
24
+ /** Empty/missing records are not explicit payment instructions. */
25
+ export declare function parsePaymentRecord(raw: string): PaymentDestination;
26
+ export declare function paymentMemoToScVal(memo: PaymentMemo): xdr.ScVal;
27
+ /** Decode Soroban contract enum values, checking arity and native types. */
28
+ export declare function paymentFromNative(raw: unknown): PaymentDestination;
29
+ /** Decode a full muxed destination without treating its operation ID as a memo. */
30
+ export declare function decodeMuxedAddress(address: string): {
31
+ account: string;
32
+ id: string;
33
+ };
34
+ /** Encode only canonical G + exact decimal u64; numbers are never accepted. */
35
+ export declare function encodeMuxedAddress(account: string, id: string): string;
36
+ /** Strict additive on-chain destination enum; v1 payment structs stay separate. */
37
+ export declare function destinationFromNative(raw: unknown): PaymentDestination;
@@ -0,0 +1,148 @@
1
+ /** Direct v1 and muxed v2 payment records. Kept identical in the independently published lookup
2
+ * and holder packages; the conformance tests exercise both copies. */
3
+ import { StrKey, nativeToScVal, xdr } from "@stellar/stellar-sdk";
4
+ export const PAYMENT_RECORD_KEY = "payment";
5
+ const MAX_U64 = 18446744073709551615n;
6
+ const utf8 = (value) => new TextEncoder().encode(value);
7
+ /** Reject invalid data without normalizing meaningful memo bytes. */
8
+ export function validatePaymentDestination(value) {
9
+ if (!value || typeof value !== "object" || Array.isArray(value))
10
+ throw new Error("invalid payment destination");
11
+ const p = value;
12
+ if (Object.keys(p).sort().join(",") !== "address,memo")
13
+ throw new Error("unexpected payment fields");
14
+ if (typeof p.address !== "string" || (!StrKey.isValidEd25519PublicKey(p.address) && !StrKey.isValidContract(p.address) && !StrKey.isValidMed25519PublicKey(p.address)))
15
+ throw new Error("payment address must be a valid G, C or M address");
16
+ if (!p.memo || typeof p.memo !== "object" || Array.isArray(p.memo))
17
+ throw new Error("invalid memo");
18
+ const m = p.memo;
19
+ if (m.type === "none") {
20
+ if (Object.keys(m).join(",") !== "type")
21
+ throw new Error("none memo cannot have a value");
22
+ if (StrKey.isValidMed25519PublicKey(p.address))
23
+ decodeMuxedAddress(p.address);
24
+ return { address: p.address, memo: { type: "none" } };
25
+ }
26
+ if (!StrKey.isValidEd25519PublicKey(p.address))
27
+ throw new Error("memos require a classic G address");
28
+ if (Object.keys(m).sort().join(",") !== "type,value" || typeof m.value !== "string")
29
+ throw new Error("memo value must be a string");
30
+ switch (m.type) {
31
+ case "id":
32
+ if (!/^(0|[1-9][0-9]{0,19})$/.test(m.value) || BigInt(m.value) > MAX_U64)
33
+ throw new Error("memo ID must be canonical decimal u64");
34
+ return { address: p.address, memo: { type: "id", value: m.value } };
35
+ case "text": {
36
+ const bytes = utf8(m.value);
37
+ if (!bytes.length || bytes.length > 28 || new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes) !== m.value)
38
+ throw new Error("memo text must be valid UTF-8, 1–28 bytes");
39
+ return { address: p.address, memo: { type: "text", value: m.value } };
40
+ }
41
+ case "hash":
42
+ if (!/^[0-9a-f]{64}$/.test(m.value))
43
+ throw new Error("memo hash must be 32 bytes as lowercase hex");
44
+ return { address: p.address, memo: { type: "hash", value: m.value } };
45
+ default: throw new Error("unsupported memo type");
46
+ }
47
+ }
48
+ export function encodePaymentRecord(value) {
49
+ const p = validatePaymentDestination(value);
50
+ if (StrKey.isValidMed25519PublicKey(p.address)) {
51
+ const muxed = decodeMuxedAddress(p.address);
52
+ return `2|${muxed.account}|muxed|${muxed.id}`;
53
+ }
54
+ return `1|${p.address}|${p.memo.type}|${p.memo.type === "none" ? "" : p.memo.value}`;
55
+ }
56
+ /** Empty/missing records are not explicit payment instructions. */
57
+ export function parsePaymentRecord(raw) {
58
+ if (typeof raw !== "string" || utf8(raw).length > 128)
59
+ throw new Error("invalid payment record length");
60
+ const first = raw.indexOf("|");
61
+ const second = raw.indexOf("|", first + 1);
62
+ const third = raw.indexOf("|", second + 1);
63
+ if (first < 0 || second < 0 || third < 0)
64
+ throw new Error("unsupported payment record");
65
+ const version = raw.slice(0, first);
66
+ const address = raw.slice(first + 1, second);
67
+ const type = raw.slice(second + 1, third);
68
+ const value = raw.slice(third + 1);
69
+ if (version === "2" && type === "muxed")
70
+ return { address: encodeMuxedAddress(address, value), memo: { type: "none" } };
71
+ if (version !== "1" || (!StrKey.isValidEd25519PublicKey(address) && !StrKey.isValidContract(address)))
72
+ throw new Error("unsupported payment record");
73
+ if (type === "none" && value !== "")
74
+ throw new Error("none memo cannot have a value");
75
+ return validatePaymentDestination({ address, memo: type === "none" ? { type } : { type, value } });
76
+ }
77
+ export function paymentMemoToScVal(memo) {
78
+ const symbol = (s) => nativeToScVal(s, { type: "symbol" });
79
+ switch (memo.type) {
80
+ case "none": return xdr.ScVal.scvVec([symbol("None")]);
81
+ case "id": return xdr.ScVal.scvVec([symbol("Id"), nativeToScVal(BigInt(memo.value), { type: "u64" })]);
82
+ case "text": return xdr.ScVal.scvVec([symbol("Text"), nativeToScVal(memo.value, { type: "string" })]);
83
+ case "hash": return xdr.ScVal.scvVec([symbol("Hash"), nativeToScVal(Uint8Array.from(memo.value.match(/../g), (b) => parseInt(b, 16)), { type: "bytes" })]);
84
+ }
85
+ }
86
+ /** Decode Soroban contract enum values, checking arity and native types. */
87
+ export function paymentFromNative(raw) {
88
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
89
+ throw new Error("invalid payment result");
90
+ const p = raw;
91
+ if (Object.keys(p).sort().join(",") !== "address,memo" || !Array.isArray(p.memo))
92
+ throw new Error("invalid payment result fields");
93
+ if (typeof p.address !== "string" || (!StrKey.isValidEd25519PublicKey(p.address) && !StrKey.isValidContract(p.address)))
94
+ throw new Error("direct payment must contain a G or C address");
95
+ const m = p.memo;
96
+ let memo;
97
+ if (m.length === 1 && m[0] === "None")
98
+ memo = { type: "none" };
99
+ else if (m.length === 2 && m[0] === "Id" && typeof m[1] === "bigint")
100
+ memo = { type: "id", value: m[1].toString() };
101
+ else if (m.length === 2 && m[0] === "Text" && typeof m[1] === "string")
102
+ memo = { type: "text", value: m[1] };
103
+ else if (m.length === 2 && m[0] === "Hash" && m[1] instanceof Uint8Array && m[1].length === 32)
104
+ memo = { type: "hash", value: Array.from(m[1], (b) => b.toString(16).padStart(2, "0")).join("") };
105
+ else
106
+ throw new Error("invalid payment memo result");
107
+ return validatePaymentDestination({ address: p.address, memo });
108
+ }
109
+ /** Decode a full muxed destination without treating its operation ID as a memo. */
110
+ export function decodeMuxedAddress(address) {
111
+ if (typeof address !== "string" || !StrKey.isValidMed25519PublicKey(address))
112
+ throw new Error("invalid muxed M address");
113
+ const raw = StrKey.decodeMed25519PublicKey(address);
114
+ if (raw.length !== 40 || StrKey.encodeMed25519PublicKey(raw) !== address)
115
+ throw new Error("noncanonical muxed address");
116
+ let id = 0n;
117
+ for (const byte of raw.subarray(32))
118
+ id = (id << 8n) | BigInt(byte);
119
+ return { account: StrKey.encodeEd25519PublicKey(raw.subarray(0, 32)), id: id.toString() };
120
+ }
121
+ /** Encode only canonical G + exact decimal u64; numbers are never accepted. */
122
+ export function encodeMuxedAddress(account, id) {
123
+ if (typeof account !== "string" || !StrKey.isValidEd25519PublicKey(account))
124
+ throw new Error("muxed base must be a G account");
125
+ if (typeof id !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(id) || BigInt(id) > MAX_U64)
126
+ throw new Error("muxed ID must be canonical decimal u64");
127
+ const raw = new Uint8Array(40);
128
+ raw.set(StrKey.decodeEd25519PublicKey(account));
129
+ let value = BigInt(id);
130
+ for (let i = 39; i >= 32; i--) {
131
+ raw[i] = Number(value & 255n);
132
+ value >>= 8n;
133
+ }
134
+ return StrKey.encodeMed25519PublicKey(raw);
135
+ }
136
+ /** Strict additive on-chain destination enum; v1 payment structs stay separate. */
137
+ export function destinationFromNative(raw) {
138
+ if (!Array.isArray(raw) || raw.length !== 2)
139
+ throw new Error("invalid destination enum");
140
+ if (raw[0] === "Direct")
141
+ return paymentFromNative(raw[1]);
142
+ if (raw[0] !== "Muxed" || !raw[1] || typeof raw[1] !== "object" || Array.isArray(raw[1]))
143
+ throw new Error("invalid destination variant");
144
+ const value = raw[1];
145
+ if (Object.keys(value).sort().join(",") !== "account,id" || typeof value.account !== "string" || typeof value.id !== "bigint")
146
+ throw new Error("invalid muxed destination fields");
147
+ return { address: encodeMuxedAddress(value.account, value.id.toString()), memo: { type: "none" } };
148
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sorandomains/owner",
3
- "version": "0.6.0",
4
- "description": "Run your Soran namespace on Stellar \u2014 issue names, manage lifecycle, transfer, and walk the one-way permanence door.",
3
+ "version": "0.8.0-migration.0",
4
+ "description": "Run your Soran namespace on Stellar: configure claims, issue names and manage namespace policies.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -13,7 +13,7 @@
13
13
  "typecheck": "tsc --noEmit",
14
14
  "prepublishOnly": "tsc",
15
15
  "check:browser": "esbuild dist/index.js --bundle --platform=browser --external:@stellar/stellar-sdk --outfile=browser-check.js --legal-comments=none --log-level=error && node -e \"const fs=require('fs');const s=fs.readFileSync('browser-check.js','utf8');fs.unlinkSync('browser-check.js');if(/\\bBuffer\\b/.test(s)){console.error('FAIL: bare Buffer reference in browser bundle');process.exit(1)}console.log('browser bundle clean')\"",
16
- "test": "node --import tsx test/decode-failure.test.mts && node --import tsx --test test/integration.test.mts"
16
+ "test": "node --import tsx test/decode-failure.test.mts && node --import tsx --test test/integration.test.mts test/native-*.test.mts"
17
17
  },
18
18
  "license": "MIT",
19
19
  "repository": {