Skip to content

API ReferenceLOC lifecycleInterface

LOCModule

Letter of Credit operations: create, manage, and read LOCs, look up the collateral and credited tokens they can use, and check each operation’s inputs before the wallet is involved.

Reach it as sdk.loc on an AnvilSDK instance, which creates the module for you.

Create

buildCreateDynamicWorkflow()

buildCreateDynamicWorkflow(params): Promise<WalletOperationWorkflow>;

Builds the workflow that creates a dynamic LOC — one collateralized in a different token from the one it credits, so its collateral is priced against the credited token and can be liquidated if it falls too far.

Creation is priced, and the price update is yours to supply: pass priceUpdate from PricingModule.getOraclePriceUpdate, whose fee the builder attaches as the transaction’s value. Fetch it immediately before building — it goes stale within PricingModule.getMaxPriceUpdateSecondsAgo seconds, and the contract reverts once it has.

Building does not validate. Call LOCModule.validateCreateDynamic for early form feedback; execute() always repeats full validation against fresh state before its first prompt.

Parameters

ParameterTypeDescription
paramsCreateDynamicLOCParamsThe beneficiary, credited amount, collateral token and amount, and expiration.
params.beneficiaryAddressThe Beneficiary: the account entitled to redeem the credited value before expiration, and the only party (besides a caller holding its signed authorization) that can cancel the LOC before it expires. If LOCConfig.locBeneficiaryAllowList is configured, it must be one of its entries.
params.collateralTokenAmountTokenAmountCollateral the Creator reserves in the Collateral Vault to back the LOC, in the collateral token’s smallest unit. Must be a different token than the credited token, and its oracle value must satisfy the pair’s creation collateral factor; the workflow deposits and approves any shortfall.
params.creator?AddressThe LOC’s Creator. Defaults to the connected signer’s address. If set, it must equal the connected signer’s address, because the contract records the transaction sender as the Creator; a different value is rejected.
params.creditedTokenAmountTokenAmountThe LOC’s face value: the token and amount the Beneficiary is entitled to redeem, in the credited token’s smallest unit. The credited token must be enabled for Dynamic LOCs (LOCModule.getCreditedToken) and the amount must fall within its per-LOC minimum/maximum and the global cap on dynamic use.
params.expirationTimestampSecondsbigintUnix-seconds instant at which the LOC expires — expired at, not after, this second. Must be in the future and no further out than the deployment’s maximum duration; LOCModule.getMinDate and LOCModule.getMaxDate give the SDK’s padded bounds.
params.locAllowanceSignature?BytesVault allowance signature letting the LetterOfCredit contract reserve this LOC’s collateral, from VaultModule.buildModifyAllowanceAuthorizationWorkflow. When it is omitted and the allowance is short, the workflow asks the wallet to sign one.
params.priceUpdate?OraclePriceUpdateSourceOracle price update the contract uses to check the collateral. Supply an update from PricingModule.getOraclePriceUpdate to pass it through unchanged (its fee becomes the transaction value), pass 'auto' to fetch one when the final transaction is built, or pass null or omit the field to rely on the current onchain price, with no fetch and no fee. With 'auto', if the fetch fails the SDK uses the onchain price only when it can prove that price is still fresh.
params.tag?BytesOptional reference data (for example an invoice number or document hash) recorded in the creation event and returned as origin.tag on LetterOfCredit; it is not stored in contract state. 0x-prefixed hex of at most 512 bytes (LOCModule.getCreateTagByteLimit).

Returns

Promise<WalletOperationWorkflow>

The workflow to present and execute.

Example

// WETH is any registered collateral token address, e.g. one listed
// by `sdk.loc.getCollateralTokens()`.
const USDC = testnetProfile.contracts.USDC.address;
// A fresh Pyth price so creation does not depend on the on-chain price
// being recent; its fee is attached to the transaction automatically.
const priceUpdate = await sdk.pricing.getOraclePriceUpdate({
inputToken: WETH,
outputToken: USDC,
});
const params: CreateDynamicLOCParams = {
beneficiary: '0x1111111111111111111111111111111111111111',
// 1,000 USDC face value backed by 0.5 WETH of collateral.
creditedTokenAmount: { tokenAddress: USDC, amount: 1_000_000_000n },
collateralTokenAmount: { tokenAddress: WETH, amount: 5n * 10n ** 17n },
expirationTimestampSeconds: dateToEthereumTimestamp(
await sdk.loc.getMaxDate()
),
priceUpdate,
};
const issues = await sdk.loc.validateCreateDynamic(params);
if (issues.length > 0) throw new Error(JSON.stringify(issues));
const workflow = await sdk.loc.buildCreateDynamicWorkflow(params);
await workflow.execute();

Throws

WorkflowSignerChangedError If the SDK’s configured accountAddress and the connected wallet’s account disagree, or if the signer observed while executing differs from the one observed while building. Rebuild the workflow for the currently connected signer; re-executing the same workflow succeeds only if the original signer reconnects.


buildCreateStaticWorkflow()

buildCreateStaticWorkflow(params): Promise<WalletOperationWorkflow>;

Builds the workflow that creates a static LOC — one collateralized in the same token it is credited in, so it carries no price exposure and cannot be liquidated.

The workflow is assembled from current chain state: deposit, ERC-20 approve, and vault-allowance steps appear only when the account is actually short. Read workflow.operations to show the user every signature they are about to give before calling workflow.execute().

Building does not validate. Call LOCModule.validateCreateStatic for early form feedback; execute() always repeats full validation against fresh state before its first prompt.

Parameters

ParameterTypeDescription
paramsCreateStaticLOCParamsThe beneficiary, credited amount, and expiration.
params.beneficiaryAddressThe Beneficiary: the account entitled to redeem the credited value before expiration, and the only party (besides a caller holding its signed authorization) that can cancel the LOC before it expires. If LOCConfig.locBeneficiaryAllowList is configured, it must be one of its entries.
params.creator?AddressThe LOC’s Creator. Defaults to the connected signer’s address. If set, it must equal the connected signer’s address, because the contract records the transaction sender as the Creator; a different value is rejected.
params.expirationTimestampSecondsbigintUnix-seconds instant at which the LOC expires — expired at, not after, this second. Must be in the future and no further out than the deployment’s maximum duration; LOCModule.getMinDate and LOCModule.getMaxDate give the SDK’s padded bounds. After expiration the Beneficiary can no longer redeem and anyone may cancel to release the collateral.
params.locAllowanceSignature?BytesVault allowance signature letting the LetterOfCredit contract reserve this LOC’s collateral, from VaultModule.buildModifyAllowanceAuthorizationWorkflow. When it is omitted and the allowance is short, the workflow asks the wallet to sign one.
params.tag?BytesOptional reference data (for example an invoice number or document hash) recorded in the creation event and returned as origin.tag on LetterOfCredit; it is not stored in contract state. 0x-prefixed hex of at most 512 bytes (LOCModule.getCreateTagByteLimit).
params.tokenAmountTokenAmountThe LOC’s face value: the token credited to the Beneficiary and, because a Static LOC is 1:1, also the collateral, in the token’s smallest unit. The vault reserves the amount plus its withdrawal fee so the full face value is redeemable; the workflow tops the vault up to that figure. If LOCConfig.staticLOCTokenAddressAllowlist is configured, tokenAddress must be one of its entries.

Returns

Promise<WalletOperationWorkflow>

The workflow to present and execute.

Example

