@toon-protocol/client 5.1.0 → 5.1.1
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/{chunk-BHGJXLS7.js → chunk-GNPJRJ6U.js} +60 -16
- package/dist/chunk-GNPJRJ6U.js.map +1 -0
- package/dist/cli/main.js +13 -4
- package/dist/cli/main.js.map +1 -1
- package/dist/{client-DF3LZVLC.js → client-RO3VITXU.js} +4 -2
- package/dist/index.d.ts +38 -10
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-BHGJXLS7.js.map +0 -1
- /package/dist/{client-DF3LZVLC.js.map → client-RO3VITXU.js.map} +0 -0
|
@@ -28,11 +28,12 @@ import {
|
|
|
28
28
|
ValidationError,
|
|
29
29
|
addressFor,
|
|
30
30
|
chainUnavailableMessage,
|
|
31
|
+
describeEndpoint,
|
|
31
32
|
isInsufficientGasError,
|
|
32
33
|
resolveConfig,
|
|
33
34
|
send,
|
|
34
35
|
toEnvelopeRequest
|
|
35
|
-
} from "./chunk-
|
|
36
|
+
} from "./chunk-GNPJRJ6U.js";
|
|
36
37
|
import "./chunk-6O5OXJVR.js";
|
|
37
38
|
import "./chunk-32MD3CXE.js";
|
|
38
39
|
export {
|
|
@@ -65,9 +66,10 @@ export {
|
|
|
65
66
|
ValidationError,
|
|
66
67
|
addressFor,
|
|
67
68
|
chainUnavailableMessage,
|
|
69
|
+
describeEndpoint,
|
|
68
70
|
isInsufficientGasError,
|
|
69
71
|
resolveConfig,
|
|
70
72
|
send,
|
|
71
73
|
toEnvelopeRequest
|
|
72
74
|
};
|
|
73
|
-
//# sourceMappingURL=client-
|
|
75
|
+
//# sourceMappingURL=client-RO3VITXU.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -311,8 +311,14 @@ declare class ToonClientError extends Error {
|
|
|
311
311
|
* These errors trigger retry logic with exponential backoff.
|
|
312
312
|
*/
|
|
313
313
|
declare class NetworkError extends ToonClientError {
|
|
314
|
-
|
|
314
|
+
/** The URL that could not be reached, when the failure was reaching one. */
|
|
315
|
+
readonly endpoint?: string;
|
|
316
|
+
constructor(message: string, cause?: Error, endpoint?: string);
|
|
315
317
|
}
|
|
318
|
+
/** Where a packet-path URL came from: the caller's config, or the node's self-description. */
|
|
319
|
+
type EndpointSource = 'configured' | 'published';
|
|
320
|
+
/** `url`, plus a note when the node (not the caller) chose it. */
|
|
321
|
+
declare function describeEndpoint(url: string, source?: EndpointSource): string;
|
|
316
322
|
/**
|
|
317
323
|
* Connector error for a transport-level failure at the client edge: a `4xx`
|
|
318
324
|
* that is not a greeting, or a `5xx`.
|
|
@@ -2849,9 +2855,10 @@ interface ConnectorEdgeClientConfig {
|
|
|
2849
2855
|
* are how a stale answer is dropped.
|
|
2850
2856
|
*
|
|
2851
2857
|
* A price is cached the same way and for the same reason (toon-client#452):
|
|
2852
|
-
* under ADR 0020 a route
|
|
2853
|
-
* not vary with what is being sent
|
|
2854
|
-
*
|
|
2858
|
+
* under ADR 0020 a route has one set of terms — one handler, one base price and
|
|
2859
|
+
* an optional per-KiB rate — and the terms do not vary with what is being sent
|
|
2860
|
+
* (only the arithmetic over the sealed size does), so asking again per packet
|
|
2861
|
+
* would buy nothing but latency.
|
|
2855
2862
|
*/
|
|
2856
2863
|
declare class ConnectorEdgeClient {
|
|
2857
2864
|
private readonly fetchImpl;
|
|
@@ -2963,8 +2970,8 @@ declare class ConnectorEdgeClient {
|
|
|
2963
2970
|
* a transport failure throws {@link NetworkError} instead, so a caller can
|
|
2964
2971
|
* always tell "not mine" from "could not ask".
|
|
2965
2972
|
*
|
|
2966
|
-
* Fetched once per (endpoint, destination) and reused. ADR 0020
|
|
2967
|
-
*
|
|
2973
|
+
* Fetched once per (endpoint, destination) and reused. ADR 0020 gives a
|
|
2974
|
+
* handler one set of terms, which do not vary with the packet — a route
|
|
2968
2975
|
* being repriced is an operator event, and {@link invalidateRoutePrice} is
|
|
2969
2976
|
* how a caller reacts to one.
|
|
2970
2977
|
*
|
|
@@ -3323,9 +3330,10 @@ declare function fundWallet(faucetUrl: string, address: string, chain: FaucetCha
|
|
|
3323
3330
|
* send, and what comes back.
|
|
3324
3331
|
*
|
|
3325
3332
|
* One idea underlies all of it. A **connector** is a paid reverse proxy: it
|
|
3326
|
-
* fronts an ordinary HTTP app, charges a
|
|
3327
|
-
*
|
|
3328
|
-
* "publish" or "post" — it
|
|
3333
|
+
* fronts an ordinary HTTP app, charges a base price plus an optional
|
|
3334
|
+
* per-kibibyte rate per route, and hands the app a request that was already
|
|
3335
|
+
* paid for. So the client's central operation is not "publish" or "post" — it
|
|
3336
|
+
* is {@link ToonClientLike.send}, which puts one HTTP
|
|
3329
3337
|
* request through a connector and gives you back the app's HTTP response, having
|
|
3330
3338
|
* paid for it with a voucher — a signed, cumulative claim on an x402
|
|
3331
3339
|
* `batch-settlement` channel — that travels *with* the packet (connector ADRs
|
|
@@ -4792,6 +4800,11 @@ declare function readResponseMeta(headers: ResponseHeaderSource): IlpResponseMet
|
|
|
4792
4800
|
interface HttpIlpClientConfig {
|
|
4793
4801
|
/** The peer's `POST /ilp` URL (the `httpEndpoint` from discovery). */
|
|
4794
4802
|
httpEndpoint: string;
|
|
4803
|
+
/**
|
|
4804
|
+
* Where `httpEndpoint` came from, so a network failure can say so. Omit when
|
|
4805
|
+
* the caller supplied it.
|
|
4806
|
+
*/
|
|
4807
|
+
endpointSource?: EndpointSource;
|
|
4795
4808
|
/**
|
|
4796
4809
|
* Optional peer identity. With no `peerId`/`authToken` the connector treats
|
|
4797
4810
|
* the request as an anonymous no-auth peer (permissionless default) and
|
|
@@ -4828,6 +4841,7 @@ interface HttpIlpClientConfig {
|
|
|
4828
4841
|
*/
|
|
4829
4842
|
declare class HttpIlpClient implements IlpClient {
|
|
4830
4843
|
private readonly httpEndpoint;
|
|
4844
|
+
private readonly endpointSource;
|
|
4831
4845
|
private readonly peerId;
|
|
4832
4846
|
private readonly authToken;
|
|
4833
4847
|
private readonly timeout;
|
|
@@ -5020,6 +5034,13 @@ interface BtpPaidWriteTransportConfig {
|
|
|
5020
5034
|
* lazily on first use and never disconnected between writes.
|
|
5021
5035
|
*/
|
|
5022
5036
|
session: OrderedBtpSession;
|
|
5037
|
+
/**
|
|
5038
|
+
* The `ws(s)://` URL the session dials, so a connection failure can name it.
|
|
5039
|
+
* Omit and a failure carries the session's own message alone.
|
|
5040
|
+
*/
|
|
5041
|
+
url?: string;
|
|
5042
|
+
/** Where `url` came from, so a failure can say the node chose it. */
|
|
5043
|
+
endpointSource?: EndpointSource;
|
|
5023
5044
|
/**
|
|
5024
5045
|
* Stateless fallback used once a write's reconnect budget is exhausted.
|
|
5025
5046
|
* Typically an `HttpIlpClient` pointed at the same connector's `POST /ilp`.
|
|
@@ -5043,6 +5064,8 @@ interface BtpPaidWriteTransportConfig {
|
|
|
5043
5064
|
declare class BtpPaidWriteTransport implements ClaimSendingTransport {
|
|
5044
5065
|
private readonly session;
|
|
5045
5066
|
private readonly fallback;
|
|
5067
|
+
private readonly url;
|
|
5068
|
+
private readonly endpointSource;
|
|
5046
5069
|
private readonly maxReconnectAttempts;
|
|
5047
5070
|
private readonly reconnectDelay;
|
|
5048
5071
|
/**
|
|
@@ -5076,6 +5099,11 @@ declare class BtpPaidWriteTransport implements ClaimSendingTransport {
|
|
|
5076
5099
|
sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;
|
|
5077
5100
|
/** Connect if need be, then send once. No claim, so nothing to re-spend. */
|
|
5078
5101
|
private dispatchUnpaid;
|
|
5102
|
+
/**
|
|
5103
|
+
* A connection-level failure becomes a {@link NetworkError} naming the BTP
|
|
5104
|
+
* URL, with the original kept as `cause`. Anything else passes through.
|
|
5105
|
+
*/
|
|
5106
|
+
private nameEndpoint;
|
|
5079
5107
|
/**
|
|
5080
5108
|
* One write's worth of connect/send/reconnect/fallback policy. Runs
|
|
5081
5109
|
* strictly after every write enqueued ahead of it has settled.
|
|
@@ -6980,4 +7008,4 @@ interface RetryOptions {
|
|
|
6980
7008
|
*/
|
|
6981
7009
|
declare function withRetry<T>(operation: () => Promise<T>, options: RetryOptions): Promise<T>;
|
|
6982
7010
|
|
|
6983
|
-
export { ACCUMULATED_COST_HEADER, ACCUMULATED_COST_PROTOCOL, ARNS_KIND, type AntSpawnOutcome, type AntSpawnParams, type AntSpawnRefused, type AntSpawnStep, type AntSpawned, type ArnsAntPrepareReceipt, type ArnsBuyOutcome, type ArnsBuyParams, type ArnsBuyReceipt, type ArnsNameType, type ArnsNameWithAntOutcome, type ArnsNetwork, type BTPMessage, BTPMessageType, type BTPProtocolData, type BatchChannel, type BatchChannelConfig, BatchChannelManager, type BatchChannelSummary, type BatchDepositPayload, type BatchExitResult, type BatchSettlementBinding, type BatchSettlementEvmOffer, type BatchSettlementOffer, BatchSettlementPayer, type BatchSettlementPayerConfig, type BatchSettlementSvmOffer, type BatchSettlementTerms, type BatchVoucher, BeforePayRefusedError, BtpAuthError, type BtpChannelDeclaration, BtpConnectionError, type BtpPacketResponse, BtpPaidWriteTransport, type BtpPaidWriteTransportConfig, BtpRuntimeClient, type BtpRuntimeClientConfig, CHANNEL_CHALLENGE_MAX_LIFETIME_SECONDS, CLAIM_ACK_HEADER, CLAIM_ACK_PROTOCOL, CLAIM_REJECT_REASONS, CONNECTOR_MAX_TIMEOUT_SECONDS, ChainKind, ChainUnavailableError, type ChannelBinding, type ChannelBindingContext, type ChannelFacade, type ChannelFacadeDeps, ChannelFundingError, ChannelNotOpenError, ChannelResumeError, type ChannelState, type ChannelStore, type ChannelStoreEntry, type ClaimAck, type ClaimSendingTransport$1 as ClaimSendingTransport, type ClaimStateFailed, type ClaimStateOk, type ClaimStateRequestEntry, type ClaimStateResult, type ClaimSummary, ClientChannelFacade, ClientWalletFacade, ConfigError, ConnectorEdgeClient, type ConnectorEdgeClientConfig, ConnectorEdgeError, type ConnectorEdgeErrorCode, ConnectorError, type ConnectorIdentity, type ConnectorRoutePrice, type ConnectorRouteTerms, type ContractReader, DEFAULT_DEPOSIT, DEFAULT_TIMEOUT_MS, DEVNET, type Decoded, type DepositExtensions, type DeriveIdentityOptions, type DerivedIdentity, type DevnetNode, EIP2612_GAS_SPONSORING, ERC20_APPROVAL_GAS_SPONSORING, ERC3009_DEPOSIT_COLLECTOR_ADDRESS, type EdgeIdentity, type Eip3009DepositPayload, type EncryptedKeystore, type Envelope, EnvelopeError, EnvelopeErrorKind, type EnvelopeHeader, type EnvelopeRequest, type EnvelopeResponse, type EvmBatchChannelState, type EvmExitClients, EvmSigner, type EvmWalletAccess, type ExchangeOutcome, FULFILLMENT_MISMATCH_CODE, FULFILLMENT_MISMATCH_MESSAGE, FacilitatorError, type FaucetChain, type FundWalletOptions, type FundWalletResult, GIFTWRAP_NONCE_LENGTH, GIFTWRAP_PUBLIC_KEY_LENGTH, GIFTWRAP_SECRET_LENGTH, GIFTWRAP_TYPE_REQUEST, GIFTWRAP_TYPE_RESPONSE, type GasStationExecuteReceipt, type GasStationFailureReason, type GasStationFailureReceipt, type GasStationQuoteReceipt, type GasStationReceipt, type GiftWrapEcdh, GiftWrapError, GiftWrapErrorKind, HS_HOSTNAME_MAX_LENGTH, HS_HOSTNAME_REGEX, HttpIlpClient, type HttpIlpClientConfig, type ILPFulfillPacket, ILPPacketType, type ILPPreparePacket, type ILPRejectPacket, type ILPResponsePacket, ILP_CLAIM_HEADER, ILP_PEER_ID_HEADER, type IlpClient, type IlpResponseMeta, type IlpSendParams, type IlpSendResult, type IlpSendResultWithFulfillment, InMemoryChannelStore, InsufficientBalanceError, InvalidAddressError, IsomorphicBtpClient, type JobAnswer, type JobEndpoint, type JobEvent, type JobEventParams, type JobSender, JsonFileChannelStore, KEYSTORE_VERSION, type KeyDerivationScheme, MAX_GRACE_PERIOD_SECONDS, MAX_WITHDRAW_DELAY_SECONDS, MIN_GRACE_PERIOD_SECONDS, MIN_WITHDRAW_DELAY_SECONDS, NetworkError, type NodeSelfDescription, OerError, OerErrorKind, type OpenedKeystore, type OpenedRequest, PACKET_EXPIRY_HEADROOM_MS, PAYMENT_CHANNELS_PROGRAM_ID, PAYMENT_REQUIRED_HEADER, PAYMENT_REQUIRED_PROTOCOL, PERMIT2_ADDRESS, PERMIT2_DEPOSIT_COLLECTOR_ADDRESS, PROXIED_RPC_DEFAULTS, type PaidWriteTransport, type ParsedX402Challenge, PaymentRequiredError, type PaymentTerms, type Permit2DepositPayload, type PreparedVoucher, type ProxiedChainRpc, type RequiredTransport, type ResolvedConfig, type ResolvedIdentity, type ResponseHeaderSource, type RetryOptions, type RouteCharge, RouteNotPricedError, type RoutePrice, type RpcTransportOptions, SOLANA_GAS_KIND, type SealedExchange, type SealedRequest, SealedResponseError, type SealedResponseErrorKind, type SendContext, type SendFulfilled, type SendOptions, type SendRefused, type SendRequest, type SendResult, type SendTransferParams, type SendTransferResult, type SettledDeposit, type Signer as SolanaKeypair, type SolanaNetwork, SolanaRpcTransportError, type SolanaWireTransaction, SponsorRefusedError, type SponsoredOpen, StaleRpcReadError, type SvmBatchChannelConfig, type SvmBatchChannelState, type SvmBatchVoucher, ToonClient, type ToonClientConfig, ToonClientError, type ToonClientLike, type ToonGreeting, type ToonIdentity, type ToonTermsInfo, TransactionOutcomeError, type TransferConfig, TransferNotDeliveredError, TransferUnsupportedError, type TransportChoice, type TransportPreference, TransportRequiredError, type TypedDataSigner, UnknownChainError, ValidationError, type VoucherClaimEnvelope, type VoucherOutcome, type VoucherSigner, type WalletBalance, type WalletBalanceSources, type WalletChainBalances, type WalletFacade, type WalletFacadeDeps, type WalletTokenAmount, type WriteKeystoreOptions, X402_BATCH_SETTLEMENT_ADDRESS, X402_BATCH_SETTLEMENT_DEPOSIT_ABI, X402_BATCH_SETTLEMENT_EXIT_ABI, X402_BATCH_SETTLEMENT_READ_ABI, addressFor, approvePermit2, assertRoutableHsHostname, batchChannelId, batchVoucherDigest, buildBatchChannelConfig, buildEip3009Deposit, buildJobEvent, buildPermit2Deposit, buildResponseMeta, buildSponsoredOpen, buildSvmBatchChannelConfig, buildSvmRequestCloseInstruction, buildSvmSealInstruction, buildSvmTopUpInstruction, buildSvmVoucherMessage, buildSvmWithdrawPayerInstruction, buyArnsName, buyArnsNameWithNewAnt, chainUnavailableMessage, chargeFor, chooseBatchSettlement, connectorEdgeBaseUrl, decodeAccumulatedCost, decodeBase64Text, decodeClaimAck, decodeEnvelope, decodeEnvelopeRequest, decodeEnvelopeResponse, decodePaymentRequired, decodeSvmBatchChannel, decodeVarOctetString, decodeVarUint, decryptMnemonic, defaultDestinationFor, defaultFacilitatorFor, defaultFaucetTimeout, defaultRpcUrl, depositDirectly, deriveFulfillment, deriveFullIdentity, deserializeIlpPacket, deserializeIlpPrepare, eip2612Nonce, eip2612PermitData, encodeEnvelope, encodeEnvelopeRequest, encodeEnvelopeResponse, encodeVarOctetString, encodeVarUint, encryptMnemonic, envelopeHeader, erc3009CollectorData, evmChainIdOf, evmChallengeDigest, evmDerivationPath, evmIdentityFromKey, evmVoucherClaim, evmWalletAccess, facilitatorExtensions, finalizeEvmBatchWithdraw, fundWallet, generateKeystore, generateMnemonic, generateRandomIdentity, generateSolanaKeypair, getSvmBatchChannel, giftWrapPublicKey, httpEndpointToBtpUrl, importKeystore, initiateEvmBatchWithdraw, isGasStationFailure, isHiddenServiceUrl, isInsufficientGasError, isRoutableHsHostname, jobEventParam, keystoreDerivation, loadKeystore, localGiftWrapEcdh, looksLikeSealedResponse, mapIlpResponse, nextVoucherAmount, offerFromTerms, openKeystore, openRequest, openResponse, parseBatchSettlementOffer, parseBatchSettlementTerms, parseBtpMessage, parsePaymentTerms, parseSelfDescription, parseSolanaWireTransaction, parseX402Body, parseX402Challenge, patchSolanaRecentBlockhash, paymentChannelsEventAuthority, permit2Allowance, permit2CollectorData, readBaseUnits, readResponseMeta$1 as readBtpResponseMeta, readEvmBatchChannel, readEvmNativeBalance, readEvmTokenBalance, readExchangeOutcome, readResponseMeta, readSolanaNativeBalance, readSolanaTokenBalance, readVoucherRefusal, readWalletBalances, requestSponsoredOpen, requestSvmBatchClose, resolveConfig, resolveExpectedFulfillment, resolveExpiresAt, routeFor, routePriceFor, rpcFetch, rpcTransport, sealExchange, sealRequest, sealRequestWithRandomness, sealResponse, sealResponseWithRandomness, selectTransport, send, sendJob, sendTransfer, serializeBtpMessage, serializeIlpFulfill, serializeIlpPrepare, serializeIlpReject, settleDeposit, signBatchVoucher, signEip2612GasSponsoring, signErc20ApprovalGasSponsoring, signEvmChallenge, signSolanaChallenge, signSolanaWireTransaction, signSvmVoucher, singleRecipientDistributionHash, solanaChallengeMessage, solanaKeypair, solanaVoucherClaim, spawnAnt, svmBatchChannelAddress, toEnvelopeRequest, trimTrailingSlashes, validateMnemonic, withRetry, withdrawSvmBatchChannel, writeKeystoreFile };
|
|
7011
|
+
export { ACCUMULATED_COST_HEADER, ACCUMULATED_COST_PROTOCOL, ARNS_KIND, type AntSpawnOutcome, type AntSpawnParams, type AntSpawnRefused, type AntSpawnStep, type AntSpawned, type ArnsAntPrepareReceipt, type ArnsBuyOutcome, type ArnsBuyParams, type ArnsBuyReceipt, type ArnsNameType, type ArnsNameWithAntOutcome, type ArnsNetwork, type BTPMessage, BTPMessageType, type BTPProtocolData, type BatchChannel, type BatchChannelConfig, BatchChannelManager, type BatchChannelSummary, type BatchDepositPayload, type BatchExitResult, type BatchSettlementBinding, type BatchSettlementEvmOffer, type BatchSettlementOffer, BatchSettlementPayer, type BatchSettlementPayerConfig, type BatchSettlementSvmOffer, type BatchSettlementTerms, type BatchVoucher, BeforePayRefusedError, BtpAuthError, type BtpChannelDeclaration, BtpConnectionError, type BtpPacketResponse, BtpPaidWriteTransport, type BtpPaidWriteTransportConfig, BtpRuntimeClient, type BtpRuntimeClientConfig, CHANNEL_CHALLENGE_MAX_LIFETIME_SECONDS, CLAIM_ACK_HEADER, CLAIM_ACK_PROTOCOL, CLAIM_REJECT_REASONS, CONNECTOR_MAX_TIMEOUT_SECONDS, ChainKind, ChainUnavailableError, type ChannelBinding, type ChannelBindingContext, type ChannelFacade, type ChannelFacadeDeps, ChannelFundingError, ChannelNotOpenError, ChannelResumeError, type ChannelState, type ChannelStore, type ChannelStoreEntry, type ClaimAck, type ClaimSendingTransport$1 as ClaimSendingTransport, type ClaimStateFailed, type ClaimStateOk, type ClaimStateRequestEntry, type ClaimStateResult, type ClaimSummary, ClientChannelFacade, ClientWalletFacade, ConfigError, ConnectorEdgeClient, type ConnectorEdgeClientConfig, ConnectorEdgeError, type ConnectorEdgeErrorCode, ConnectorError, type ConnectorIdentity, type ConnectorRoutePrice, type ConnectorRouteTerms, type ContractReader, DEFAULT_DEPOSIT, DEFAULT_TIMEOUT_MS, DEVNET, type Decoded, type DepositExtensions, type DeriveIdentityOptions, type DerivedIdentity, type DevnetNode, EIP2612_GAS_SPONSORING, ERC20_APPROVAL_GAS_SPONSORING, ERC3009_DEPOSIT_COLLECTOR_ADDRESS, type EdgeIdentity, type Eip3009DepositPayload, type EncryptedKeystore, type EndpointSource, type Envelope, EnvelopeError, EnvelopeErrorKind, type EnvelopeHeader, type EnvelopeRequest, type EnvelopeResponse, type EvmBatchChannelState, type EvmExitClients, EvmSigner, type EvmWalletAccess, type ExchangeOutcome, FULFILLMENT_MISMATCH_CODE, FULFILLMENT_MISMATCH_MESSAGE, FacilitatorError, type FaucetChain, type FundWalletOptions, type FundWalletResult, GIFTWRAP_NONCE_LENGTH, GIFTWRAP_PUBLIC_KEY_LENGTH, GIFTWRAP_SECRET_LENGTH, GIFTWRAP_TYPE_REQUEST, GIFTWRAP_TYPE_RESPONSE, type GasStationExecuteReceipt, type GasStationFailureReason, type GasStationFailureReceipt, type GasStationQuoteReceipt, type GasStationReceipt, type GiftWrapEcdh, GiftWrapError, GiftWrapErrorKind, HS_HOSTNAME_MAX_LENGTH, HS_HOSTNAME_REGEX, HttpIlpClient, type HttpIlpClientConfig, type ILPFulfillPacket, ILPPacketType, type ILPPreparePacket, type ILPRejectPacket, type ILPResponsePacket, ILP_CLAIM_HEADER, ILP_PEER_ID_HEADER, type IlpClient, type IlpResponseMeta, type IlpSendParams, type IlpSendResult, type IlpSendResultWithFulfillment, InMemoryChannelStore, InsufficientBalanceError, InvalidAddressError, IsomorphicBtpClient, type JobAnswer, type JobEndpoint, type JobEvent, type JobEventParams, type JobSender, JsonFileChannelStore, KEYSTORE_VERSION, type KeyDerivationScheme, MAX_GRACE_PERIOD_SECONDS, MAX_WITHDRAW_DELAY_SECONDS, MIN_GRACE_PERIOD_SECONDS, MIN_WITHDRAW_DELAY_SECONDS, NetworkError, type NodeSelfDescription, OerError, OerErrorKind, type OpenedKeystore, type OpenedRequest, PACKET_EXPIRY_HEADROOM_MS, PAYMENT_CHANNELS_PROGRAM_ID, PAYMENT_REQUIRED_HEADER, PAYMENT_REQUIRED_PROTOCOL, PERMIT2_ADDRESS, PERMIT2_DEPOSIT_COLLECTOR_ADDRESS, PROXIED_RPC_DEFAULTS, type PaidWriteTransport, type ParsedX402Challenge, PaymentRequiredError, type PaymentTerms, type Permit2DepositPayload, type PreparedVoucher, type ProxiedChainRpc, type RequiredTransport, type ResolvedConfig, type ResolvedIdentity, type ResponseHeaderSource, type RetryOptions, type RouteCharge, RouteNotPricedError, type RoutePrice, type RpcTransportOptions, SOLANA_GAS_KIND, type SealedExchange, type SealedRequest, SealedResponseError, type SealedResponseErrorKind, type SendContext, type SendFulfilled, type SendOptions, type SendRefused, type SendRequest, type SendResult, type SendTransferParams, type SendTransferResult, type SettledDeposit, type Signer as SolanaKeypair, type SolanaNetwork, SolanaRpcTransportError, type SolanaWireTransaction, SponsorRefusedError, type SponsoredOpen, StaleRpcReadError, type SvmBatchChannelConfig, type SvmBatchChannelState, type SvmBatchVoucher, ToonClient, type ToonClientConfig, ToonClientError, type ToonClientLike, type ToonGreeting, type ToonIdentity, type ToonTermsInfo, TransactionOutcomeError, type TransferConfig, TransferNotDeliveredError, TransferUnsupportedError, type TransportChoice, type TransportPreference, TransportRequiredError, type TypedDataSigner, UnknownChainError, ValidationError, type VoucherClaimEnvelope, type VoucherOutcome, type VoucherSigner, type WalletBalance, type WalletBalanceSources, type WalletChainBalances, type WalletFacade, type WalletFacadeDeps, type WalletTokenAmount, type WriteKeystoreOptions, X402_BATCH_SETTLEMENT_ADDRESS, X402_BATCH_SETTLEMENT_DEPOSIT_ABI, X402_BATCH_SETTLEMENT_EXIT_ABI, X402_BATCH_SETTLEMENT_READ_ABI, addressFor, approvePermit2, assertRoutableHsHostname, batchChannelId, batchVoucherDigest, buildBatchChannelConfig, buildEip3009Deposit, buildJobEvent, buildPermit2Deposit, buildResponseMeta, buildSponsoredOpen, buildSvmBatchChannelConfig, buildSvmRequestCloseInstruction, buildSvmSealInstruction, buildSvmTopUpInstruction, buildSvmVoucherMessage, buildSvmWithdrawPayerInstruction, buyArnsName, buyArnsNameWithNewAnt, chainUnavailableMessage, chargeFor, chooseBatchSettlement, connectorEdgeBaseUrl, decodeAccumulatedCost, decodeBase64Text, decodeClaimAck, decodeEnvelope, decodeEnvelopeRequest, decodeEnvelopeResponse, decodePaymentRequired, decodeSvmBatchChannel, decodeVarOctetString, decodeVarUint, decryptMnemonic, defaultDestinationFor, defaultFacilitatorFor, defaultFaucetTimeout, defaultRpcUrl, depositDirectly, deriveFulfillment, deriveFullIdentity, describeEndpoint, deserializeIlpPacket, deserializeIlpPrepare, eip2612Nonce, eip2612PermitData, encodeEnvelope, encodeEnvelopeRequest, encodeEnvelopeResponse, encodeVarOctetString, encodeVarUint, encryptMnemonic, envelopeHeader, erc3009CollectorData, evmChainIdOf, evmChallengeDigest, evmDerivationPath, evmIdentityFromKey, evmVoucherClaim, evmWalletAccess, facilitatorExtensions, finalizeEvmBatchWithdraw, fundWallet, generateKeystore, generateMnemonic, generateRandomIdentity, generateSolanaKeypair, getSvmBatchChannel, giftWrapPublicKey, httpEndpointToBtpUrl, importKeystore, initiateEvmBatchWithdraw, isGasStationFailure, isHiddenServiceUrl, isInsufficientGasError, isRoutableHsHostname, jobEventParam, keystoreDerivation, loadKeystore, localGiftWrapEcdh, looksLikeSealedResponse, mapIlpResponse, nextVoucherAmount, offerFromTerms, openKeystore, openRequest, openResponse, parseBatchSettlementOffer, parseBatchSettlementTerms, parseBtpMessage, parsePaymentTerms, parseSelfDescription, parseSolanaWireTransaction, parseX402Body, parseX402Challenge, patchSolanaRecentBlockhash, paymentChannelsEventAuthority, permit2Allowance, permit2CollectorData, readBaseUnits, readResponseMeta$1 as readBtpResponseMeta, readEvmBatchChannel, readEvmNativeBalance, readEvmTokenBalance, readExchangeOutcome, readResponseMeta, readSolanaNativeBalance, readSolanaTokenBalance, readVoucherRefusal, readWalletBalances, requestSponsoredOpen, requestSvmBatchClose, resolveConfig, resolveExpectedFulfillment, resolveExpiresAt, routeFor, routePriceFor, rpcFetch, rpcTransport, sealExchange, sealRequest, sealRequestWithRandomness, sealResponse, sealResponseWithRandomness, selectTransport, send, sendJob, sendTransfer, serializeBtpMessage, serializeIlpFulfill, serializeIlpPrepare, serializeIlpReject, settleDeposit, signBatchVoucher, signEip2612GasSponsoring, signErc20ApprovalGasSponsoring, signEvmChallenge, signSolanaChallenge, signSolanaWireTransaction, signSvmVoucher, singleRecipientDistributionHash, solanaChallengeMessage, solanaKeypair, solanaVoucherClaim, spawnAnt, svmBatchChannelAddress, toEnvelopeRequest, trimTrailingSlashes, validateMnemonic, withRetry, withdrawSvmBatchChannel, writeKeystoreFile };
|
package/dist/index.js
CHANGED
|
@@ -128,6 +128,7 @@ import {
|
|
|
128
128
|
defaultFaucetTimeout,
|
|
129
129
|
depositDirectly,
|
|
130
130
|
deriveFulfillment,
|
|
131
|
+
describeEndpoint,
|
|
131
132
|
deserializeIlpPacket,
|
|
132
133
|
deserializeIlpPrepare,
|
|
133
134
|
eip2612Nonce,
|
|
@@ -223,7 +224,7 @@ import {
|
|
|
223
224
|
trimTrailingSlashes,
|
|
224
225
|
withRetry,
|
|
225
226
|
withdrawSvmBatchChannel
|
|
226
|
-
} from "./chunk-
|
|
227
|
+
} from "./chunk-GNPJRJ6U.js";
|
|
227
228
|
import {
|
|
228
229
|
DEVNET,
|
|
229
230
|
HS_HOSTNAME_MAX_LENGTH,
|
|
@@ -723,6 +724,7 @@ export {
|
|
|
723
724
|
depositDirectly,
|
|
724
725
|
deriveFulfillment,
|
|
725
726
|
deriveFullIdentity,
|
|
727
|
+
describeEndpoint,
|
|
726
728
|
deserializeIlpPacket,
|
|
727
729
|
deserializeIlpPrepare,
|
|
728
730
|
eip2612Nonce,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/jobs/job-event.ts","../src/jobs/send-job.ts","../src/jobs/receipts.ts","../src/jobs/ant-spawn.ts"],"sourcesContent":["/**\n * The signed job event a NIP-90 app behind a connector reads.\n *\n * Some apps a connector fronts are not plain HTTP handlers: the store and the\n * gas station both take their input as a **kind-tagged Nostr event** whose\n * arguments are `['param', key, value]` tags, and answer in the FULFILL body.\n * There is no relay and no round trip — the event is the request body of the\n * paid POST, and the receipt comes back in that same response.\n *\n * The signature on the event is **integrity, not identity**. Both apps say so\n * in as many words: it proves the tags were not altered between this client and\n * the handler, and nothing else — who paid is the connector's `X-TOON-Payer`\n * header, proved against a claim, and no app takes an event pubkey for an\n * authority. So the key here is generated per event by default. A caller who\n * wants a stable pubkey in the app's logs can supply one; nothing about the\n * job's outcome depends on which key it is.\n *\n * This is why the 1.0 client carries no Nostr identity. There is no key to\n * derive, back up or rotate — only 32 bytes to sign one request with and then\n * forget.\n */\n\nimport { schnorr } from '@noble/curves/secp256k1.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { encodeUtf8, toHex } from '../utils/binary.js';\n\n/**\n * A signed Nostr event, in the field order and JSON spelling every verifier\n * expects.\n */\nexport interface JobEvent {\n /** 32-byte sha256 of the serialization below, hex. */\n id: string;\n /** The signing key's x-only public half, hex. */\n pubkey: string;\n /** Unix SECONDS. */\n created_at: number;\n kind: number;\n tags: string[][];\n content: string;\n /** BIP-340 signature over `id`, hex. */\n sig: string;\n}\n\n/** What one job asks for: its kind, and its `param` tags. */\nexport interface JobEventParams {\n /** The NIP-90 job kind — `5095` for the ArNS job, `5096` for Solana gas. */\n kind: number;\n /**\n * The job's arguments, emitted in iteration order as `['param', key, value]`.\n * An `undefined` value is omitted rather than sent as the string\n * `\"undefined\"`, so an optional parameter can be passed through unset.\n */\n params: Record<string, string | undefined>;\n /** Extra tags to carry beside the params. Rarely needed. */\n tags?: string[][];\n /** Default `''`. Neither of this repository's job kinds reads it. */\n content?: string;\n /** 32-byte secp256k1 secret. Default: a fresh one, used once. */\n secretKey?: Uint8Array;\n /** Unix seconds. Default `Date.now() / 1000`, floored. */\n createdAt?: number;\n}\n\n/**\n * NIP-01 serialization: a six-element array, `JSON.stringify`d exactly as\n * written. The verifier recomputes this from the event's own fields, so any\n * difference in shape — a reordered key, a number where a string belongs —\n * surfaces as an id mismatch rather than as a validation message.\n */\nfunction serializeForId(event: Omit<JobEvent, 'id' | 'sig'>): string {\n return JSON.stringify([\n 0,\n event.pubkey,\n event.created_at,\n event.kind,\n event.tags,\n event.content,\n ]);\n}\n\n/**\n * Build and sign one job event.\n *\n * @returns The event, ready to be the `{ event }` body of a paid POST.\n */\nexport function buildJobEvent(params: JobEventParams): JobEvent {\n const secretKey = params.secretKey ?? randomBytes(32);\n const pubkey = toHex(new Uint8Array(schnorr.getPublicKey(secretKey)));\n\n const tags: string[][] = [];\n for (const [key, value] of Object.entries(params.params)) {\n if (value !== undefined) tags.push(['param', key, value]);\n }\n if (params.tags) tags.push(...params.tags);\n\n const unsigned = {\n pubkey,\n created_at: params.createdAt ?? Math.floor(Date.now() / 1000),\n kind: params.kind,\n tags,\n content: params.content ?? '',\n };\n\n const idBytes = sha256(encodeUtf8(serializeForId(unsigned)));\n return {\n ...unsigned,\n id: toHex(idBytes),\n sig: toHex(new Uint8Array(schnorr.sign(idBytes, secretKey))),\n };\n}\n\n/** First value of a `['param', key, value]` tag, if the event carries one. */\nexport function jobEventParam(event: JobEvent, key: string): string | undefined {\n for (const tag of event.tags) {\n if (tag[0] === 'param' && tag[1] === key) return tag[2];\n }\n return undefined;\n}\n","/**\n * Putting a {@link JobEvent} through a connector, and reading what came back.\n *\n * A job is an ordinary paid request — `POST` the event to the route, get the\n * app's HTTP response — so this adds no wire of its own. What it adds is the\n * one decoding rule both NIP-90 apps in this protocol share, and a single\n * vocabulary for the three quite different ways a job can fail to produce a\n * receipt:\n *\n * - **the packet was refused** — a price, a route or a seal was wrong, and the\n * app was never reached. `send()` returns this rather than throwing, and so\n * does {@link sendJob};\n * - **the app rejected the event** — a missing param, an unregistered kind.\n * It rides home on a FULFILL with `accept: false`, so it cost what a receipt\n * would have cost;\n * - **the app answered, and the answer is a refusal.** A gas station that\n * declines to spend has done its job: `accept: true`, a receipt, and\n * `status: 'failed'` inside it. That is NOT this module's business — it is a\n * successful job, and the caller branches on the receipt's own `reason`.\n *\n * The decoding rule: a receipt is `base64(JSON)` in `data`, and both apps ALSO\n * decode it into `result` for readability. `data` is the byte-faithful one and\n * is preferred here; `result` is the fallback, so a future app that emits only\n * one of the two still works.\n */\n\nimport { fromBase64, decodeUtf8 } from '../utils/binary.js';\nimport type { SendRefused, SendRequest, SendResult, SendOptions } from '../client/types.js';\nimport type { JobEvent } from './job-event.js';\n\n/**\n * The part of a client a job needs: the ability to pay for one HTTP request.\n * `ToonClient` satisfies it, and so does any stand-in a test supplies.\n */\nexport interface JobSender {\n send(\n destination: string,\n request?: SendRequest,\n options?: SendOptions\n ): Promise<SendResult>;\n}\n\n/**\n * Where a job goes: who pays for it, which route terminates it, and — on a\n * FORWARDED route — whose key the payload is sealed to.\n *\n * The store and the gas station MAY be different nodes with different\n * connectors and different channels, so a ceremony spanning both takes two\n * endpoints. Where one connector terminates both — as the devnet's does, at\n * `https://toonprotocol.dev` — both endpoints name the same client and no\n * `sealTo` is needed. Where a node only forwards to one of them, `sealTo` names\n * the far node.\n */\nexport interface JobEndpoint {\n /** Pays for the request. */\n client: JobSender;\n /** The ILP address of the route that terminates at the app. */\n destination: string;\n /** The terminating connector, when `destination` is forwarded. */\n sealTo?: string | Uint8Array;\n /** Per-packet timeout, in milliseconds. */\n timeoutMs?: number;\n}\n\n/**\n * What a job produced: a decoded receipt, or the reason there is none.\n *\n * `accepted: false` never means \"the app said no to what you asked\" — that is a\n * receipt. It means the receipt does not exist: the packet was refused, or the\n * app rejected the event before running it.\n */\nexport type JobAnswer<T> =\n | { accepted: true; receipt: T }\n | {\n accepted: false;\n /** An ILP reject code for a refusal, or the app's own `F00` / `T00`. */\n code: string;\n message: string;\n /** Present when the packet never reached the app. */\n refusal?: SendRefused;\n };\n\n/** The `{ accept, data, result, code, message }` envelope both apps answer in. */\ninterface JobEnvelope {\n accept?: boolean;\n data?: string;\n result?: unknown;\n /**\n * The store's answer when its `data` is NOT JSON — kind:5094 returns a bare\n * Arweave transaction id, and the backend surfaces it here rather than under\n * `result`. A documented contract, not a quirk.\n */\n txId?: unknown;\n code?: string;\n message?: string;\n}\n\n/**\n * Pay for one job and decode its receipt.\n *\n * The receipt type is the caller's assertion, not a checked fact: these apps\n * publish their receipt shapes and this client mirrors them, but nothing on the\n * wire enforces the match, so a caller reading a field it needs should still\n * check it is there.\n */\nexport async function sendJob<T>(\n endpoint: JobEndpoint,\n event: JobEvent\n): Promise<JobAnswer<T>> {\n const answer = await endpoint.client.send(\n endpoint.destination,\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: { event },\n },\n {\n ...(endpoint.sealTo !== undefined ? { sealTo: endpoint.sealTo } : {}),\n ...(endpoint.timeoutMs !== undefined ? { timeoutMs: endpoint.timeoutMs } : {}),\n }\n );\n\n if (!answer.fulfilled) {\n return {\n accepted: false,\n code: answer.code,\n message: `kind:${event.kind} refused by ${answer.refusedBy}: ${answer.message}`,\n refusal: answer,\n };\n }\n\n let envelope: JobEnvelope;\n try {\n envelope = answer.json<JobEnvelope>();\n } catch {\n return {\n accepted: false,\n code: 'F00',\n message:\n `kind:${event.kind} answered ${answer.status} with a body that is not JSON: ` +\n truncate(decodeUtf8(answer.body)),\n };\n }\n\n if (envelope.accept !== true) {\n return {\n accepted: false,\n code: envelope.code ?? String(answer.status),\n message: envelope.message ?? `kind:${event.kind} was not accepted`,\n };\n }\n\n const receipt = decodeReceipt<T>(envelope);\n if (receipt === undefined) {\n return {\n accepted: false,\n code: 'F00',\n message: `kind:${event.kind} was accepted but carried no receipt`,\n };\n }\n return { accepted: true, receipt };\n}\n\n/**\n * `data` (byte-faithful) if it decodes as JSON; otherwise whichever field the\n * app said its answer in.\n *\n * The store decides between two of those by whether its base64 `data` parses\n * as a JSON object: a receipt goes to `result`, and anything else goes to\n * `txId`. kind:5094 takes the second branch — its whole answer is one Arweave\n * transaction id — so a client that reads only `result` calls a successful\n * upload \"accepted but carried no receipt\".\n */\nfunction decodeReceipt<T>(envelope: JobEnvelope): T | undefined {\n if (typeof envelope.data === 'string') {\n try {\n return JSON.parse(decodeUtf8(fromBase64(envelope.data))) as T;\n } catch {\n // Fall through: an app that base64'd something that is not JSON has still\n // said what it meant in `result` or `txId`.\n }\n }\n if (envelope.result !== null && typeof envelope.result === 'object') {\n return envelope.result as T;\n }\n // A bare id is still a receipt. Wrapped, so the caller reads `receipt.txId`\n // the same way every other job's fields are read.\n if (typeof envelope.txId === 'string' && envelope.txId.length > 0) {\n return { txId: envelope.txId } as T;\n }\n return undefined;\n}\n\nfunction truncate(text: string): string {\n return text.length > 200 ? `${text.slice(0, 200)}…` : text;\n}\n","/**\n * The receipts the store and the gas station answer with.\n *\n * These MIRROR the two app repositories — `toon-protocol/store`'s\n * `ArnsAntPrepareReceipt` / `ArnsBuyReceipt` and `toon-protocol/gas-station`'s\n * `GasStationReceipt` — and mirror them by hand, because this package has no\n * TOON-protocol runtime dependencies. That makes them a claim about a remote\n * contract rather than a shared type, so every integer that could exceed 2^53\n * is a `string` here exactly as it is on the wire: reading one as a `number`\n * would be this client inventing precision the app never sent.\n *\n * A field this client does not read is still declared, so that a receipt logged\n * or forwarded whole keeps its shape.\n */\n\n/** Which cluster's ar.io deployment a kind:5095 job targets. */\nexport type ArnsNetwork = 'mainnet' | 'devnet';\n\n/** A name registration kind: a time-boxed lease, or a one-time permabuy. */\nexport type ArnsNameType = 'lease' | 'permabuy';\n\n/** Which Solana cluster the gas station pays on. */\nexport type SolanaNetwork = 'mainnet' | 'devnet';\n\n/**\n * kind:5095 `op=prepare` — the unsigned ANT-spawn transaction.\n *\n * `requiredSigners` is the compiled slot order and is **address-sorted within a\n * role**, so it says who signs, never what each one is for. Map a keypair to a\n * slot by address. The fee payer is always slot 0 and is the one slot a client\n * leaves alone.\n */\nexport interface ArnsAntPrepareReceipt {\n job: 'arns-buy';\n op: 'prepare';\n network: ArnsNetwork;\n /** The ANT's MPL Core asset pubkey — the `processId` for `op=buy`. */\n processId: string;\n /** The same key, named for the keypair the client signs with. */\n mint: string;\n owner: string;\n feePayer: string;\n name: string;\n antProgramId: string;\n /** Base64 v0 wire transaction, every signature slot zero-filled. */\n transaction: string;\n recentBlockhash: string;\n /** True ⇒ built on a placeholder blockhash: quote with it, never execute it. */\n draft: boolean;\n requiredSigners: string[];\n /** The subset the client must fill before the gas station will look at it. */\n clientSigners: string[];\n rentTransferLamports: string;\n estimatedFeePayerLamports: string;\n instructions: string[];\n}\n\n/** kind:5095 `op=buy` — the name is registered to the ANT. */\nexport interface ArnsBuyReceipt {\n job: 'arns-buy';\n network: ArnsNetwork;\n name: string;\n type: ArnsNameType;\n years: number | null;\n processId: string;\n quotedMario: string;\n registryTxId: string;\n syncAttributesTxId: string | null;\n}\n\n/**\n * Why a gas station declined, from its own closed vocabulary. The ones a client\n * driving this ceremony can act on:\n *\n * - `float_exhausted` — the node is out of gas money; nothing to retry.\n * - `dvm_key_misplaced` — the gas wallet appears where it may not. Almost\n * always a transaction built wrong.\n * - `quote_expired`, `blockhash_expired`, `blockhash_mismatch` — re-quote,\n * re-patch, re-sign.\n * - `missing_client_signature` — a slot is still zero: sign AFTER patching.\n * - `confirmation_timeout` — broadcast but not confirmed. It may still land;\n * retry with the **same** `idempotencyKey`.\n */\nexport type GasStationFailureReason =\n | 'malformed_transaction'\n | 'fee_payer_mismatch'\n | 'dvm_key_misplaced'\n | 'program_not_whitelisted'\n | 'priority_fee_exceeded'\n | 'channel_op_not_permitted'\n | 'missing_client_signature'\n | 'unknown_quote'\n | 'quote_expired'\n | 'blockhash_mismatch'\n | 'blockhash_expired'\n | 'simulation_failed'\n | 'delta_cap_exceeded'\n | 'float_exhausted'\n | 'quote_refused'\n | 'confirmation_timeout'\n | 'broadcast_failed';\n\n/** kind:5096 `phase=quote` — what this node will do, and what it will cost. */\nexport interface GasStationQuoteReceipt {\n job: 'gas-station';\n phase: 'quote';\n status: 'ok';\n network: SolanaNetwork;\n quoteId: string;\n /** The address the transaction must name as its fee payer. */\n feePayer: string;\n maxLamports: string;\n /** The blockhash the executed transaction must carry. */\n recentBlockhash: string;\n /** ms epoch — quote TTL and blockhash validity, merged into one deadline. */\n expiresAt: number;\n}\n\n/** kind:5096 `phase=execute` — co-signed, broadcast, confirmed. */\nexport interface GasStationExecuteReceipt {\n job: 'gas-station';\n phase: 'execute';\n status: 'ok';\n network: SolanaNetwork;\n quoteId: string;\n idempotencyKey: string;\n signature: string;\n slot: string | null;\n feeLamportsActual: string | null;\n /** True when this result was replayed from the idempotency store. */\n replayed?: boolean;\n}\n\n/**\n * The gate said no — and said so as an accepted job, because it was asked a\n * question and applied its rules. Branch on {@link reason}, never on `detail`.\n */\nexport interface GasStationFailureReceipt {\n job: 'gas-station';\n phase: 'quote' | 'execute';\n status: 'failed';\n network: SolanaNetwork;\n reason: GasStationFailureReason;\n detail: string;\n}\n\nexport type GasStationReceipt =\n | GasStationQuoteReceipt\n | GasStationExecuteReceipt\n | GasStationFailureReceipt;\n\n/** True when a gas-station receipt is the gate declining. */\nexport function isGasStationFailure(\n receipt: GasStationReceipt\n): receipt is GasStationFailureReceipt {\n return receipt.status === 'failed';\n}\n","/**\n * Buying an ArNS name while holding nothing but ILP credit.\n *\n * `kind:5095 op=buy` needs a `processId` — the MPL Core asset pubkey of an ANT\n * the caller already owns. Spawning one costs ~0.012 SOL of rent, and a TOON\n * client holds stablecoin credit on a payment channel, not SOL. So the work is\n * split across the three parties, and no single one has to be able to do all of\n * it:\n *\n * - the **store** composes the transaction (it is the only party with `@ar.io/sdk`)\n * - the **client** signs it (it is the only party that may own the ANT)\n * - the **gas station** pays for it and broadcasts it (it is the only party with SOL)\n *\n * The ceremony {@link spawnAnt} drives:\n *\n * ```text\n * 1. → gas kind:5096 quote, no draft → feePayer\n * 2. → store kind:5095 op=prepare → unsigned draft transaction\n * 3. sign the mint and owner slots\n * 4. → gas kind:5096 quote, with draft → quoteId, recentBlockhash, maxLamports\n * 5. patch the blockhash, sign again\n * 6. → gas kind:5096 execute → co-signed, broadcast, signature\n * ```\n *\n * Two quotes and two signings, because the gas station prices the job from a\n * SIGNED draft (that is what makes the free quote a full policy dry run) and\n * then requires the executed transaction to carry the blockhash **it** chose.\n * Everything from step 4 on runs inside one merged quote/blockhash deadline —\n * 60 seconds by default — which is why step 5 patches the 32 bytes locally\n * instead of paying for a second `op=prepare` round trip. Pass `reprepare` to\n * take that round trip anyway; the store returns a byte-identical transaction\n * but for those 32 bytes, so both routes end in the same place.\n *\n * Then {@link buyArnsName} spends the ANT: `kind:5095 op=buy` with the spawned\n * `processId`. {@link buyArnsNameWithNewAnt} is the two in order.\n *\n * **The spawned ANT is not ACL-bootstrapped.** That is ~61.4M lamports against\n * the gas station's 20M per-job ceiling, and its instructions would put the fee\n * payer in an ar.io slot, which the inspector refuses outright. The ANT resolves\n * fine; it just will not appear in \"ANTs I own\" registry lookups until the owner\n * bootstraps it later with its own SOL — and that registry is an\n * eventually-consistent secondary index, not truth.\n *\n * **Nothing here throws.** A packet the connector would not carry, an event the\n * app rejected, a gate that declined to spend and a receipt this client will not\n * sign are all outcomes — `{ spawned: false, step, reason, detail }`. By the\n * time any of them is read a packet has already been paid for, which is exactly\n * the case CLAUDE.md's rule covers: a refusal is returned, never thrown.\n *\n * `reason` is the gas station's own closed vocabulary wherever the verdict is\n * one the gas station would give — including the two checks this client makes\n * locally, which exist only to reach that verdict before paying for it.\n */\n\nimport {\n generateSolanaKeypair,\n parseSolanaWireTransaction,\n patchSolanaRecentBlockhash,\n signSolanaWireTransaction,\n} from '../channel/solana/wire-transaction.js';\nimport type { Signer } from '../channel/solana/payment-channel.js';\nimport { base58Encode } from '../utils/base58.js';\nimport { buildJobEvent } from './job-event.js';\nimport { sendJob, type JobAnswer, type JobEndpoint } from './send-job.js';\nimport type {\n ArnsAntPrepareReceipt,\n ArnsBuyReceipt,\n ArnsNameType,\n GasStationExecuteReceipt,\n GasStationQuoteReceipt,\n GasStationReceipt,\n} from './receipts.js';\nimport type { SendRefused } from '../client/types.js';\n\n/** The NIP-90 job kind for the ArNS job — both of its ops. */\nexport const ARNS_KIND = 5095;\n/** The NIP-90 job kind for the Solana gas station — both of its phases. */\nexport const SOLANA_GAS_KIND = 5096;\n\n/** Which step of the ceremony an outcome stopped at. */\nexport type AntSpawnStep =\n | 'fee-payer-quote'\n | 'prepare'\n | 'quote'\n | 'reprepare'\n | 'sign'\n | 'execute';\n\nexport interface AntSpawnParams {\n /** Where the kind:5095 job goes — the store. */\n store: JobEndpoint;\n /** Where the kind:5096 job goes — the gas station. */\n gas: JobEndpoint;\n /**\n * The keypair that will own the ANT. Its address goes to the store as\n * `owner`, and it signs the owner slot — which is also the account the fee\n * payer transfers the ANT state PDAs' rent to, in the same transaction.\n */\n owner: Signer;\n /** The ANT's display name: 1–51 lowercase alphanumerics and hyphens. */\n name: string;\n /** Arweave tx id the root `@` record points at. Default: the store's own. */\n target?: string;\n /** ANT ticker, 1–16 chars. Default: the ar.io program's own. */\n ticker?: string;\n /**\n * Override the ephemeral mint keypair. Supply one only to make a run\n * reproducible — its public half becomes the ANT's permanent address, and\n * nothing needs its private half once the spawn confirms.\n */\n mint?: Signer;\n /**\n * The gas station's execute-phase idempotency key. Default: a fresh UUID —\n * and it must be one, because that idempotency store is global and unscoped,\n * so a guessable key is somebody else's receipt.\n *\n * Reuse the SAME key to retry a `confirmation_timeout`. Both outcomes report\n * the key that was used, so a generated one is recoverable rather than lost\n * with the run that made it.\n */\n idempotencyKey?: string;\n /**\n * Ask the store to re-prepare against the quoted blockhash instead of\n * patching those 32 bytes locally. One more paid round trip inside the quote\n * TTL, for a transaction composed entirely by the party that composes it.\n */\n reprepare?: boolean;\n}\n\n/** The ANT exists on chain, and the client owns it. */\nexport interface AntSpawned {\n spawned: true;\n /** The ANT's MPL Core asset pubkey — hand this to {@link buyArnsName}. */\n processId: string;\n /** The same key, named for the keypair that signed the mint slot. */\n mint: string;\n owner: string;\n feePayer: string;\n quoteId: string;\n /** The confirmed transaction signature. */\n signature: string;\n slot: string | null;\n feeLamportsActual: string | null;\n recentBlockhash: string;\n /** True when the gas station replayed a receipt for this idempotency key. */\n replayed: boolean;\n /** The key used, so a `confirmation_timeout` can be retried with it. */\n idempotencyKey: string;\n /** The executed transaction, base64 — every slot filled but the fee payer's. */\n transaction: string;\n}\n\n/** Somebody said no, and said why. */\nexport interface AntSpawnRefused {\n spawned: false;\n step: AntSpawnStep;\n /**\n * The gas station's machine-readable reason where it was the gate that\n * declined, an ILP reject code where the packet was refused, or the app's own\n * `F00` / `T00` where the event was rejected. Branch on this, not on\n * {@link detail}.\n *\n * A check this client made locally answers in the gas station's OWN\n * vocabulary — `fee_payer_mismatch`, `blockhash_mismatch`,\n * `missing_client_signature` — because it is the same verdict on the same\n * bytes, reached before paying for it rather than after.\n */\n reason: string;\n detail: string;\n /** Present when the packet never reached the app. */\n refusal?: SendRefused;\n /** The ANT's address. It exists only if the spawn confirmed. */\n mint: string;\n /**\n * The key the execute carried, or would have. Together with {@link quoteId}\n * and {@link transaction} it is everything needed to re-send that execute —\n * which is the documented recovery from a `confirmation_timeout`, where the\n * transaction is broadcast and may yet land.\n */\n idempotencyKey: string;\n /** The quote the execute was made against, once there was one. */\n quoteId?: string;\n /** The bytes sent to the gas station, when the execute is what failed. */\n transaction?: string;\n}\n\nexport type AntSpawnOutcome = AntSpawned | AntSpawnRefused;\n\n/**\n * Spawn an ANT the caller owns, paid for by a gas station and composed by a\n * store. Steps 1–6 above.\n */\nexport async function spawnAnt(params: AntSpawnParams): Promise<AntSpawnOutcome> {\n const owner = base58Encode(params.owner.publicKey);\n const mintKeypair = params.mint ?? generateSolanaKeypair();\n const mint = base58Encode(mintKeypair.publicKey);\n const idempotencyKey = params.idempotencyKey ?? crypto.randomUUID();\n const held = new Map<string, Signer>([\n [mint, mintKeypair],\n [owner, params.owner],\n ]);\n\n /** Every refusal carries the same three facts about the run that produced it. */\n const stop = (\n step: AntSpawnStep,\n refused: PartialRefusal\n ): AntSpawnRefused => ({ ...refused, step, mint, idempotencyKey });\n\n // ── 1. What address must the transaction name as its fee payer? ───────────\n // A quote with no draft is the cheapest way to ask: it prices nothing and\n // returns the gas wallet, which the store needs before it can compose.\n const feePayerQuote = await quote(params.gas, undefined);\n if (!feePayerQuote.ok) return stop('fee-payer-quote', feePayerQuote.refused);\n const feePayer = feePayerQuote.receipt.feePayer;\n\n // ── 2. Compose. No blockhash yet: a draft exists only to be priced. ───────\n const drafted = await prepare(params, { mint, owner, feePayer });\n if (!drafted.ok) return stop('prepare', drafted.refused);\n const draft = drafted.receipt;\n\n const drafters = signersFor(draft, held, { mint, feePayer });\n if (!drafters.ok) return stop('prepare', drafters.refused);\n\n // ── 3. Sign the slots the store said are ours. ────────────────────────────\n const signedDraft = signSolanaWireTransaction(draft.transaction, drafters.receipt);\n\n // ── 4. Quote the SIGNED draft: a full policy dry run, for free. ───────────\n const priced = await quote(params.gas, signedDraft);\n if (!priced.ok) return stop('quote', priced.refused);\n const { quoteId, recentBlockhash } = priced.receipt;\n\n // ── 5. Carry the quoted blockhash, then sign again — in that order. ───────\n // Signing first would be signing a message about to change underneath the\n // signature, so both routes end with the signing, never with the blockhash.\n let unsigned: string;\n let signers = drafters.receipt;\n if (params.reprepare === true) {\n const reprepared = await prepare(params, { mint, owner, feePayer }, recentBlockhash);\n if (!reprepared.ok) return stop('reprepare', { ...reprepared.refused, quoteId });\n const resigners = signersFor(reprepared.receipt, held, { mint, feePayer });\n if (!resigners.ok) return stop('reprepare', { ...resigners.refused, quoteId });\n unsigned = reprepared.receipt.transaction;\n signers = resigners.receipt;\n } else {\n unsigned = patchSolanaRecentBlockhash(draft.transaction, recentBlockhash);\n }\n const executable = signSolanaWireTransaction(unsigned, signers);\n\n const unexecutable = checkExecutable(executable, { feePayer, recentBlockhash });\n if (unexecutable) return stop('sign', { ...unexecutable, quoteId, transaction: executable });\n\n // ── 6. Pay, co-sign, broadcast. ───────────────────────────────────────────\n const executed = await sendJob<GasStationReceipt>(\n params.gas,\n buildJobEvent({\n kind: SOLANA_GAS_KIND,\n params: {\n phase: 'execute',\n transaction: executable,\n quoteId,\n idempotencyKey,\n },\n })\n );\n const settled = readGasStation<GasStationExecuteReceipt>(executed, 'execute');\n if (!settled.ok) {\n return stop('execute', { ...settled.refused, quoteId, transaction: executable });\n }\n\n return {\n spawned: true,\n processId: draft.processId,\n mint,\n owner,\n feePayer,\n quoteId,\n signature: settled.receipt.signature,\n slot: settled.receipt.slot,\n feeLamportsActual: settled.receipt.feeLamportsActual,\n recentBlockhash,\n replayed: settled.receipt.replayed === true,\n idempotencyKey,\n transaction: executable,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Buying the name\n// ---------------------------------------------------------------------------\n\nexport interface ArnsBuyParams {\n /** Where the kind:5095 job goes — the store. */\n store: JobEndpoint;\n /** The ArNS name to register. */\n name: string;\n /** The ANT that will hold it — {@link AntSpawned.processId}. */\n processId: string;\n /** Default `'lease'`. */\n type?: ArnsNameType;\n /** Lease length, 1–5. Invalid for a permabuy. */\n years?: number;\n /** The store's own replay key for the buy. Defaults to the event id. */\n idempotencyKey?: string;\n}\n\nexport type ArnsBuyOutcome =\n | { bought: true; receipt: ArnsBuyReceipt }\n | { bought: false; reason: string; detail: string; refusal?: SendRefused };\n\n/**\n * Register an ArNS name to an ANT the caller already owns — `kind:5095 op=buy`.\n * The store's own ARIO float pays the registry; this client pays the store.\n */\nexport async function buyArnsName(params: ArnsBuyParams): Promise<ArnsBuyOutcome> {\n const answer = await sendJob<ArnsBuyReceipt>(\n params.store,\n buildJobEvent({\n kind: ARNS_KIND,\n params: {\n op: 'buy',\n name: params.name,\n processId: params.processId,\n type: params.type ?? 'lease',\n years:\n (params.type ?? 'lease') === 'lease' && params.years !== undefined\n ? String(params.years)\n : undefined,\n idempotencyKey: params.idempotencyKey,\n },\n })\n );\n if (!answer.accepted) {\n return {\n bought: false,\n reason: answer.code,\n detail: answer.message,\n ...(answer.refusal ? { refusal: answer.refusal } : {}),\n };\n }\n return { bought: true, receipt: answer.receipt };\n}\n\n/** Both halves: spawn an ANT, then register the name to it. */\nexport type ArnsNameWithAntOutcome =\n | { bought: true; ant: AntSpawned; receipt: ArnsBuyReceipt }\n | { bought: false; ant?: AntSpawned; step: AntSpawnStep | 'buy'; reason: string; detail: string };\n\n/**\n * The whole thing: spawn an ANT and register `name` to it.\n *\n * The two halves are separately re-runnable on purpose. If the buy fails after\n * the spawn confirmed, the ANT is still yours — call {@link buyArnsName} with\n * the `processId` in `ant` rather than spawning a second one.\n */\nexport async function buyArnsNameWithNewAnt(\n params: AntSpawnParams & Pick<ArnsBuyParams, 'type' | 'years'>\n): Promise<ArnsNameWithAntOutcome> {\n const ant = await spawnAnt(params);\n if (!ant.spawned) {\n return { bought: false, step: ant.step, reason: ant.reason, detail: ant.detail };\n }\n const bought = await buyArnsName({\n store: params.store,\n name: params.name,\n processId: ant.processId,\n ...(params.type !== undefined ? { type: params.type } : {}),\n ...(params.years !== undefined ? { years: params.years } : {}),\n });\n if (!bought.bought) {\n return { bought: false, ant, step: 'buy', reason: bought.reason, detail: bought.detail };\n }\n return { bought: true, ant, receipt: bought.receipt };\n}\n\n// ---------------------------------------------------------------------------\n// Steps\n// ---------------------------------------------------------------------------\n\n/**\n * A refusal as a step knows it — before the facts about the run as a whole\n * (which step, which mint, which idempotency key) are stamped on by `stop`.\n */\ntype PartialRefusal = Omit<AntSpawnRefused, 'step' | 'mint' | 'idempotencyKey'>;\n\n/** A step's result: its receipt, or the refusal to hand back to the caller. */\ntype Step<T> =\n | { ok: true; receipt: T }\n | { ok: false; refused: PartialRefusal };\n\nasync function quote(\n gas: JobEndpoint,\n draft: string | undefined\n): Promise<Step<GasStationQuoteReceipt>> {\n const answer = await sendJob<GasStationReceipt>(\n gas,\n buildJobEvent({\n kind: SOLANA_GAS_KIND,\n params: { phase: 'quote', transaction: draft },\n })\n );\n return readGasStation<GasStationQuoteReceipt>(answer, 'quote');\n}\n\nasync function prepare(\n params: AntSpawnParams,\n keys: { mint: string; owner: string; feePayer: string },\n recentBlockhash?: string\n): Promise<Step<ArnsAntPrepareReceipt>> {\n const answer = await sendJob<ArnsAntPrepareReceipt>(\n params.store,\n buildJobEvent({\n kind: ARNS_KIND,\n params: {\n op: 'prepare',\n name: params.name,\n owner: keys.owner,\n mint: keys.mint,\n feePayer: keys.feePayer,\n recentBlockhash,\n target: params.target,\n ticker: params.ticker,\n },\n })\n );\n if (!answer.accepted) return { ok: false, refused: refusalOf(answer) };\n return { ok: true, receipt: answer.receipt };\n}\n\n/**\n * Read a gas-station answer. A receipt with `status: 'failed'` is the gate\n * declining — an accepted job, and the one case where {@link AntSpawnRefused}'s\n * `reason` carries the vocabulary a caller can branch on.\n */\nfunction readGasStation<T extends GasStationReceipt>(\n answer: JobAnswer<GasStationReceipt>,\n phase: 'quote' | 'execute'\n): Step<T> {\n if (!answer.accepted) return { ok: false, refused: refusalOf(answer) };\n const receipt = answer.receipt;\n if (receipt.status === 'failed') {\n return {\n ok: false,\n refused: {\n spawned: false,\n reason: receipt.reason,\n detail: receipt.detail,\n },\n };\n }\n if (receipt.phase !== phase) {\n return {\n ok: false,\n refused: {\n spawned: false,\n reason: 'malformed_receipt',\n detail: `asked the gas station for a ${phase} and it answered with a ${receipt.phase}`,\n },\n };\n }\n return { ok: true, receipt: receipt as T };\n}\n\n/**\n * The store named the signers; resolve them to the keys we hold, BY ADDRESS.\n *\n * `clientSigners` is the subset of the compiled slots that are ours to fill, and\n * `requiredSigners` is address-sorted within a role — so a positional read of\n * either is wrong for exactly the pairs of keys that happen to sort the other\n * way, which is the kind of bug that passes every test but one run in ten.\n * Signing what the receipt NAMES, rather than what this function assumes, is\n * also the only thing that stays right if a future store composes a transaction\n * where the owner is not among the client's slots.\n *\n * A receipt this client cannot honour is a REFUSAL, not an exception: two\n * packets have already been paid for by the time it is read, and a client that\n * threw here would be throwing after the packet went out.\n */\nfunction signersFor(\n receipt: ArnsAntPrepareReceipt,\n held: Map<string, Signer>,\n expected: { mint: string; feePayer: string }\n): Step<Signer[]> {\n const unheld = receipt.clientSigners.filter((signer) => !held.has(signer));\n if (unheld.length > 0) {\n return malformed(\n `the prepared transaction needs signatures this client does not hold: ${unheld.join(', ')} ` +\n `(holding ${[...held.keys()].join(' and ')})`\n );\n }\n if (receipt.feePayer !== expected.feePayer) {\n return malformed(\n `the prepared transaction names ${receipt.feePayer} as fee payer, not the quoted ${expected.feePayer}`\n );\n }\n // The mint's public half IS the ANT's address, so a `processId` that is not\n // it would send the follow-up name purchase at somebody else's asset.\n if (receipt.processId !== expected.mint) {\n return malformed(\n `the prepared transaction spawns ${receipt.processId}, not the mint ${expected.mint} it was given`\n );\n }\n const signers: Signer[] = [];\n for (const address of receipt.clientSigners) {\n const signer = held.get(address);\n if (signer !== undefined) signers.push(signer);\n }\n return { ok: true, receipt: signers };\n}\n\n/**\n * The local half of what the gas station is about to check: the fee payer is\n * slot 0, the blockhash is the quoted one, and every other slot is filled.\n *\n * Advisory only — the gas station's inspector is the authority and runs again\n * on the same bytes. This exists so that its verdict arrives for free instead of\n * for the price of an execute, which is why it answers in that inspector's own\n * vocabulary rather than inventing a second one.\n *\n * @returns The refusal, or `undefined` when the transaction is executable.\n */\nfunction checkExecutable(\n wireBase64: string,\n expected: { feePayer: string; recentBlockhash: string }\n): PartialRefusal | undefined {\n const parsed = parseSolanaWireTransaction(wireBase64);\n if (parsed.signers[0] !== expected.feePayer) {\n return {\n spawned: false,\n reason: 'fee_payer_mismatch',\n detail: `slot 0 is ${parsed.signers[0] ?? '(none)'}, not the quoted fee payer ${expected.feePayer}`,\n };\n }\n if (parsed.recentBlockhash !== expected.recentBlockhash) {\n return {\n spawned: false,\n reason: 'blockhash_mismatch',\n detail: `the transaction carries blockhash ${parsed.recentBlockhash}, not the quoted ${expected.recentBlockhash}`,\n };\n }\n const missing = parsed.unsigned.filter((signer) => signer !== expected.feePayer);\n if (missing.length > 0) {\n return {\n spawned: false,\n reason: 'missing_client_signature',\n detail: `these slots are still unsigned: ${missing.join(', ')}`,\n };\n }\n return undefined;\n}\n\n/** A job that produced no receipt, as the refusal to hand back to the caller. */\nfunction refusalOf(\n answer: Extract<JobAnswer<unknown>, { accepted: false }>\n): PartialRefusal {\n return {\n spawned: false,\n reason: answer.code,\n detail: answer.message,\n ...(answer.refusal ? { refusal: answer.refusal } : {}),\n };\n}\n\n/** The store composed something this client will not sign. */\nfunction malformed(detail: string): { ok: false; refused: PartialRefusal } {\n return { ok: false, refused: { spawned: false, reason: 'malformed_receipt', detail } };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAS,eAAe;AACxB,SAAS,cAAc;AACvB,SAAS,mBAAmB;AA+C5B,SAAS,eAAe,OAA6C;AACnE,SAAO,KAAK,UAAU;AAAA,IACpB;AAAA,IACA,MAAM;AAAA,IACN,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B,SAAS,iBAAiB;AACvD,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,QAAQ,qCAAqC,OAAO,eAAe,oBAAoB,SAAS,eAAe;AAAA,IACjH;AAAA,EACF;AACA,QAAM,UAAU,OAAO,SAAS,OAAO,CAAC,WAAW,WAAW,SAAS,QAAQ;AAC/E,MAAI,QAAQ,SAAS,GAAG;AACtB,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,QAAQ,mCAAmC,QAAQ,KAAK,IAAI,CAAC;AAAA,IAC/D;AAAA,EACF;AACA,SAAO;AACT;AAGA,SAAS,UACP,QACgB;AAChB,SAAO;AAAA,IACL,SAAS;AAAA,IACT,QAAQ,OAAO;AAAA,IACf,QAAQ,OAAO;AAAA,IACf,GAAI,OAAO,UAAU,EAAE,SAAS,OAAO,QAAQ,IAAI,CAAC;AAAA,EACtD;AACF;AAGA,SAAS,UAAU,QAAwD;AACzE,SAAO,EAAE,IAAI,OAAO,SAAS,EAAE,SAAS,OAAO,QAAQ,qBAAqB,OAAO,EAAE;AACvF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/jobs/job-event.ts","../src/jobs/send-job.ts","../src/jobs/receipts.ts","../src/jobs/ant-spawn.ts"],"sourcesContent":["/**\n * The signed job event a NIP-90 app behind a connector reads.\n *\n * Some apps a connector fronts are not plain HTTP handlers: the store and the\n * gas station both take their input as a **kind-tagged Nostr event** whose\n * arguments are `['param', key, value]` tags, and answer in the FULFILL body.\n * There is no relay and no round trip — the event is the request body of the\n * paid POST, and the receipt comes back in that same response.\n *\n * The signature on the event is **integrity, not identity**. Both apps say so\n * in as many words: it proves the tags were not altered between this client and\n * the handler, and nothing else — who paid is the connector's `X-TOON-Payer`\n * header, proved against a claim, and no app takes an event pubkey for an\n * authority. So the key here is generated per event by default. A caller who\n * wants a stable pubkey in the app's logs can supply one; nothing about the\n * job's outcome depends on which key it is.\n *\n * This is why the 1.0 client carries no Nostr identity. There is no key to\n * derive, back up or rotate — only 32 bytes to sign one request with and then\n * forget.\n */\n\nimport { schnorr } from '@noble/curves/secp256k1.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { encodeUtf8, toHex } from '../utils/binary.js';\n\n/**\n * A signed Nostr event, in the field order and JSON spelling every verifier\n * expects.\n */\nexport interface JobEvent {\n /** 32-byte sha256 of the serialization below, hex. */\n id: string;\n /** The signing key's x-only public half, hex. */\n pubkey: string;\n /** Unix SECONDS. */\n created_at: number;\n kind: number;\n tags: string[][];\n content: string;\n /** BIP-340 signature over `id`, hex. */\n sig: string;\n}\n\n/** What one job asks for: its kind, and its `param` tags. */\nexport interface JobEventParams {\n /** The NIP-90 job kind — `5095` for the ArNS job, `5096` for Solana gas. */\n kind: number;\n /**\n * The job's arguments, emitted in iteration order as `['param', key, value]`.\n * An `undefined` value is omitted rather than sent as the string\n * `\"undefined\"`, so an optional parameter can be passed through unset.\n */\n params: Record<string, string | undefined>;\n /** Extra tags to carry beside the params. Rarely needed. */\n tags?: string[][];\n /** Default `''`. Neither of this repository's job kinds reads it. */\n content?: string;\n /** 32-byte secp256k1 secret. Default: a fresh one, used once. */\n secretKey?: Uint8Array;\n /** Unix seconds. Default `Date.now() / 1000`, floored. */\n createdAt?: number;\n}\n\n/**\n * NIP-01 serialization: a six-element array, `JSON.stringify`d exactly as\n * written. The verifier recomputes this from the event's own fields, so any\n * difference in shape — a reordered key, a number where a string belongs —\n * surfaces as an id mismatch rather than as a validation message.\n */\nfunction serializeForId(event: Omit<JobEvent, 'id' | 'sig'>): string {\n return JSON.stringify([\n 0,\n event.pubkey,\n event.created_at,\n event.kind,\n event.tags,\n event.content,\n ]);\n}\n\n/**\n * Build and sign one job event.\n *\n * @returns The event, ready to be the `{ event }` body of a paid POST.\n */\nexport function buildJobEvent(params: JobEventParams): JobEvent {\n const secretKey = params.secretKey ?? randomBytes(32);\n const pubkey = toHex(new Uint8Array(schnorr.getPublicKey(secretKey)));\n\n const tags: string[][] = [];\n for (const [key, value] of Object.entries(params.params)) {\n if (value !== undefined) tags.push(['param', key, value]);\n }\n if (params.tags) tags.push(...params.tags);\n\n const unsigned = {\n pubkey,\n created_at: params.createdAt ?? Math.floor(Date.now() / 1000),\n kind: params.kind,\n tags,\n content: params.content ?? '',\n };\n\n const idBytes = sha256(encodeUtf8(serializeForId(unsigned)));\n return {\n ...unsigned,\n id: toHex(idBytes),\n sig: toHex(new Uint8Array(schnorr.sign(idBytes, secretKey))),\n };\n}\n\n/** First value of a `['param', key, value]` tag, if the event carries one. */\nexport function jobEventParam(event: JobEvent, key: string): string | undefined {\n for (const tag of event.tags) {\n if (tag[0] === 'param' && tag[1] === key) return tag[2];\n }\n return undefined;\n}\n","/**\n * Putting a {@link JobEvent} through a connector, and reading what came back.\n *\n * A job is an ordinary paid request — `POST` the event to the route, get the\n * app's HTTP response — so this adds no wire of its own. What it adds is the\n * one decoding rule both NIP-90 apps in this protocol share, and a single\n * vocabulary for the three quite different ways a job can fail to produce a\n * receipt:\n *\n * - **the packet was refused** — a price, a route or a seal was wrong, and the\n * app was never reached. `send()` returns this rather than throwing, and so\n * does {@link sendJob};\n * - **the app rejected the event** — a missing param, an unregistered kind.\n * It rides home on a FULFILL with `accept: false`, so it cost what a receipt\n * would have cost;\n * - **the app answered, and the answer is a refusal.** A gas station that\n * declines to spend has done its job: `accept: true`, a receipt, and\n * `status: 'failed'` inside it. That is NOT this module's business — it is a\n * successful job, and the caller branches on the receipt's own `reason`.\n *\n * The decoding rule: a receipt is `base64(JSON)` in `data`, and both apps ALSO\n * decode it into `result` for readability. `data` is the byte-faithful one and\n * is preferred here; `result` is the fallback, so a future app that emits only\n * one of the two still works.\n */\n\nimport { fromBase64, decodeUtf8 } from '../utils/binary.js';\nimport type { SendRefused, SendRequest, SendResult, SendOptions } from '../client/types.js';\nimport type { JobEvent } from './job-event.js';\n\n/**\n * The part of a client a job needs: the ability to pay for one HTTP request.\n * `ToonClient` satisfies it, and so does any stand-in a test supplies.\n */\nexport interface JobSender {\n send(\n destination: string,\n request?: SendRequest,\n options?: SendOptions\n ): Promise<SendResult>;\n}\n\n/**\n * Where a job goes: who pays for it, which route terminates it, and — on a\n * FORWARDED route — whose key the payload is sealed to.\n *\n * The store and the gas station MAY be different nodes with different\n * connectors and different channels, so a ceremony spanning both takes two\n * endpoints. Where one connector terminates both — as the devnet's does, at\n * `https://toonprotocol.dev` — both endpoints name the same client and no\n * `sealTo` is needed. Where a node only forwards to one of them, `sealTo` names\n * the far node.\n */\nexport interface JobEndpoint {\n /** Pays for the request. */\n client: JobSender;\n /** The ILP address of the route that terminates at the app. */\n destination: string;\n /** The terminating connector, when `destination` is forwarded. */\n sealTo?: string | Uint8Array;\n /** Per-packet timeout, in milliseconds. */\n timeoutMs?: number;\n}\n\n/**\n * What a job produced: a decoded receipt, or the reason there is none.\n *\n * `accepted: false` never means \"the app said no to what you asked\" — that is a\n * receipt. It means the receipt does not exist: the packet was refused, or the\n * app rejected the event before running it.\n */\nexport type JobAnswer<T> =\n | { accepted: true; receipt: T }\n | {\n accepted: false;\n /** An ILP reject code for a refusal, or the app's own `F00` / `T00`. */\n code: string;\n message: string;\n /** Present when the packet never reached the app. */\n refusal?: SendRefused;\n };\n\n/** The `{ accept, data, result, code, message }` envelope both apps answer in. */\ninterface JobEnvelope {\n accept?: boolean;\n data?: string;\n result?: unknown;\n /**\n * The store's answer when its `data` is NOT JSON — kind:5094 returns a bare\n * Arweave transaction id, and the backend surfaces it here rather than under\n * `result`. A documented contract, not a quirk.\n */\n txId?: unknown;\n code?: string;\n message?: string;\n}\n\n/**\n * Pay for one job and decode its receipt.\n *\n * The receipt type is the caller's assertion, not a checked fact: these apps\n * publish their receipt shapes and this client mirrors them, but nothing on the\n * wire enforces the match, so a caller reading a field it needs should still\n * check it is there.\n */\nexport async function sendJob<T>(\n endpoint: JobEndpoint,\n event: JobEvent\n): Promise<JobAnswer<T>> {\n const answer = await endpoint.client.send(\n endpoint.destination,\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: { event },\n },\n {\n ...(endpoint.sealTo !== undefined ? { sealTo: endpoint.sealTo } : {}),\n ...(endpoint.timeoutMs !== undefined ? { timeoutMs: endpoint.timeoutMs } : {}),\n }\n );\n\n if (!answer.fulfilled) {\n return {\n accepted: false,\n code: answer.code,\n message: `kind:${event.kind} refused by ${answer.refusedBy}: ${answer.message}`,\n refusal: answer,\n };\n }\n\n let envelope: JobEnvelope;\n try {\n envelope = answer.json<JobEnvelope>();\n } catch {\n return {\n accepted: false,\n code: 'F00',\n message:\n `kind:${event.kind} answered ${answer.status} with a body that is not JSON: ` +\n truncate(decodeUtf8(answer.body)),\n };\n }\n\n if (envelope.accept !== true) {\n return {\n accepted: false,\n code: envelope.code ?? String(answer.status),\n message: envelope.message ?? `kind:${event.kind} was not accepted`,\n };\n }\n\n const receipt = decodeReceipt<T>(envelope);\n if (receipt === undefined) {\n return {\n accepted: false,\n code: 'F00',\n message: `kind:${event.kind} was accepted but carried no receipt`,\n };\n }\n return { accepted: true, receipt };\n}\n\n/**\n * `data` (byte-faithful) if it decodes as JSON; otherwise whichever field the\n * app said its answer in.\n *\n * The store decides between two of those by whether its base64 `data` parses\n * as a JSON object: a receipt goes to `result`, and anything else goes to\n * `txId`. kind:5094 takes the second branch — its whole answer is one Arweave\n * transaction id — so a client that reads only `result` calls a successful\n * upload \"accepted but carried no receipt\".\n */\nfunction decodeReceipt<T>(envelope: JobEnvelope): T | undefined {\n if (typeof envelope.data === 'string') {\n try {\n return JSON.parse(decodeUtf8(fromBase64(envelope.data))) as T;\n } catch {\n // Fall through: an app that base64'd something that is not JSON has still\n // said what it meant in `result` or `txId`.\n }\n }\n if (envelope.result !== null && typeof envelope.result === 'object') {\n return envelope.result as T;\n }\n // A bare id is still a receipt. Wrapped, so the caller reads `receipt.txId`\n // the same way every other job's fields are read.\n if (typeof envelope.txId === 'string' && envelope.txId.length > 0) {\n return { txId: envelope.txId } as T;\n }\n return undefined;\n}\n\nfunction truncate(text: string): string {\n return text.length > 200 ? `${text.slice(0, 200)}…` : text;\n}\n","/**\n * The receipts the store and the gas station answer with.\n *\n * These MIRROR the two app repositories — `toon-protocol/store`'s\n * `ArnsAntPrepareReceipt` / `ArnsBuyReceipt` and `toon-protocol/gas-station`'s\n * `GasStationReceipt` — and mirror them by hand, because this package has no\n * TOON-protocol runtime dependencies. That makes them a claim about a remote\n * contract rather than a shared type, so every integer that could exceed 2^53\n * is a `string` here exactly as it is on the wire: reading one as a `number`\n * would be this client inventing precision the app never sent.\n *\n * A field this client does not read is still declared, so that a receipt logged\n * or forwarded whole keeps its shape.\n */\n\n/** Which cluster's ar.io deployment a kind:5095 job targets. */\nexport type ArnsNetwork = 'mainnet' | 'devnet';\n\n/** A name registration kind: a time-boxed lease, or a one-time permabuy. */\nexport type ArnsNameType = 'lease' | 'permabuy';\n\n/** Which Solana cluster the gas station pays on. */\nexport type SolanaNetwork = 'mainnet' | 'devnet';\n\n/**\n * kind:5095 `op=prepare` — the unsigned ANT-spawn transaction.\n *\n * `requiredSigners` is the compiled slot order and is **address-sorted within a\n * role**, so it says who signs, never what each one is for. Map a keypair to a\n * slot by address. The fee payer is always slot 0 and is the one slot a client\n * leaves alone.\n */\nexport interface ArnsAntPrepareReceipt {\n job: 'arns-buy';\n op: 'prepare';\n network: ArnsNetwork;\n /** The ANT's MPL Core asset pubkey — the `processId` for `op=buy`. */\n processId: string;\n /** The same key, named for the keypair the client signs with. */\n mint: string;\n owner: string;\n feePayer: string;\n name: string;\n antProgramId: string;\n /** Base64 v0 wire transaction, every signature slot zero-filled. */\n transaction: string;\n recentBlockhash: string;\n /** True ⇒ built on a placeholder blockhash: quote with it, never execute it. */\n draft: boolean;\n requiredSigners: string[];\n /** The subset the client must fill before the gas station will look at it. */\n clientSigners: string[];\n rentTransferLamports: string;\n estimatedFeePayerLamports: string;\n instructions: string[];\n}\n\n/** kind:5095 `op=buy` — the name is registered to the ANT. */\nexport interface ArnsBuyReceipt {\n job: 'arns-buy';\n network: ArnsNetwork;\n name: string;\n type: ArnsNameType;\n years: number | null;\n processId: string;\n quotedMario: string;\n registryTxId: string;\n syncAttributesTxId: string | null;\n}\n\n/**\n * Why a gas station declined, from its own closed vocabulary. The ones a client\n * driving this ceremony can act on:\n *\n * - `float_exhausted` — the node is out of gas money; nothing to retry.\n * - `dvm_key_misplaced` — the gas wallet appears where it may not. Almost\n * always a transaction built wrong.\n * - `quote_expired`, `blockhash_expired`, `blockhash_mismatch` — re-quote,\n * re-patch, re-sign.\n * - `missing_client_signature` — a slot is still zero: sign AFTER patching.\n * - `confirmation_timeout` — broadcast but not confirmed. It may still land;\n * retry with the **same** `idempotencyKey`.\n */\nexport type GasStationFailureReason =\n | 'malformed_transaction'\n | 'fee_payer_mismatch'\n | 'dvm_key_misplaced'\n | 'program_not_whitelisted'\n | 'priority_fee_exceeded'\n | 'channel_op_not_permitted'\n | 'missing_client_signature'\n | 'unknown_quote'\n | 'quote_expired'\n | 'blockhash_mismatch'\n | 'blockhash_expired'\n | 'simulation_failed'\n | 'delta_cap_exceeded'\n | 'float_exhausted'\n | 'quote_refused'\n | 'confirmation_timeout'\n | 'broadcast_failed';\n\n/** kind:5096 `phase=quote` — what this node will do, and what it will cost. */\nexport interface GasStationQuoteReceipt {\n job: 'gas-station';\n phase: 'quote';\n status: 'ok';\n network: SolanaNetwork;\n quoteId: string;\n /** The address the transaction must name as its fee payer. */\n feePayer: string;\n maxLamports: string;\n /** The blockhash the executed transaction must carry. */\n recentBlockhash: string;\n /** ms epoch — quote TTL and blockhash validity, merged into one deadline. */\n expiresAt: number;\n}\n\n/** kind:5096 `phase=execute` — co-signed, broadcast, confirmed. */\nexport interface GasStationExecuteReceipt {\n job: 'gas-station';\n phase: 'execute';\n status: 'ok';\n network: SolanaNetwork;\n quoteId: string;\n idempotencyKey: string;\n signature: string;\n slot: string | null;\n feeLamportsActual: string | null;\n /** True when this result was replayed from the idempotency store. */\n replayed?: boolean;\n}\n\n/**\n * The gate said no — and said so as an accepted job, because it was asked a\n * question and applied its rules. Branch on {@link reason}, never on `detail`.\n */\nexport interface GasStationFailureReceipt {\n job: 'gas-station';\n phase: 'quote' | 'execute';\n status: 'failed';\n network: SolanaNetwork;\n reason: GasStationFailureReason;\n detail: string;\n}\n\nexport type GasStationReceipt =\n | GasStationQuoteReceipt\n | GasStationExecuteReceipt\n | GasStationFailureReceipt;\n\n/** True when a gas-station receipt is the gate declining. */\nexport function isGasStationFailure(\n receipt: GasStationReceipt\n): receipt is GasStationFailureReceipt {\n return receipt.status === 'failed';\n}\n","/**\n * Buying an ArNS name while holding nothing but ILP credit.\n *\n * `kind:5095 op=buy` needs a `processId` — the MPL Core asset pubkey of an ANT\n * the caller already owns. Spawning one costs ~0.012 SOL of rent, and a TOON\n * client holds stablecoin credit on a payment channel, not SOL. So the work is\n * split across the three parties, and no single one has to be able to do all of\n * it:\n *\n * - the **store** composes the transaction (it is the only party with `@ar.io/sdk`)\n * - the **client** signs it (it is the only party that may own the ANT)\n * - the **gas station** pays for it and broadcasts it (it is the only party with SOL)\n *\n * The ceremony {@link spawnAnt} drives:\n *\n * ```text\n * 1. → gas kind:5096 quote, no draft → feePayer\n * 2. → store kind:5095 op=prepare → unsigned draft transaction\n * 3. sign the mint and owner slots\n * 4. → gas kind:5096 quote, with draft → quoteId, recentBlockhash, maxLamports\n * 5. patch the blockhash, sign again\n * 6. → gas kind:5096 execute → co-signed, broadcast, signature\n * ```\n *\n * Two quotes and two signings, because the gas station prices the job from a\n * SIGNED draft (that is what makes the free quote a full policy dry run) and\n * then requires the executed transaction to carry the blockhash **it** chose.\n * Everything from step 4 on runs inside one merged quote/blockhash deadline —\n * 60 seconds by default — which is why step 5 patches the 32 bytes locally\n * instead of paying for a second `op=prepare` round trip. Pass `reprepare` to\n * take that round trip anyway; the store returns a byte-identical transaction\n * but for those 32 bytes, so both routes end in the same place.\n *\n * Then {@link buyArnsName} spends the ANT: `kind:5095 op=buy` with the spawned\n * `processId`. {@link buyArnsNameWithNewAnt} is the two in order.\n *\n * **The spawned ANT is not ACL-bootstrapped.** That is ~61.4M lamports against\n * the gas station's 20M per-job ceiling, and its instructions would put the fee\n * payer in an ar.io slot, which the inspector refuses outright. The ANT resolves\n * fine; it just will not appear in \"ANTs I own\" registry lookups until the owner\n * bootstraps it later with its own SOL — and that registry is an\n * eventually-consistent secondary index, not truth.\n *\n * **Nothing here throws.** A packet the connector would not carry, an event the\n * app rejected, a gate that declined to spend and a receipt this client will not\n * sign are all outcomes — `{ spawned: false, step, reason, detail }`. By the\n * time any of them is read a packet has already been paid for, which is exactly\n * the case CLAUDE.md's rule covers: a refusal is returned, never thrown.\n *\n * `reason` is the gas station's own closed vocabulary wherever the verdict is\n * one the gas station would give — including the two checks this client makes\n * locally, which exist only to reach that verdict before paying for it.\n */\n\nimport {\n generateSolanaKeypair,\n parseSolanaWireTransaction,\n patchSolanaRecentBlockhash,\n signSolanaWireTransaction,\n} from '../channel/solana/wire-transaction.js';\nimport type { Signer } from '../channel/solana/payment-channel.js';\nimport { base58Encode } from '../utils/base58.js';\nimport { buildJobEvent } from './job-event.js';\nimport { sendJob, type JobAnswer, type JobEndpoint } from './send-job.js';\nimport type {\n ArnsAntPrepareReceipt,\n ArnsBuyReceipt,\n ArnsNameType,\n GasStationExecuteReceipt,\n GasStationQuoteReceipt,\n GasStationReceipt,\n} from './receipts.js';\nimport type { SendRefused } from '../client/types.js';\n\n/** The NIP-90 job kind for the ArNS job — both of its ops. */\nexport const ARNS_KIND = 5095;\n/** The NIP-90 job kind for the Solana gas station — both of its phases. */\nexport const SOLANA_GAS_KIND = 5096;\n\n/** Which step of the ceremony an outcome stopped at. */\nexport type AntSpawnStep =\n | 'fee-payer-quote'\n | 'prepare'\n | 'quote'\n | 'reprepare'\n | 'sign'\n | 'execute';\n\nexport interface AntSpawnParams {\n /** Where the kind:5095 job goes — the store. */\n store: JobEndpoint;\n /** Where the kind:5096 job goes — the gas station. */\n gas: JobEndpoint;\n /**\n * The keypair that will own the ANT. Its address goes to the store as\n * `owner`, and it signs the owner slot — which is also the account the fee\n * payer transfers the ANT state PDAs' rent to, in the same transaction.\n */\n owner: Signer;\n /** The ANT's display name: 1–51 lowercase alphanumerics and hyphens. */\n name: string;\n /** Arweave tx id the root `@` record points at. Default: the store's own. */\n target?: string;\n /** ANT ticker, 1–16 chars. Default: the ar.io program's own. */\n ticker?: string;\n /**\n * Override the ephemeral mint keypair. Supply one only to make a run\n * reproducible — its public half becomes the ANT's permanent address, and\n * nothing needs its private half once the spawn confirms.\n */\n mint?: Signer;\n /**\n * The gas station's execute-phase idempotency key. Default: a fresh UUID —\n * and it must be one, because that idempotency store is global and unscoped,\n * so a guessable key is somebody else's receipt.\n *\n * Reuse the SAME key to retry a `confirmation_timeout`. Both outcomes report\n * the key that was used, so a generated one is recoverable rather than lost\n * with the run that made it.\n */\n idempotencyKey?: string;\n /**\n * Ask the store to re-prepare against the quoted blockhash instead of\n * patching those 32 bytes locally. One more paid round trip inside the quote\n * TTL, for a transaction composed entirely by the party that composes it.\n */\n reprepare?: boolean;\n}\n\n/** The ANT exists on chain, and the client owns it. */\nexport interface AntSpawned {\n spawned: true;\n /** The ANT's MPL Core asset pubkey — hand this to {@link buyArnsName}. */\n processId: string;\n /** The same key, named for the keypair that signed the mint slot. */\n mint: string;\n owner: string;\n feePayer: string;\n quoteId: string;\n /** The confirmed transaction signature. */\n signature: string;\n slot: string | null;\n feeLamportsActual: string | null;\n recentBlockhash: string;\n /** True when the gas station replayed a receipt for this idempotency key. */\n replayed: boolean;\n /** The key used, so a `confirmation_timeout` can be retried with it. */\n idempotencyKey: string;\n /** The executed transaction, base64 — every slot filled but the fee payer's. */\n transaction: string;\n}\n\n/** Somebody said no, and said why. */\nexport interface AntSpawnRefused {\n spawned: false;\n step: AntSpawnStep;\n /**\n * The gas station's machine-readable reason where it was the gate that\n * declined, an ILP reject code where the packet was refused, or the app's own\n * `F00` / `T00` where the event was rejected. Branch on this, not on\n * {@link detail}.\n *\n * A check this client made locally answers in the gas station's OWN\n * vocabulary — `fee_payer_mismatch`, `blockhash_mismatch`,\n * `missing_client_signature` — because it is the same verdict on the same\n * bytes, reached before paying for it rather than after.\n */\n reason: string;\n detail: string;\n /** Present when the packet never reached the app. */\n refusal?: SendRefused;\n /** The ANT's address. It exists only if the spawn confirmed. */\n mint: string;\n /**\n * The key the execute carried, or would have. Together with {@link quoteId}\n * and {@link transaction} it is everything needed to re-send that execute —\n * which is the documented recovery from a `confirmation_timeout`, where the\n * transaction is broadcast and may yet land.\n */\n idempotencyKey: string;\n /** The quote the execute was made against, once there was one. */\n quoteId?: string;\n /** The bytes sent to the gas station, when the execute is what failed. */\n transaction?: string;\n}\n\nexport type AntSpawnOutcome = AntSpawned | AntSpawnRefused;\n\n/**\n * Spawn an ANT the caller owns, paid for by a gas station and composed by a\n * store. Steps 1–6 above.\n */\nexport async function spawnAnt(params: AntSpawnParams): Promise<AntSpawnOutcome> {\n const owner = base58Encode(params.owner.publicKey);\n const mintKeypair = params.mint ?? generateSolanaKeypair();\n const mint = base58Encode(mintKeypair.publicKey);\n const idempotencyKey = params.idempotencyKey ?? crypto.randomUUID();\n const held = new Map<string, Signer>([\n [mint, mintKeypair],\n [owner, params.owner],\n ]);\n\n /** Every refusal carries the same three facts about the run that produced it. */\n const stop = (\n step: AntSpawnStep,\n refused: PartialRefusal\n ): AntSpawnRefused => ({ ...refused, step, mint, idempotencyKey });\n\n // ── 1. What address must the transaction name as its fee payer? ───────────\n // A quote with no draft is the cheapest way to ask: it prices nothing and\n // returns the gas wallet, which the store needs before it can compose.\n const feePayerQuote = await quote(params.gas, undefined);\n if (!feePayerQuote.ok) return stop('fee-payer-quote', feePayerQuote.refused);\n const feePayer = feePayerQuote.receipt.feePayer;\n\n // ── 2. Compose. No blockhash yet: a draft exists only to be priced. ───────\n const drafted = await prepare(params, { mint, owner, feePayer });\n if (!drafted.ok) return stop('prepare', drafted.refused);\n const draft = drafted.receipt;\n\n const drafters = signersFor(draft, held, { mint, feePayer });\n if (!drafters.ok) return stop('prepare', drafters.refused);\n\n // ── 3. Sign the slots the store said are ours. ────────────────────────────\n const signedDraft = signSolanaWireTransaction(draft.transaction, drafters.receipt);\n\n // ── 4. Quote the SIGNED draft: a full policy dry run, for free. ───────────\n const priced = await quote(params.gas, signedDraft);\n if (!priced.ok) return stop('quote', priced.refused);\n const { quoteId, recentBlockhash } = priced.receipt;\n\n // ── 5. Carry the quoted blockhash, then sign again — in that order. ───────\n // Signing first would be signing a message about to change underneath the\n // signature, so both routes end with the signing, never with the blockhash.\n let unsigned: string;\n let signers = drafters.receipt;\n if (params.reprepare === true) {\n const reprepared = await prepare(params, { mint, owner, feePayer }, recentBlockhash);\n if (!reprepared.ok) return stop('reprepare', { ...reprepared.refused, quoteId });\n const resigners = signersFor(reprepared.receipt, held, { mint, feePayer });\n if (!resigners.ok) return stop('reprepare', { ...resigners.refused, quoteId });\n unsigned = reprepared.receipt.transaction;\n signers = resigners.receipt;\n } else {\n unsigned = patchSolanaRecentBlockhash(draft.transaction, recentBlockhash);\n }\n const executable = signSolanaWireTransaction(unsigned, signers);\n\n const unexecutable = checkExecutable(executable, { feePayer, recentBlockhash });\n if (unexecutable) return stop('sign', { ...unexecutable, quoteId, transaction: executable });\n\n // ── 6. Pay, co-sign, broadcast. ───────────────────────────────────────────\n const executed = await sendJob<GasStationReceipt>(\n params.gas,\n buildJobEvent({\n kind: SOLANA_GAS_KIND,\n params: {\n phase: 'execute',\n transaction: executable,\n quoteId,\n idempotencyKey,\n },\n })\n );\n const settled = readGasStation<GasStationExecuteReceipt>(executed, 'execute');\n if (!settled.ok) {\n return stop('execute', { ...settled.refused, quoteId, transaction: executable });\n }\n\n return {\n spawned: true,\n processId: draft.processId,\n mint,\n owner,\n feePayer,\n quoteId,\n signature: settled.receipt.signature,\n slot: settled.receipt.slot,\n feeLamportsActual: settled.receipt.feeLamportsActual,\n recentBlockhash,\n replayed: settled.receipt.replayed === true,\n idempotencyKey,\n transaction: executable,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Buying the name\n// ---------------------------------------------------------------------------\n\nexport interface ArnsBuyParams {\n /** Where the kind:5095 job goes — the store. */\n store: JobEndpoint;\n /** The ArNS name to register. */\n name: string;\n /** The ANT that will hold it — {@link AntSpawned.processId}. */\n processId: string;\n /** Default `'lease'`. */\n type?: ArnsNameType;\n /** Lease length, 1–5. Invalid for a permabuy. */\n years?: number;\n /** The store's own replay key for the buy. Defaults to the event id. */\n idempotencyKey?: string;\n}\n\nexport type ArnsBuyOutcome =\n | { bought: true; receipt: ArnsBuyReceipt }\n | { bought: false; reason: string; detail: string; refusal?: SendRefused };\n\n/**\n * Register an ArNS name to an ANT the caller already owns — `kind:5095 op=buy`.\n * The store's own ARIO float pays the registry; this client pays the store.\n */\nexport async function buyArnsName(params: ArnsBuyParams): Promise<ArnsBuyOutcome> {\n const answer = await sendJob<ArnsBuyReceipt>(\n params.store,\n buildJobEvent({\n kind: ARNS_KIND,\n params: {\n op: 'buy',\n name: params.name,\n processId: params.processId,\n type: params.type ?? 'lease',\n years:\n (params.type ?? 'lease') === 'lease' && params.years !== undefined\n ? String(params.years)\n : undefined,\n idempotencyKey: params.idempotencyKey,\n },\n })\n );\n if (!answer.accepted) {\n return {\n bought: false,\n reason: answer.code,\n detail: answer.message,\n ...(answer.refusal ? { refusal: answer.refusal } : {}),\n };\n }\n return { bought: true, receipt: answer.receipt };\n}\n\n/** Both halves: spawn an ANT, then register the name to it. */\nexport type ArnsNameWithAntOutcome =\n | { bought: true; ant: AntSpawned; receipt: ArnsBuyReceipt }\n | { bought: false; ant?: AntSpawned; step: AntSpawnStep | 'buy'; reason: string; detail: string };\n\n/**\n * The whole thing: spawn an ANT and register `name` to it.\n *\n * The two halves are separately re-runnable on purpose. If the buy fails after\n * the spawn confirmed, the ANT is still yours — call {@link buyArnsName} with\n * the `processId` in `ant` rather than spawning a second one.\n */\nexport async function buyArnsNameWithNewAnt(\n params: AntSpawnParams & Pick<ArnsBuyParams, 'type' | 'years'>\n): Promise<ArnsNameWithAntOutcome> {\n const ant = await spawnAnt(params);\n if (!ant.spawned) {\n return { bought: false, step: ant.step, reason: ant.reason, detail: ant.detail };\n }\n const bought = await buyArnsName({\n store: params.store,\n name: params.name,\n processId: ant.processId,\n ...(params.type !== undefined ? { type: params.type } : {}),\n ...(params.years !== undefined ? { years: params.years } : {}),\n });\n if (!bought.bought) {\n return { bought: false, ant, step: 'buy', reason: bought.reason, detail: bought.detail };\n }\n return { bought: true, ant, receipt: bought.receipt };\n}\n\n// ---------------------------------------------------------------------------\n// Steps\n// ---------------------------------------------------------------------------\n\n/**\n * A refusal as a step knows it — before the facts about the run as a whole\n * (which step, which mint, which idempotency key) are stamped on by `stop`.\n */\ntype PartialRefusal = Omit<AntSpawnRefused, 'step' | 'mint' | 'idempotencyKey'>;\n\n/** A step's result: its receipt, or the refusal to hand back to the caller. */\ntype Step<T> =\n | { ok: true; receipt: T }\n | { ok: false; refused: PartialRefusal };\n\nasync function quote(\n gas: JobEndpoint,\n draft: string | undefined\n): Promise<Step<GasStationQuoteReceipt>> {\n const answer = await sendJob<GasStationReceipt>(\n gas,\n buildJobEvent({\n kind: SOLANA_GAS_KIND,\n params: { phase: 'quote', transaction: draft },\n })\n );\n return readGasStation<GasStationQuoteReceipt>(answer, 'quote');\n}\n\nasync function prepare(\n params: AntSpawnParams,\n keys: { mint: string; owner: string; feePayer: string },\n recentBlockhash?: string\n): Promise<Step<ArnsAntPrepareReceipt>> {\n const answer = await sendJob<ArnsAntPrepareReceipt>(\n params.store,\n buildJobEvent({\n kind: ARNS_KIND,\n params: {\n op: 'prepare',\n name: params.name,\n owner: keys.owner,\n mint: keys.mint,\n feePayer: keys.feePayer,\n recentBlockhash,\n target: params.target,\n ticker: params.ticker,\n },\n })\n );\n if (!answer.accepted) return { ok: false, refused: refusalOf(answer) };\n return { ok: true, receipt: answer.receipt };\n}\n\n/**\n * Read a gas-station answer. A receipt with `status: 'failed'` is the gate\n * declining — an accepted job, and the one case where {@link AntSpawnRefused}'s\n * `reason` carries the vocabulary a caller can branch on.\n */\nfunction readGasStation<T extends GasStationReceipt>(\n answer: JobAnswer<GasStationReceipt>,\n phase: 'quote' | 'execute'\n): Step<T> {\n if (!answer.accepted) return { ok: false, refused: refusalOf(answer) };\n const receipt = answer.receipt;\n if (receipt.status === 'failed') {\n return {\n ok: false,\n refused: {\n spawned: false,\n reason: receipt.reason,\n detail: receipt.detail,\n },\n };\n }\n if (receipt.phase !== phase) {\n return {\n ok: false,\n refused: {\n spawned: false,\n reason: 'malformed_receipt',\n detail: `asked the gas station for a ${phase} and it answered with a ${receipt.phase}`,\n },\n };\n }\n return { ok: true, receipt: receipt as T };\n}\n\n/**\n * The store named the signers; resolve them to the keys we hold, BY ADDRESS.\n *\n * `clientSigners` is the subset of the compiled slots that are ours to fill, and\n * `requiredSigners` is address-sorted within a role — so a positional read of\n * either is wrong for exactly the pairs of keys that happen to sort the other\n * way, which is the kind of bug that passes every test but one run in ten.\n * Signing what the receipt NAMES, rather than what this function assumes, is\n * also the only thing that stays right if a future store composes a transaction\n * where the owner is not among the client's slots.\n *\n * A receipt this client cannot honour is a REFUSAL, not an exception: two\n * packets have already been paid for by the time it is read, and a client that\n * threw here would be throwing after the packet went out.\n */\nfunction signersFor(\n receipt: ArnsAntPrepareReceipt,\n held: Map<string, Signer>,\n expected: { mint: string; feePayer: string }\n): Step<Signer[]> {\n const unheld = receipt.clientSigners.filter((signer) => !held.has(signer));\n if (unheld.length > 0) {\n return malformed(\n `the prepared transaction needs signatures this client does not hold: ${unheld.join(', ')} ` +\n `(holding ${[...held.keys()].join(' and ')})`\n );\n }\n if (receipt.feePayer !== expected.feePayer) {\n return malformed(\n `the prepared transaction names ${receipt.feePayer} as fee payer, not the quoted ${expected.feePayer}`\n );\n }\n // The mint's public half IS the ANT's address, so a `processId` that is not\n // it would send the follow-up name purchase at somebody else's asset.\n if (receipt.processId !== expected.mint) {\n return malformed(\n `the prepared transaction spawns ${receipt.processId}, not the mint ${expected.mint} it was given`\n );\n }\n const signers: Signer[] = [];\n for (const address of receipt.clientSigners) {\n const signer = held.get(address);\n if (signer !== undefined) signers.push(signer);\n }\n return { ok: true, receipt: signers };\n}\n\n/**\n * The local half of what the gas station is about to check: the fee payer is\n * slot 0, the blockhash is the quoted one, and every other slot is filled.\n *\n * Advisory only — the gas station's inspector is the authority and runs again\n * on the same bytes. This exists so that its verdict arrives for free instead of\n * for the price of an execute, which is why it answers in that inspector's own\n * vocabulary rather than inventing a second one.\n *\n * @returns The refusal, or `undefined` when the transaction is executable.\n */\nfunction checkExecutable(\n wireBase64: string,\n expected: { feePayer: string; recentBlockhash: string }\n): PartialRefusal | undefined {\n const parsed = parseSolanaWireTransaction(wireBase64);\n if (parsed.signers[0] !== expected.feePayer) {\n return {\n spawned: false,\n reason: 'fee_payer_mismatch',\n detail: `slot 0 is ${parsed.signers[0] ?? '(none)'}, not the quoted fee payer ${expected.feePayer}`,\n };\n }\n if (parsed.recentBlockhash !== expected.recentBlockhash) {\n return {\n spawned: false,\n reason: 'blockhash_mismatch',\n detail: `the transaction carries blockhash ${parsed.recentBlockhash}, not the quoted ${expected.recentBlockhash}`,\n };\n }\n const missing = parsed.unsigned.filter((signer) => signer !== expected.feePayer);\n if (missing.length > 0) {\n return {\n spawned: false,\n reason: 'missing_client_signature',\n detail: `these slots are still unsigned: ${missing.join(', ')}`,\n };\n }\n return undefined;\n}\n\n/** A job that produced no receipt, as the refusal to hand back to the caller. */\nfunction refusalOf(\n answer: Extract<JobAnswer<unknown>, { accepted: false }>\n): PartialRefusal {\n return {\n spawned: false,\n reason: answer.code,\n detail: answer.message,\n ...(answer.refusal ? { refusal: answer.refusal } : {}),\n };\n}\n\n/** The store composed something this client will not sign. */\nfunction malformed(detail: string): { ok: false; refused: PartialRefusal } {\n return { ok: false, refused: { spawned: false, reason: 'malformed_receipt', detail } };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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