const params: CreateStaticLOCParams = {
beneficiary: '0x1111111111111111111111111111111111111111',
// 1,000 USDC (6 decimals): face value and, for a static LOC,
// collateral.
tokenAmount: {
tokenAddress: testnetProfile.contracts.USDC.address,
amount: 1_000_000_000n,
},
expirationTimestampSeconds: dateToEthereumTimestamp(
await sdk.loc.getMaxDate()
),
};
// Validate before touching the wallet; an empty array means valid
// params.
const issues = await sdk.loc.validateCreateStatic(params);
if (issues.length > 0) throw new Error(JSON.stringify(issues));
// Deposit, approve, and allowance steps appear only if the vault is
// short.
const workflow = await sdk.loc.buildCreateStaticWorkflow(params);
await workflow.execute(operations => {
console.log(operations.map(operation => operation.status));
});

Throws

WorkflowSignerChangedError If the SDK’s configured accountAddress and the connected wallet’s account disagree, or if the signer observed while executing differs from the one observed while building. Rebuild the workflow for the currently connected signer; re-executing the same workflow succeeds only if the original signer reconnects.


getCreateTagByteLimit()

getCreateTagByteLimit(): number;

Returns the largest tag (reference data), in bytes, that the LetterOfCredit contract in this SDK’s profile accepts at creation. Every published profile accepts 512 bytes.

Use this value for form counters and client-side validation so users do not compose a tag the contract will reject.

Returns

number

The maximum tag size in bytes.


getMaxDate()

getMaxDate(): Promise<Date>;

Returns the latest expiration a LOC created right now may carry: the current time plus the deployment’s maximum duration, rounded down to the hour.

Like LOCModule.getMinDate it is conservative relative to the contract and it moves with the clock.

Returns

Promise<Date>

The latest expiration date the SDK treats as valid.


getMaxDuration()

getMaxDuration(): Promise<number>;

Returns the deployment’s maximum LOC duration, in seconds.

This bounds the window from now to expiration, not the LOC’s total lifetime: extending repeatedly can keep a LOC alive far longer, so long as its remaining duration never exceeds this value at any moment.

Returns

Promise<number>

The maximum duration in seconds.


getMinDate()

getMinDate(): Promise<Date>;

Returns the earliest expiration a LOC created right now may carry.

The SDK pads the current time by two hours so a LOC is not already invalid by the time the user signs. The result can therefore sit further out than the contract’s own minimum, and it moves with the clock — read it when you build the form, not once at startup.

Returns

Promise<Date>

The earliest expiration date the SDK treats as valid.


getRequiredCollateralForDynamic()

getRequiredCollateralForDynamic(params): Promise<bigint | undefined>;

Returns a contract-verified collateral estimate for a Dynamic LOC, given the collateral/credited token pair and the requested credited amount.

For a positive credited amount, the SDK starts from a floor estimate and returns the smallest amount at or above it that the contract’s creation check would accept, so the result can exceed the absolute minimum.

Returns undefined when no collateral amount can satisfy the pair’s creation collateral factor: either the pair is unconfigured or disabled (a zero creation factor), or the oracle reports a zero price. Treat undefined as “this pair cannot back this LOC right now”, not as zero.

For an enabled pair, a price that cannot be fetched causes this call to reject. An unconfigured pair returns undefined even if its concurrent price read fails; a failed factor read takes precedence over a price error.

Parameters

ParameterTypeDescription
paramsGetRequiredCollateralForDynamicLOCParamsThe token pair and credited amount to collateralize.
params.collateralTokenAddress`0x${string}`Token that will back the LOC (the input side of the oracle price).
params.creationCollateralFactorBasisPoints?bigintOverride for the pair’s creation collateral factor. Omit to read it from the LetterOfCredit contract; pass 0n (a disabled pair) and the result is undefined without any network call.
params.creditedTokenAmountTokenAmountToken and amount the LOC will credit, in the credited token’s smallest unit.
params.oraclePrice?PriceOverride for the collateral-to-credited price (see Price). Omit to fetch a fresh Pyth price via PricingModule.getPrice; supply one to keep several calculations on the same quote.

Returns

Promise<bigint | undefined>

The required collateral, or undefined if there is no valid amount for these parameters.


getRequiredCollateralForStatic()

getRequiredCollateralForStatic(params): Promise<bigint>;

Returns the minimum collateral a static LOC needs for the requested credited amount.

A static LOC is collateralized in the credited token itself, so this is close to the face value — but not equal to it: the vault’s withdrawal fee dominates the difference.

Parameters

ParameterTypeDescription
paramsGetRequiredCollateralForStaticLOCParamsThe credited token and amount to collateralize.
params.collateralTokenAmountbigintFace value the static LOC will credit, in the token’s smallest unit (collateral and credited token are the same). The result is this amount grossed up by the vault withdrawal fee, because the vault reserves amount + fee so the Beneficiary can claim the full face value.
params.vaultWithdrawalFeeBasisPoints?numberOverride for the vault’s withdrawal fee (basis points). Omit to read it from the Collateral Vault via VaultModule.getWithdrawalFeeBasisPoints; 0 is honored as an explicit zero fee.

Returns

Promise<bigint>

The required collateral, in the token’s smallest units.


validateCreateDynamic()

validateCreateDynamic(params, signal?): Promise<ValidationIssue[]>;

Validates Dynamic LOC creation parameters without touching the wallet: Beneficiary format and allowlist, expiration format and bounds, collateral token and amount against the vault balance, credited token validity, tag length, and the freshness of a price update you supply.

Vault allowance is deliberately not checked here. The workflow builder resolves a short allowance on its own, so failing validation on it would block a submission that would have succeeded.

Parameters

ParameterTypeDescription
paramsPartial<CreateDynamicLOCParams>The partial creation parameters to check. Fields as listed under buildCreateDynamicWorkflow, each optional here.
signal?AbortSignalAborts the validation’s onchain reads; the call then rejects with the signal’s reason.

Returns

Promise<ValidationIssue[]>

The issues found. An empty array means every rule ran and passed; a rule whose required field is missing reports FieldRequired instead of being skipped. An infrastructure failure rejects rather than returning a partial list.

Throws

When validation itself cannot run: a typed SDK error passes through unchanged, a provider failure becomes ProviderConnectionError, any other failure becomes ContactSupportError, and an abort rejects with the signal’s reason.


validateCreateStatic()

validateCreateStatic(params, signal?): Promise<ValidationIssue[]>;

Validates Static LOC creation parameters without touching the wallet.

Takes a Partial, so it is safe to call on a half-filled form. A rule that only reads a missing field to check another one waits until that field is filled in; a rule whose own field is missing reports FieldRequired as an issue rather than throwing. Failures that stop validation from running at all still reject (see @throws).

Parameters

ParameterTypeDescription
paramsPartial<CreateStaticLOCParams>The partial creation parameters to check. Fields as listed under buildCreateStaticWorkflow, each optional here.
signal?AbortSignalAborts the validation’s onchain reads; the call then rejects with the signal’s reason.

Returns

Promise<ValidationIssue[]>

The issues found. An empty array means every rule ran and passed; a rule whose required field is missing reports FieldRequired instead of being skipped. An infrastructure failure rejects rather than returning a partial list.

Examples

import { createPublicClient, http } from 'viem';
import { sepolia } from 'viem/chains';
import { AnvilSDK, type CreateStaticLOCParams, testnetProfile } from '@anvilresearchlabs/sdk/core';
const sdk = new AnvilSDK({
publicClient: createPublicClient({
chain: sepolia,
transport: http('https://your-rpc-url'),
}),
profile: testnetProfile,
// In an app this is the connected user (wagmi's `useAccount().address`).
accountAddress: '0x50f91632bd0fb4d4521718e73db3c59ecee69351',
});
const params: CreateStaticLOCParams = {
beneficiary: '0x3c5bea6f8edba748330ad0c0e19bea6731ac57dd',
tokenAmount: {
tokenAddress: testnetProfile.contracts.USDC.address,
amount: 25_000_000n, // 25 USDC at 6 decimals
},
expirationTimestampSeconds: BigInt(Math.floor(Date.now() / 1000) + 86400 * 30),
};
// An empty array means the params are valid.
const issues = await sdk.loc.validateCreateStatic(params);
console.log(issues);
import { ContactSupportError } from '@anvilresearchlabs/sdk/core';
import { ProviderConnectionError } from '@anvilresearchlabs/sdk/core';
import type { ValidationIssue } from '@anvilresearchlabs/sdk/core';
type ValidationOutcome =
| { readonly kind: 'issues'; readonly issues: ValidationIssue[] }
| { readonly kind: 'retry' }
| { readonly kind: 'unavailable'; readonly cause: unknown };
async function validateOrClassifyFailure(): Promise<ValidationOutcome> {
try {
const issues = await sdk.loc.validateCreateStatic(params);
return { kind: 'issues', issues };
} catch (error) {
if (error instanceof ProviderConnectionError) {
// Recognizable RPC/subgraph failure -- safe to retry.
return { kind: 'retry' };
}
if (error instanceof ContactSupportError) {
// Unclassifiable failure -- not retryable; surface it as-is.
return { kind: 'unavailable', cause: error };
}
// A typed SDK error a rule already threw, or caller cancellation --
// propagate unchanged.
throw error;
}
}
console.log(await validateOrClassifyFailure());

Throws

When validation itself cannot run: a typed SDK error passes through unchanged, a provider failure becomes ProviderConnectionError, any other failure becomes ContactSupportError, and an abort rejects with the signal’s reason.

Manage

buildCancelAndWithdrawWorkflow()

buildCancelAndWithdrawWorkflow(params): Promise<WalletOperationWorkflow>;

Builds the workflow that cancels one or more LOCs and withdraws the collateral they release, in a single sequence.

Because Multicall is the immediate caller, every unexpired LOC must be supplied through cancelCalls with the beneficiary’s valid authorization, even when the connected transaction signer is that beneficiary. Use locIDs only as shorthand for already-expired LOCs. The withdrawal leg is subject to the vault’s withdrawal fee (VaultModule.getWithdrawalFeeBasisPoints).

Parameters

ParameterTypeDescription
paramsCancelLOCsAndWithdrawParamsThe LOCs to cancel and what to withdraw afterwards.

Returns

Promise<WalletOperationWorkflow>

The workflow to present and execute.

Throws

WorkflowSignerChangedError If the SDK’s configured accountAddress and the connected wallet’s account disagree, or if the signer observed while executing differs from the one observed while building. Rebuild the workflow for the currently connected signer; re-executing the same workflow succeeds only if the original signer reconnects.


buildCancelManyWorkflow()

buildCancelManyWorkflow(params): Promise<WalletOperationWorkflow>;

Builds a workflow that cancels one or more LOCs atomically through Multicall.

Because Multicall is the immediate caller, every unexpired LOC must carry the beneficiary’s valid authorization, even when the connected transaction signer is that beneficiary. Authorizations consume sequential nonces per beneficiary in batch order; expired LOCs need no authorization and consume no nonce. See CancelLOCsParams for a complete signing example.

Parameters

ParameterTypeDescription
paramsCancelLOCsParamsThe ordered LOC cancellation calls to submit atomically.
params.cancelCallsCancelLOCParams[]Cancellation calls in execution order. LOC ids must be unique. See CancelLOCParams.beneficiaryAuthorization for the authorization difference between direct and Multicall-based cancellation.

Returns

Promise<WalletOperationWorkflow>

The signer-pinned workflow to present and execute. It reruns fresh validation before every execution attempt.

Throws

WorkflowSignerChangedError If the SDK’s configured accountAddress and the connected wallet’s account disagree while building. A signer change after the workflow is built is returned by execute() in the cancellation operation’s status rather than thrown by this builder.


buildCancelWorkflow()

buildCancelWorkflow(params): Promise<WalletOperationWorkflow>;

Builds the workflow that cancels a LOC, releasing its reserved collateral back to the creator’s vault balance.

Before expiration the beneficiary, or a caller holding the beneficiary’s valid authorization, may cancel, since canceling gives up the beneficiary’s claim. Once the LOC has expired, cancellation is permissionless — any account may do it, and the collateral still returns to the creator.

To cancel and pull the freed collateral out of the vault in one pass, use LOCModule.buildCancelAndWithdrawWorkflow.

Parameters

ParameterTypeDescription
paramsCancelLOCParamsThe LOC to cancel.
params.beneficiaryAuthorization?BytesEIP-712 CancelAuthorization signed by the Beneficiary. Build and sign it with sdk.loc.buildCancelAuthorizationWorkflow. A direct buildCancelWorkflow call needs it only when the connected signer is not the Beneficiary and the LOC has not expired. Multicall-based batch methods need it for every unexpired entry because Multicall is the immediate caller. Explicit undefined is equivalent to omission.
params.idbigintID of the LOC to cancel (LetterOfCreditReference.id). Before expiration only the Beneficiary or a holder of its authorization may cancel; after expiration anyone may.

Returns

Promise<WalletOperationWorkflow>

The workflow to present and execute.

Throws

WorkflowSignerChangedError If the SDK’s configured accountAddress and the connected wallet’s account disagree, or if the signer observed while executing differs from the one observed while building. Rebuild the workflow for the currently connected signer; re-executing the same workflow succeeds only if the original signer reconnects.


buildConvertWorkflow()

buildConvertWorkflow(params): Promise<WalletOperationWorkflow>;

Builds the permissionless workflow that converts one unexpired, unhealthy dynamic LOC into its credited token. The creator has no privileged path: a healthy LOC is rejected for every caller.

Omit liquidator (or pass the zero address) to supply approved credited tokens yourself and receive collateral plus the incentive. Name an ILiquidator contract to forward collateral and require the credited amount back from it. The SDK does not choose a liquidator for you.

Parameters

ParameterTypeDescription
paramsConvertLOCParamsThe LOC, settlement mode, liquidator calldata, and price mode.
params.idbigintID of the dynamic LOC to convert (LetterOfCreditReference.id).
params.liquidator?AddressContract implementing ILiquidator. Omit it or pass the zero address for self-liquidation, where the caller supplies approved credited tokens and receives collateral plus the liquidator incentive. The SDK does not choose a liquidator for you. Explicit undefined is equivalent to omission.
params.liquidatorParams?BytesOpaque calldata forwarded to the external liquidator. It must be empty or omitted for self-liquidation. Explicit undefined is equivalent to omission.
params.oraclePriceUpdate?OraclePriceUpdate | nullSigned Pyth update for the collateral/credited pair. A non-empty update object is forwarded verbatim and its fee is attached as transaction value. Omit it to fetch automatically when the transaction is built; if that fetch fails, the SDK uses the onchain price only after proving it is still fresh, and otherwise rejects with the price-service error. Pass null to skip the fetch and use the current onchain price. An object whose data is '0x' is invalid; use null for the onchain-price mode.

Returns

Promise<WalletOperationWorkflow>

The inspectable one-step conversion workflow.

Example

const params: ConvertLOCParams = {
id: 42n,
// Any ILiquidator is valid; the SDK does not choose one for you.
liquidator,
liquidatorParams,
// Omitted: fetch a fresh Pyth update when the transaction is built.
};
const issues = await sdk.loc.validateConvert(params);
if (issues.length > 0) throw new Error(JSON.stringify(issues));
// Healthy LOCs still revert for every caller. Conversion is
// permissionless
// only after the current pair's liquidation threshold is reached.
const workflow = await sdk.loc.buildConvertWorkflow(params);
await workflow.execute();

Throws

WorkflowSignerChangedError If the SDK’s configured accountAddress and the connected wallet’s account disagree, or if the signer observed while executing differs from the one observed while building. Rebuild the workflow for the currently connected signer; re-executing the same workflow succeeds only if the original signer reconnects.


buildExtendWorkflow()

buildExtendWorkflow(params): Promise<WalletOperationWorkflow>;

Builds the workflow that moves a LOC’s expiration later.

Only the creator may extend, the new expiration must be later than the current one, and the LOC must not have expired already — an expired LOC cannot be revived, only canceled. The new remaining duration must also fit within LOCModule.getMaxDuration.

Parameters

ParameterTypeDescription
paramsExtendLOCParamsThe LOC id and its new expiration.
params.locIDbigintID of the LOC to extend (LetterOfCreditReference.id). Only the Creator may extend, and only while the LOC is unexpired.
params.newExpirationTimestampSecondsbigintNew expiration as Unix seconds. Must be later than the current expiration and no more than the deployment’s maximum duration (LOCModule.getMaxDuration) from now — a LOC may live longer than the maximum in total, but never have more than the maximum remaining.

Returns

Promise<WalletOperationWorkflow>

The workflow to present and execute.

Throws

WorkflowSignerChangedError If the SDK’s configured accountAddress and the connected wallet’s account disagree, or if the signer observed while executing differs from the one observed while building. Rebuild the workflow for the currently connected signer; re-executing the same workflow succeeds only if the original signer reconnects.


buildModifyCollateralWorkflow()

buildModifyCollateralWorkflow(params): Promise<WalletOperationWorkflow>;

Builds the workflow that adds collateral to, or removes collateral from, an existing Dynamic LOC.

This is the lever for managing liquidation risk on a live LOC: adding collateral moves it away from its liquidation threshold, removing moves it closer. Removing is the price-dependent direction — the projected position still has to back the credited amount — so a removal can be rejected on a price move that an addition would not be.

A LOC whose collateral and credited tokens are the same cannot be modified at all.

Parameters

ParameterTypeDescription
paramsModifyLOCCollateralParamsThe LOC and the collateral change to apply.
params.byAmountbigintChange in collateral, in the collateral token’s smallest unit: positive adds, negative removes. Zero is invalid.
params.collateralizableAllowanceSignature?BytesVault allowance signature letting the LetterOfCredit contract reserve the added collateral. When adding and it is omitted, the workflow deposits any shortfall and asks the wallet to sign an allowance if one is still needed.
params.creator?AddressThe LOC’s Creator, whose vault balance and allowance the workflow reads when adding collateral. Defaults to the connected signer’s address.
params.locIdbigintID of the LOC to modify (LetterOfCreditReference.id).
params.oraclePriceUpdate?OraclePriceUpdateSourceOracle price update used only when removing collateral. Supply an update from PricingModule.getOraclePriceUpdate to forward its bytes and fee, 'auto' to fetch one when the final transaction is built, or null or omit the field to use the current onchain price, with no fetch and no fee.

Returns

Promise<WalletOperationWorkflow>

The workflow to present and execute.

Throws

WorkflowSignerChangedError If the SDK’s configured accountAddress and the connected wallet’s account disagree, or if the signer observed while executing differs from the one observed while building. Rebuild the workflow for the currently connected signer; re-executing the same workflow succeeds only if the original signer reconnects.


buildRedeemWorkflow()

buildRedeemWorkflow(params): Promise<WalletOperationWorkflow>;

Builds the workflow that redeems one or more LOCs to each resolved payout destination and releases any collateral left over to the creator. A beneficiary authorization may direct its payout to another account.

Redemption may be partial: pass less than the remaining credited amount and the LOC stays open for the balance. Redeeming the full remaining amount removes the LOC from contract storage, after which LOCModule.getOutstandingLetterOfCredit returns undefined for it.

On a dynamic LOC the payout asset depends on liquidator, and the SDK picks none by default because the two modes pay out differently. With a liquidator, the collateral is converted and the redemption pays in the credited token. Without one, the redeemer takes the collateral plus the liquidator incentive and must itself hold and approve the credited amount the contract pulls back. Decide which mode you want before calling.

Parameters

ParameterTypeDescription
paramsRedeemLOCsParamsThe redemptions to perform, each an id and an amount.
params.redemptionsRedeemLOCParams[]One RedeemLOCParams per LOC to redeem: which LOC, how much of it, where the payout goes, and the Beneficiary’s authorization when the caller is not the Beneficiary. Two or more entries are batched atomically through Multicall, so the contract sees Multicall rather than the Beneficiary as the caller and every entry needs a beneficiaryAuthorization; nonces are consumed per Beneficiary in array order. Every actionable LOC in a batch must already have matching collateral and credited tokens; Dynamic LOCs are rejected before calldata is built.

Returns

Promise<WalletOperationWorkflow>

The workflow to present and execute.

Example

// The connected wallet is the LOC's beneficiary.
const loc = await sdk.loc.getOutstandingLetterOfCredit({ id: 42n });
if (!loc) throw new Error('LOC 42 is no longer outstanding');
// One entry, full remaining face value, paid to the signer.
const params: RedeemLOCsParams = {
redemptions: [
{ id: loc.reference.id, amount: loc.remainingCredited.amount },
],
};
const issues = await sdk.loc.validateRedeem(params);
if (issues.length > 0) throw new Error(JSON.stringify(issues));
const workflow = await sdk.loc.buildRedeemWorkflow(params);
await workflow.execute();

Throws

WorkflowSignerChangedError If the SDK’s configured accountAddress and the connected wallet’s account disagree, or if the signer observed while executing differs from the one observed while building. Rebuild the workflow for the currently connected signer; re-executing the same workflow succeeds only if the original signer reconnects.


validateCancel()

validateCancel(params, signal?): Promise<ValidationIssue[]>;

Validates cancellation parameters without touching the wallet: the LOC has outstanding contract state and cancellation is permitted — which means the signer is the Beneficiary, or the LOC has expired, or a valid Beneficiary authorization was supplied.

Parameters

ParameterTypeDescription
paramsPartial<CancelLOCParams>The partial cancellation parameters to check. Fields as listed under buildCancelWorkflow, each optional here.
signal?AbortSignalAborts the validation’s onchain reads; the call then rejects with the signal’s reason.

Returns

Promise<ValidationIssue[]>

The issues found. An empty array means every rule ran and passed; a rule whose required field is missing reports FieldRequired instead of being skipped. An infrastructure failure rejects rather than returning a partial list.

Throws

When validation itself cannot run: a typed SDK error passes through unchanged, a provider failure becomes ProviderConnectionError, any other failure becomes ContactSupportError, and an abort rejects with the signal’s reason.


validateCancelAndWithdraw()

validateCancelAndWithdraw(params, signal?): Promise<ValidationIssue[]>;

Validates combined cancel-and-withdraw parameters without touching the wallet: the cancellations as LOCModule.validateCancelMany checks them, and the withdrawal against the balance they would release.

Parameters

ParameterTypeDescription
paramsPartial<CancelLOCsAndWithdrawParams>The partial parameters to check.
signal?AbortSignalAborts the validation’s onchain reads; the call then rejects with the signal’s reason.

Returns

Promise<ValidationIssue[]>

The issues found. An empty array means every rule ran and passed; a rule whose required field is missing reports FieldRequired instead of being skipped. An infrastructure failure rejects rather than returning a partial list.

Throws

When validation itself cannot run: a typed SDK error passes through unchanged, a provider failure becomes ProviderConnectionError, any other failure becomes ContactSupportError, and an abort rejects with the signal’s reason.


validateCancelMany()

validateCancelMany(params, signal?): Promise<ValidationIssue[]>;

Validates an atomic batch of LOC cancellations without touching the wallet.

cancelCalls is required: an absent batch reports FieldRequired for it, and an explicitly empty batch is invalid for a different reason (a separate issue on the same field). Every supplied LOC must be outstanding and unique. Because Multicall is the caller, every unexpired LOC also needs the beneficiary’s valid authorization with the expected per-beneficiary nonce. Expired LOCs need no authorization and consume no nonce.

Parameters

ParameterTypeDescription
paramsPartial<CancelLOCsParams>The partial batch parameters currently available. A missing cancelCalls reports FieldRequired rather than being silently skipped. Fields as listed under buildCancelManyWorkflow, each optional here.
signal?AbortSignalAborts the validation’s onchain reads; the call then rejects with the signal’s reason.

Returns

Promise<ValidationIssue[]>

The issues found. An empty array means every rule ran and passed; a rule whose required field is missing reports FieldRequired instead of being skipped. An infrastructure failure rejects rather than returning a partial list.

Throws

When validation itself cannot run: a typed SDK error passes through unchanged, a provider failure becomes ProviderConnectionError, any other failure becomes ContactSupportError, and an abort rejects with the signal’s reason.


validateConvert()

validateConvert(params, signal?): Promise<ValidationIssue[]>;

Validates a LOC conversion without checking who the caller is, since anyone may convert. The LOC’s state and the shape of the inputs are checked right away. Health is checked only when oraclePriceUpdate is null, because an automatic or supplied update can change the price the contract will use.

Parameters

ParameterTypeDescription
paramsPartial<ConvertLOCParams>The conversion fields available so far. A missing id reports FieldRequired rather than being skipped; a rule that only reads another missing field waits until it is filled in. Fields as listed under buildConvertWorkflow, each optional here.
signal?AbortSignalAborts the validation’s onchain reads; the call then rejects with the signal’s reason.

Returns

Promise<ValidationIssue[]>

The issues found, each tied to a field. An empty array means a complete request passed every check; with a supplied or automatically fetched price, the contract makes the final health decision. An infrastructure failure rejects rather than returning a partial list.

Throws

When validation itself cannot run: a typed SDK error passes through unchanged, a provider failure becomes ProviderConnectionError, any other failure becomes ContactSupportError, and an abort rejects with the signal’s reason.


validateExtend()

validateExtend(params, signal?): Promise<ValidationIssue[]>;

Validates extension parameters without touching the wallet. The Creator check uses the configured accountAddress, or the wallet’s account.

Parameters

ParameterTypeDescription
paramsPartial<ExtendLOCParams>The partial extension parameters to check. Fields as listed under buildExtendWorkflow, each optional here.
signal?AbortSignalAborts the validation’s onchain reads; the call then rejects with the signal’s reason.

Returns

Promise<ValidationIssue[]>

The issues found. An empty array means every rule ran and passed; a rule whose required field is missing reports FieldRequired instead of being skipped. An infrastructure failure rejects rather than returning a partial list.

Throws

WalletNotConnectedError If neither accountAddress nor a wallet is configured.

Throws

When validation itself cannot run: a typed SDK error passes through unchanged, a provider failure becomes ProviderConnectionError, any other failure becomes ContactSupportError, and an abort rejects with the signal’s reason.


validateModifyCollateral()

validateModifyCollateral(params, signal?): Promise<ValidationIssue[]>;

Validates a collateral change on an existing Dynamic LOC without touching the wallet: the change is non-zero, the LOC exists and has not expired, and its collateral and credited tokens actually differ. The Creator check uses the configured accountAddress, or the wallet’s account. With no oracle update, the remaining collateral is checked against the current onchain price. With an automatic or supplied update, the contract makes that price-dependent check, because the new price can change the outcome; an empty issue list in those modes does not guarantee enough collateral at execution.

Parameters

ParameterTypeDescription
paramsPartial<ModifyLOCCollateralParams>The partial modification parameters to check. Fields as listed under buildModifyCollateralWorkflow, each optional here.
signal?AbortSignalAborts the validation’s onchain reads; the call then rejects with the signal’s reason.

Returns

Promise<ValidationIssue[]>

The issues found. An empty array means every rule ran and passed; a rule whose required field is missing reports FieldRequired instead of being skipped. An infrastructure failure rejects rather than returning a partial list.

Throws

WalletNotConnectedError If neither accountAddress nor a wallet is configured.

Throws

When validation itself cannot run: a typed SDK error passes through unchanged, a provider failure becomes ProviderConnectionError, any other failure becomes ContactSupportError, and an abort rejects with the signal’s reason.


validateRedeem()

validateRedeem(params, signal?): Promise<ValidationIssue[]>;

Validates redemption parameters without touching the wallet: each amount is positive and within the LOC’s remaining credited value, the LOC exists and has not expired, and the redemption is authorized.

Authorization is a choice, not a single rule: for one redemption with no beneficiaryAuthorization the signer must be the Beneficiary; supply an authorization, or redeem several LOCs at once, and the Beneficiary’s signature is verified instead.

Parameters

ParameterTypeDescription
paramsPartial<RedeemLOCsParams>The partial redemption parameters to check. Fields as listed under buildRedeemWorkflow, each optional here.
signal?AbortSignalAborts the validation’s onchain reads; the call then rejects with the signal’s reason.

Returns

Promise<ValidationIssue[]>

The issues found. An empty array means every rule ran and passed; a rule whose required field is missing reports FieldRequired instead of being skipped. An infrastructure failure rejects rather than returning a partial list.

Example

// The connected wallet is the LOC's beneficiary.
const loc = await sdk.loc.getOutstandingLetterOfCredit({ id: 42n });
if (!loc) throw new Error('LOC 42 is no longer outstanding');
// One entry, full remaining face value, paid to the signer.
const params: RedeemLOCsParams = {
redemptions: [
{ id: loc.reference.id, amount: loc.remainingCredited.amount },
],
};
const issues = await sdk.loc.validateRedeem(params);
if (issues.length > 0) throw new Error(JSON.stringify(issues));
const workflow = await sdk.loc.buildRedeemWorkflow(params);
await workflow.execute();

Throws

When validation itself cannot run: a typed SDK error passes through unchanged, a provider failure becomes ProviderConnectionError, any other failure becomes ContactSupportError, and an abort rejects with the signal’s reason.

Read

getLetterOfCredit()

getLetterOfCredit(params, options?): Promise<LetterOfCredit | undefined>;

Reads the full record of one LOC from the subgraph: its origin, creation-time terms, lifecycle, and current position. Redeemed and canceled LOCs are still returned.

Parameters

ParameterTypeDescription
paramsGetLetterOfCreditParamsThe LOC’s numeric id on this profile’s LetterOfCredit contract.
params.idbigintThe LOC’s numeric id; the result carries its full reference (chain, contract, and id).
optionsReadExecutionOptionsCancellation controls for the read.
options.signal?AbortSignalCancels the read and preserves the caller’s abort reason.

Returns

Promise<LetterOfCredit | undefined>

The LOC, or undefined when the subgraph has no LOC with that id.

Throws

SubgraphCompatibilityError If the subgraph’s data for this LOC is incomplete or in a shape this SDK version cannot read.

Example

const loc = await sdk.loc.getLetterOfCredit({ id: 14n });
if (!loc) return;
const now = BigInt(Math.floor(Date.now() / 1000));
const status = deriveLetterOfCreditStatus(loc, now);
console.log(
loc.origin.credited,
loc.lifecycle.resolution,
status.displayStatus
);
console.log(loc.indexedAt.deployment, loc.indexedAt.blockHash);
// No caller selected: every direct capability is false.
const capabilities = deriveLetterOfCreditDirectCapabilities(
loc,
status,
null,
null
);
console.log(capabilities);

getLetterOfCreditHistory()

getLetterOfCreditHistory(params, options?): Promise<LetterOfCreditHistoryPage>;

Reads one LOC’s history from the subgraph: one entry per transaction that changed it, each with the state before and after and the operations it performed, in order.

Parameters

ParameterTypeDescription
paramsGetLetterOfCreditHistoryParamsThe LOC’s numeric id and paging controls; limit counts transactions, not events.
params.cursor?string | nullThe nextCursor from the previous page, passed back unchanged. Omit it, or pass null, for the first page.
params.idbigintThe LOC’s numeric id on the profile’s LetterOfCredit contract.
params.limit?numberMaximum number of items on the page, from 1 to 1000. Defaults to 250.
optionsReadExecutionOptionsCancellation controls for the page read. Fields as listed under getLetterOfCredit.

Returns

Promise<LetterOfCreditHistoryPage>

One page of history entries and the cursor for the next page.

Throws

SubgraphCompatibilityError If the subgraph’s history for this LOC is incomplete or in a shape this SDK version cannot read.

Example

const id = 14n;
let page = await sdk.loc.getLetterOfCreditHistory({ id, limit: 25 });
const entries = [...page.items];
while (page.nextCursor !== null) {
page = await sdk.loc.getLetterOfCreditHistory({
id,
limit: 25,
cursor: page.nextCursor,
});
entries.push(...page.items);
}
for (const entry of entries) {
console.log(entry.transaction.hash, entry.before, entry.after);
for (const change of entry.changes) {
console.log(change.type, change);
for (const event of change.events) {
console.log(event.sourceEvent, event.transactionLogIndex);
}
}
}

getLetterOfCredits()

getLetterOfCredits(params?, options?): Promise<LetterOfCreditPage>;

Lists the full records of LOCs from the subgraph, including redeemed and canceled ones. Every page of one listing reads the same indexed block, so paging through with nextCursor gives a consistent snapshot.

Parameters

ParameterTypeDescription
paramsGetLetterOfCreditsParamsCreator, Beneficiary, Static or Dynamic, outstanding, and paging filters.
params.beneficiaries?`0x${string}`[]Only LOCs for one of these Beneficiaries. Omit, or pass an empty list, for every Beneficiary.
params.creationKind?"static" | "dynamic"Only Static or only Dynamic LOCs, as created; a fully converted Dynamic LOC still counts as 'dynamic'.
params.creators?`0x${string}`[]Only LOCs created by one of these accounts. Omit, or pass an empty list, for every Creator.
params.cursor?string | nullThe nextCursor from the previous page, passed back unchanged. Omit it, or pass null, for the first page.
params.limit?numberMaximum number of items on the page, from 1 to 1000. Defaults to 250.
params.outstanding?booleantrue for LOCs still open, including expired ones nobody has canceled; false for redeemed or canceled LOCs. Omit for both.
optionsReadExecutionOptionsCancellation controls for the page read. Fields as listed under getLetterOfCredit.

Returns

Promise<LetterOfCreditPage>

One page of LOCs, the indexed block it was read at, and the cursor for the next page.

Throws

SubgraphCompatibilityError If any LOC on the page, or the subgraph itself, is in a shape this SDK version cannot read.

Example

const creator = await sdk.getSignerAddress();
const filters = {
creators: [creator],
creationKind: 'dynamic' as const,
limit: 50,
};
let page = await sdk.loc.getLetterOfCredits(filters);
const locs = [...page.items];
while (page.nextCursor !== null) {
page = await sdk.loc.getLetterOfCredits({
...filters,
cursor: page.nextCursor,
});
locs.push(...page.items);
}
// Includes resolved LOCs. Every continuation preserves the first index
// boundary.
console.log(locs.map(loc => [loc.reference, loc.lifecycle.resolution]));

getOutstandingLetterOfCredit()

getOutstandingLetterOfCredit(params): Promise<OutstandingLetterOfCredit | undefined>;

Reads a LOC’s live position straight from the LetterOfCredit contract: what it still promises, its expiration, and the collateral behind it. Expired LOCs that nobody has canceled yet are still returned. No subgraph is needed.

Parameters

ParameterTypeDescription
paramsGetOutstandingLetterOfCreditParamsThe LOC’s numeric id on this profile’s LetterOfCredit contract.
params.idbigintThe LOC’s numeric id on the profile’s LetterOfCredit contract (a uint96). Unknown, redeemed, and canceled LOCs return undefined.

Returns

Promise<OutstandingLetterOfCredit | undefined>

The live position, or undefined when no LOC has that id or it has been fully redeemed or canceled.

Throws

InvalidArgumentError If the id does not fit in a uint96.

Throws

ConfigError If the connected chain differs from the configured profile.

Example

const loc = await sdk.loc.getOutstandingLetterOfCredit({ id: 14n });
if (loc === undefined) {
// Fully redeemed or canceled LOCs are purged from contract state.
console.log('LOC 14 is no longer outstanding');
return;
}
const expires = ethereumTimestampToDate(loc.expirationTimestamp);
const { amount, tokenAddress } = loc.remainingCredited;
console.log(
`${amount} ${tokenAddress} owed to ` +
`${loc.beneficiary}, expires ${expires.toISOString()}`
);

getOutstandingLetterOfCredits()

getOutstandingLetterOfCredits(params?, options?): Promise<CollectionPage<OutstandingLetterOfCredit>>;

Returns a page of live positions (OutstandingLetterOfCredit) for LOCs that are neither fully redeemed nor canceled. Expired LOCs that nobody has canceled yet are included; anyone may cancel them.

The subgraph supplies the page, then each LOC is read fresh from the contract, so the SDK must have been configured with a subgraph URL. An entry the subgraph still lists but the contract has already removed is dropped, which means a page can hold fewer than limit results even while nextCursor is non-null — page until nextCursor is null rather than until a short page appears.

Parameters

ParameterTypeDescription
paramsGetOutstandingLetterOfCreditsParamsPaging and filter options for the collection.
params.beneficiaries?`0x${string}`[]Beneficiary accounts to include; omitted or empty means any Beneficiary.
params.creationKind?"static" | "dynamic"Only Static or only Dynamic LOCs, as created; a fully converted Dynamic LOC still counts as 'dynamic'.
params.creators?`0x${string}`[]Creator accounts to include; omitted or empty means any Creator.
params.cursor?string | nullThe nextCursor from the previous page, passed back unchanged. Omit it, or pass null, for the first page.
params.limit?numberMaximum number of items on the page, from 1 to 1000. Defaults to 250.
optionsReadExecutionOptionsCancellation controls for this page read. Fields as listed under getLetterOfCredit.

Returns

Promise<CollectionPage<OutstandingLetterOfCredit>>

The matching page of LOCs.

Example

// Every outstanding dynamic LOC created by the connected account,
// including expired LOCs.
const creator = await sdk.getSignerAddress();
const filter = { creators: [creator], creationKind: 'dynamic' as const };
// Keep execution controls outside the filters. A route or component can
// call controller.abort(reason) to stop the in-flight page and any retry
// backoff immediately; the SDK also bounds each page with its own
// deadline.
const controller = new AbortController();
let page = await sdk.loc.getOutstandingLetterOfCredits(
{ ...filter, limit: 50 },
{ signal: controller.signal }
);
const locs = [...page.items];
while (page.nextCursor !== null) {
page = await sdk.loc.getOutstandingLetterOfCredits(
{
...filter,
limit: 50,
cursor: page.nextCursor,
},
{ signal: controller.signal }
);
locs.push(...page.items);
}
// Pages can be short: LOCs the subgraph still lists but the chain has
// purged are dropped.
console.log(`${locs.length} outstanding dynamic LOCs`);

Collateral and tokens

getCollateralFactor()

getCollateralFactor(params): Promise<CollateralFactor | undefined>;

Returns the CollateralFactor the LetterOfCredit contract holds for a collateral/credited token pair: the creation, liquidation, and incentive basis points that govern a dynamic LOC on that pair.

Returns undefined for an unconfigured pair: the SDK normalizes the contract getter’s zero-filled tuple to an absent result. A configured pair can still have creationCollateralFactorBasisPoints === 0n, which disables dynamic LOC creation. In either case, LOCModule.getRequiredCollateralForDynamic returns undefined.

A ContractFunctionExecutionError from the read also returns undefined. Other errors cause this call to reject.

Parameters

ParameterTypeDescription
paramsGetCollateralFactorParamsThe collateral and credited token pair to look up.
params.collateralToken`0x${string}`Token that backs the LOC. Order matters: factors are configured per (collateral, credited) pair, not per unordered pair.
params.creditedToken`0x${string}`Token the LOC credits to the Beneficiary. LOCModule.getCollateralFactor returns undefined when the pair is not configured.

Returns

Promise<CollateralFactor | undefined>

The collateral factor, or undefined if the pair is unconfigured or the read raises a ContractFunctionExecutionError.


getCollateralToken()

getCollateralToken(params): Promise<CollateralToken | undefined>;

Returns the CollateralToken at an address, or undefined if the vault does not know it as collateral.

Parameters

ParameterTypeDescription
paramsGetCollateralTokenParamsThe collateral token address to look up.
params.address`0x${string}`ERC-20 address to look up in the Collateral Vault’s collateral registry. An undefined result means the vault has never registered it.
params.collateralContractAddress?`0x${string}`Collateral Vault to look in; defaults to the profile’s current vault.

Returns

Promise<CollateralToken | undefined>

The collateral token, or undefined if there is none.


getCollateralTokens()

getCollateralTokens(params?, options?): Promise<CollectionPage<CollateralToken>>;

Returns a page of every ERC-20 the Collateral Vault knows as collateral, each with its enabled flag and indexed name, symbol, and decimals.

Served from the subgraph — so a subgraph URL is required. Each call performs a fresh read; integrations that need caching should use the SDK’s shared query definition or their own query layer.

Parameters

ParameterTypeDescription
paramsGetCollateralTokensParamsPaging and filter options for the collection.
params.collateralContractAddress?`0x${string}`Collateral Vault whose tokens to list; defaults to the profile’s current vault.
params.cursor?string | nullThe nextCursor from the previous page, passed back unchanged. Omit it, or pass null, for the first page.
params.enabled?booleanFilter on whether the Collateral Vault currently accepts the token for new deposits and reservations. true returns only usable tokens (the common case for a token picker); false returns tokens Anvil Governance has disabled but that may still back existing LOCs; omit for both.
params.limit?numberMaximum number of items on the page, from 1 to 1000. Defaults to 250.
params.tokenAddressAllowlist?`0x${string}`[]Restrict results to these token addresses. Omit or pass [] for all collateral tokens.
optionsReadExecutionOptionsCancellation controls for this page read. Fields as listed under getLetterOfCredit.

Returns

Promise<CollectionPage<CollateralToken>>

The matching page of collateral tokens.

Example

// Every token the Collateral Vault currently accepts, across all pages.
const tokens: CollateralToken[] = [];
let cursor: string | undefined;
do {
const page = await sdk.loc.getCollateralTokens({
enabled: true,
cursor,
});
tokens.push(...page.items);
cursor = page.nextCursor ?? undefined;
} while (cursor);

Throws

ConfigError If neither subgraphUrl nor the configured profile supplies a subgraph endpoint. Thrown before any read.


getCollateralTokensForCreditedToken()

getCollateralTokensForCreditedToken(params, options?): Promise<CollectionPage<CollateralToken>>;

Returns the collateral tokens that may actually back a LOC credited in the given token — the list to populate a collateral picker with.

A token qualifies when it is not disabled and either is the credited token itself (the static case, where a token collateralizes itself), or has an enabled asset pair and a collateral factor with a non-zero creation requirement against the credited token (the dynamic case).

This is narrower than LOCModule.getCollateralTokens, which lists everything the vault accepts without regard to what it can back. Requires a subgraph URL.

Parameters

ParameterTypeDescription
paramsGetCollateralTokensForCreditedTokenParamsThe credited token to find eligible collateral for, plus paging options.
params.creditedToken`0x${string}`Address of the token the LOC will credit. Results are the enabled collateral tokens that may back it: the token itself (Static LOC) plus every token with an enabled asset pair and a non-zero creation collateral factor against it (Dynamic LOC).
params.cursor?string | nullThe nextCursor from the previous page, passed back unchanged. Omit it, or pass null, for the first page.
params.limit?numberMaximum number of items on the page, from 1 to 1000. Defaults to 250.
params.tokenAddressAllowlist?`0x${string}`[]Restrict the eligible result to these collateral token addresses.
optionsReadExecutionOptionsCancellation controls for this page read. Fields as listed under getLetterOfCredit.

Returns

Promise<CollectionPage<CollateralToken>>

The matching page of eligible collateral tokens.


getCreditedToken()

getCreditedToken(params): Promise<CreditedToken | undefined>;

Returns the CreditedToken configuration the LetterOfCredit contract holds for an address — the per-token minimum, per-LOC maximum, and global cap that bound what may be credited.

The contract getter is a mapping read: an ERC-20 that is simply not configured as credited comes back with zero limits rather than as undefined. undefined means the address did not answer as an ERC-20 at all, or the read failed.

Parameters

ParameterTypeDescription
paramsGetCreditedTokenParamsThe credited token address to look up.
params.address`0x${string}`ERC-20 address whose Dynamic LOC limits to read from the LetterOfCredit contract. A token that is not configured comes back with zero limits; the result is undefined only when the address is not a readable ERC-20.

Returns

Promise<CreditedToken | undefined>

The credited token, with zero limits when the address is not configured, or undefined if it is not a readable ERC-20.


getCreditedTokens()

getCreditedTokens(params?, options?): Promise<CollectionPage<CreditedToken>>;

Returns a page of the credited tokens configured for dynamic LOCs, each with its per-LOC bounds and global cap.

Served from the subgraph, so a subgraph URL is required. enabled and tokenAddressAllowlist narrow the page; the allowlist comparison is case-insensitive.

Parameters

ParameterTypeDescription
paramsGetCreditedTokensParamsOptional paging and filters.
params.cursor?string | nullThe nextCursor from the previous page, passed back unchanged. Omit it, or pass null, for the first page.
params.enabled?booleanRestrict results to enabled or disabled credited-token configurations.
params.limit?numberMaximum number of items on the page, from 1 to 1000. Defaults to 250.
params.tokenAddressAllowlist?`0x${string}`[]Restrict results to these token addresses; comparison is case-insensitive.
optionsReadExecutionOptionsCancellation controls for this page read. Fields as listed under getLetterOfCredit.

Returns

Promise<CollectionPage<CreditedToken>>

The page of credited tokens.

Signed authorizations

buildCancelAuthorization()

buildCancelAuthorization(params): Promise<CancelLOCAuthorizationDefinition>;

Builds the exact EIP-712 cancellation authorization a Beneficiary signs, without signing it. Use it to inspect the typed data or to sign it with your own tooling.

Parameters

ParameterTypeDescription
paramsBuildCancelLOCAuthorizationParamsThe LOC to authorize canceling, plus optional signer and nonce overrides.
params.expectedSigner?`0x${string}`Account that must sign the authorization. Defaults to the SDK’s signer.
params.idbigintPositive uint96 LOC id whose cancellation is authorized.
params.nonce?bigintExact uint256 nonce to bind. Defaults to the signer’s next onchain nonce when the definition or workflow is built; rebuild a long-held workflow if that nonce is consumed before signing.

Returns

Promise<CancelLOCAuthorizationDefinition>

The chain, contract, signer, nonce, and wallet-ready typed data.


buildCancelAuthorizationWorkflow()

buildCancelAuthorizationWorkflow(params): Promise<WalletOperationWorkflow>;

Builds a one-step workflow in which the Beneficiary signs a cancellation authorization. Pass the resulting signature as beneficiaryAuthorization in CancelLOCParams so another account can cancel the LOC before it expires.

Parameters

ParameterTypeDescription
paramsBuildCancelLOCAuthorizationParamsThe LOC to authorize canceling, plus optional signer and nonce overrides. Fields as listed under buildCancelAuthorization.

Returns

Promise<WalletOperationWorkflow>

A workflow whose single operation yields the signature.

Throws

WorkflowSignerChangedError If the SDK’s configured accountAddress and the connected wallet’s account disagree, or if the signer observed while executing differs from the one observed while building. Rebuild the workflow for the currently connected signer; re-executing the same workflow succeeds only if the original signer reconnects.


buildRedeemAuthorization()

buildRedeemAuthorization(params): Promise<RedeemLOCAuthorizationDefinition>;

Builds the exact EIP-712 redemption authorization a Beneficiary signs, without signing it. Use it to inspect the typed data or to sign it with your own tooling.

Parameters

ParameterTypeDescription
paramsBuildRedeemLOCAuthorizationParamsThe LOC, amount, and destination to authorize, plus optional signer and nonce overrides.
params.destinationAddress?`0x${string}`Required payout destination. Defaults to expectedSigner.
params.expectedSigner?`0x${string}`Account that must sign the authorization. Defaults to the SDK’s signer.
params.idbigintPositive uint96 LOC id whose redemption is authorized.
params.locCreditedAmountbigintThe LOC’s remaining credited amount when the authorization is built (remainingCredited.amount); the signature is valid only while the LOC still has this amount.
params.nonce?bigintExact uint256 nonce to bind. Defaults to the signer’s next onchain nonce when the definition or workflow is built; rebuild a long-held workflow if that nonce is consumed before signing.
params.redeemAmountbigintPositive uint256 credited-token amount the delegate may redeem.

Returns

Promise<RedeemLOCAuthorizationDefinition>

The chain, contract, signer, nonce, and wallet-ready typed data.


buildRedeemAuthorizationWorkflow()

buildRedeemAuthorizationWorkflow(params): Promise<WalletOperationWorkflow>;

Builds a one-step workflow in which the Beneficiary signs a redemption authorization. Pass the resulting signature as beneficiaryAuthorization on a redemption so another account can redeem to the destination the Beneficiary chose.

Parameters

ParameterTypeDescription
paramsBuildRedeemLOCAuthorizationParamsThe LOC, amount, and destination to authorize, plus optional signer and nonce overrides. Fields as listed under buildRedeemAuthorization.

Returns

Promise<WalletOperationWorkflow>

A workflow whose single operation yields the signature.

Example

const loc = await sdk.loc.getOutstandingLetterOfCredit({ id: 42n });
if (!loc) throw new Error('LOC 42 is no longer outstanding');
// Beneficiary's wallet: authorize a third party to redeem half to
// itself.
const destinationAddress = '0x2222222222222222222222222222222222222222';
const authWorkflow = await sdk.loc.buildRedeemAuthorizationWorkflow({
id: loc.reference.id,
redeemAmount: loc.remainingCredited.amount / 2n,
locCreditedAmount: loc.remainingCredited.amount,
destinationAddress,
});
console.log(authWorkflow.operations[0]?.authorization?.typedData);
const authorizationExecution = await authWorkflow.execute();
if (authorizationExecution.status !== 'executed') {
throw new Error(
`authorization preflight ended as ${authorizationExecution.status}`
);
}
const [authorization] = authorizationExecution.operations;
if (
authorization?.status !== WalletOperationStatus.Signed ||
!authorization.signature
) {
throw new Error('beneficiary declined to sign');
}
// Third party's wallet: the same id, amount, and destination the
// beneficiary signed, plus the signature.
const workflow = await sdk.loc.buildRedeemWorkflow({
redemptions: [
{
id: loc.reference.id,
amount: loc.remainingCredited.amount / 2n,
destinationAddress,
beneficiaryAuthorization: authorization.signature,
},
],
});
await workflow.execute();

Throws

WorkflowSignerChangedError If the SDK’s configured accountAddress and the connected wallet’s account disagree, or if the signer observed while executing differs from the one observed while building. Rebuild the workflow for the currently connected signer; re-executing the same workflow succeeds only if the original signer reconnects.


validateCancelAuthorization()

validateCancelAuthorization(params, signal?): Promise<ValidationIssue[]>;

Validates the inputs of a cancellation authorization before the SDK reads its nonce or asks the wallet to sign.

Parameters

ParameterTypeDescription
paramsPartial<BuildCancelLOCAuthorizationParams>The partial authorization parameters to check. Fields as listed under buildCancelAuthorization, each optional here.
signal?AbortSignalAborts the validation’s onchain reads; the call then rejects with the signal’s reason.

Returns

Promise<ValidationIssue[]>

The issues found. An empty array means every rule ran and passed; a rule whose required field is missing reports FieldRequired instead of being skipped. An infrastructure failure rejects rather than returning a partial list.

Throws

When validation itself cannot run: a typed SDK error passes through unchanged, a provider failure becomes ProviderConnectionError, any other failure becomes ContactSupportError, and an abort rejects with the signal’s reason.


validateRedeemAuthorization()

validateRedeemAuthorization(params, signal?): Promise<ValidationIssue[]>;

Validates the inputs of a redemption authorization before the SDK reads its nonce or asks the wallet to sign.

Parameters

ParameterTypeDescription
paramsPartial<BuildRedeemLOCAuthorizationParams>The partial authorization parameters to check. Fields as listed under buildRedeemAuthorization, each optional here.
signal?AbortSignalAborts the validation’s onchain reads; the call then rejects with the signal’s reason.

Returns

Promise<ValidationIssue[]>

The issues found. An empty array means every rule ran and passed; a rule whose required field is missing reports FieldRequired instead of being skipped. An infrastructure failure rejects rather than returning a partial list.

Throws

When validation itself cannot run: a typed SDK error passes through unchanged, a provider failure becomes ProviderConnectionError, any other failure becomes ContactSupportError, and an abort rejects with the signal’s reason.