IMPLEMENTATION / CODE WALKTHROUGH
Build the wallet Adapter Onli talks to.
Openfort is the Adapter we built. Follow it as the worked example for your provider: equip the platform, automatically provision each member’s wallet, move funds in and out, and preserve portable ownership.
Build the Adapter Onli talks to
You are a wallet provider. Build an Adapter that translates Onli’s wallet operations into your provider’s API and returns results Onli can verify. Openfort is the Adapter we built; use its implementation as the worked example for your provider.
Onli owns membership, action authorization, deposit accounting and payout orchestration. Your Adapter supplies wallet provisioning, permitted access, exact movements, observations and portability. Onli calls it through a Capability, selected by a Recipe.
Agree the complete operation contract
The following is a proposed provider-neutral teaching contract, not an exported interface or an Openfort SDK API. Agree its final schema and permission rules with the Onli integration owner before implementation. Each method needs explicit inputs, effects, result states and evidence.
interface PlatformWalletAdapter {
resolveMemberWallet(input: MemberProvisioning): Promise<WalletResult>
resolveTreasuryWallet(input: TreasuryProvisioning): Promise<WalletResult>
prepareTransfer(input: ExactIntent): Promise<PreparedTransfer>
submitMemberTransfer(input: AuthorizedMemberTransfer): Promise<Submission>
submitTreasuryMovement(input: AuthorizedTreasuryLeg): Promise<Submission>
observeOperation(input: OperationReference): Promise<Observation>
exportMemberWallet(input: AuthorizedExport): Promise<EncryptedArtifact>
}These names describe required operations. Types such as AuthorizedTreasuryLeg must carry the verified scope, stable operation reference, exact wallet bindings, network, asset and amount. Never accept a browser’s assertion that it is authorized. Report pending, completed, refused, failed or indeterminate according to the agreed evidence contract.
1. Provision the platform’s three wallets
Resolve or create separate backend wallets for Incoming, Master and Outgoing. Bind each to the platform identity, network and treasury role. Keep signing credentials server-side. An administrator operates these wallets through Onli-authorized requests; their personal wallet is a different account.
This orchestration example calls your Adapter three times. The role reference must remain stable across retries. Your implementation must serialize competing requests and persist the role binding before returning it.
for (const role of ['incoming', 'master', 'outgoing'] as const) {
await walletCapability.resolveTreasuryWallet({
platformRef: verifiedPlatform.ref,
role,
networkRef: recipe.networkRef,
provisioningRef: `${verifiedPlatform.ref}:${role}`,
})
}In the Openfort implementation, these are backend treasury wallets. This repository’s server/gateway.mjs reads their canonical bindings from the Appliance. It is not the provider’s wallet-creation implementation. Your server Adapter must implement creation or resolution behind that contract and verify the returned account type, identity and network.
2. Automatically give each member a wallet
After Onli authenticates the member and establishes membership readiness, it requests that member’s wallet. Resolve the existing binding first. Create only when permitted and absent, using a stable provisioning reference. Later sign-ins open the same wallet.
The server-side Adapter pattern below uses illustrative provider-port methods. They stand for your provider’s verified API, not Openfort SDK methods. The binding store needs a unique platform/member/network key and a durable provisioning operation.
async function resolveMemberWallet(input: MemberProvisioning) {
await authority.requireMemberProvisioning(input)
return bindings.withProvisioningLock(input.provisioningRef, async () => {
const existing = await bindings.readMember(input)
if (existing) return verifyCanonicalWallet(existing, input)
const operation = await operations.resumeOrCreate(input.provisioningRef)
const account = await provider.resolveOrCreateEmbeddedAccount({
ownerRef: input.memberRef,
networkRef: input.networkRef,
operationRef: operation.ref,
})
const wallet = verifyCanonicalWallet(account, input)
await bindings.commitMember(input, wallet, operation)
return wallet
})
}If the provider response is lost, resume the original operation and find its account before creating again. If the provider cannot deduplicate or resolve an uncertain creation, return indeterminate and reconcile through an agreed process. A local lock alone cannot guarantee exactly-once creation across servers.
Follow the existing client handoff in journey_open_member_wallet.ts and workflow_resolve_member_readiness.ts. They read readiness, open an issued wallet or call ensureMemberWallet. tool_capability_member.ts reaches the Appliance through its Adapter. That is the caller your provider provisioning must serve, rather than a browser creating an unrelated wallet.
3. Implement one exact backend movement
The same movement contract supports Incoming → Master, Master → Outgoing and Outgoing → approved recipient. Onli selects and authorizes the leg. Your Adapter validates that scope, translates the exact leg into a provider transaction and returns its submission reference.
This server-side pattern is contract pseudocode. It deliberately leaves provider transaction construction and signing inside the private provider port.
async function submitTreasuryMovement(leg: AuthorizedTreasuryLeg) {
await authority.verifyExactLeg(leg)
const operation = await operations.bindExactIntent(leg.operationRef, leg)
if (operation.submitted || operation.uncertain)
return observeOperation(operation.reference)
const source = await bindings.requireTreasurySource(leg)
const destination = await bindings.requireApprovedDestination(leg)
const prepared = await provider.prepareExactMovement({
source, destination, asset: leg.asset, units: leg.units,
networkRef: leg.networkRef,
})
await operations.recordBeforeSubmission(operation, prepared)
return provider.submitOrResolve(prepared, operation.reference)
}The operation store must serialize submission and reject reuse of an operation reference with changed intent. submitOrResolve is a required contract behavior, not permission to blindly retry. Preserve uncertainty after a possible effect and observe the original transaction. Use exact integer asset units, not floating-point money.
Onli verifies the member’s arrival at Incoming before requesting settlement to Master. For payouts, its Workflow checks reserved available funds and requests Master → Outgoing only when needed. Your Adapter does not decide to rebalance or credit the member. Completion requires matching evidence and Onli’s accounting result, not merely a provider acknowledgment.
4. Bind all operations through the Recipe
The existing src/recipe/wallet-provider.ts selects openfort/v1 for recovered wallet sessions. Full lifecycle provisioning and treasury access need their own agreed bindings. This illustrative expanded arrangement shows what must be selected; it is not a configuration this client accepts today.
const platformWalletRecipe = {
version: 'platform-wallet/illustrative-v1',
bindings: {
memberProvisioning: 'provider/member-provisioning/v1',
treasuryProvisioning: 'provider/treasury-provisioning/v1',
memberSession: 'provider/member-session/v1',
treasuryMovement: 'provider/treasury-movement/v1',
observation: 'provider/observation/v1',
portability: 'provider/member-portability/v1',
},
networkRef: approvedNetworkRef,
treasuryRefs: approvedTreasuryRefs,
policyRef: approvedWalletPolicyRef,
}The Recipe supplies approved bindings and configuration. The request supplies the member, exact intent and operation identity. Live authority and secrets belong in neither static configuration nor AI-selected provider names. Preserve the selected versions with each operation so recovery cannot silently switch providers or networks.
5. Make the member’s wallet portable
Portability means using the same wallet and address beyond the platform. Implement authorized export and recovery for that wallet’s custody model, not creation of a replacement wallet. If the account is a smart-contract wallet, private-key export may not preserve control or its address; declare that limitation and agree a supported migration or recovery contract.
- Verify the member and issued wallet identity, then obtain the export authority required by the contract.
- Use scoped provider recovery to obtain the permitted export material. Keep key material out of logs and persistent plaintext storage.
- Encrypt the backup in the agreed format and deliver the artifact with wallet identity and supported network metadata.
- Require the configured OnliYou behavior approval before releasing the file’s decryption access.
- Import into a compatible external wallet and verify that its address matches the issued wallet.
- End the provider session and clear temporary key access. Explain that an imported key grants control outside the platform.
Our Openfort example composes journey_export_wallet_backup.ts, workflow_create_member_backup.ts and the private Openfort export operation. WalletBackupDialog.tsx opens the encrypted artifact after OnliYou approval and offers import into Phantom. This flow preserves the member wallet; it does not export platform treasury authority.
The encrypted file still depends on Onli’s authorization and key-release service to open it through this flow. Once a compatible wallet imports the key, its access no longer depends on the Onli interface. That does not transfer Onli membership, account credits, smart-wallet policies or Oracle history. Verify external address preservation with a test wallet before claiming portability for your provider.
Prove the complete Adapter contract
Before release, demonstrate these outcomes with test accounts and provider evidence:
- Platform setup returns three distinct, correctly bound treasury wallets; retries return the same bindings.
- Eligible member sign-in creates one wallet automatically; repeat sign-in and interrupted provisioning recover that same wallet.
- The member → Incoming transfer and Incoming → Master settlement produce matching references and the Appliance’s deposit receipt.
- Payout works with sufficient Outgoing funds and with authorized Master funding; unresolved submissions never create duplicate payments.
- Unauthorized or changed requests are refused at the provider boundary, including cross-member and cross-platform requests.
- An approved encrypted export opens only under its required authority and imports as the same supported wallet address.
- Transport and persisted sensitive data are encrypted, secrets remain server-side, and recovery and cleanup failure states are tested.
The browser repository demonstrates member access, transfer execution and encrypted export. Appliance-owned provisioning and treasury settlement must be verified through their server contracts. Local test doubles cannot establish those live outcomes.
This is the structure
- Journey: Own one requested outcome, such as opening a member wallet, depositing, paying a recipient or exporting a wallet.
- Workflow: Compose the responsibilities needed for that outcome. A payout Workflow resolves treasury accounts, checks authority and funds, rebalances when needed, executes and reconciles.
- Tools: Perform each bounded check, movement or observation.
- Recipe: Supply the provider binding, network, treasury references and policy configuration.
- Resources: What the work identifies, uses, evaluates, changes, transmits, references or produces. Each has independently addressable Identity, Content and Context.
Identity: who or what it is. Content: what it contains. Context: what matters about its current use. Keep observed state separate from required state, and reference authoritative facts rather than duplicating them into Context.
For example, a wallet is a Resource: its identity identifies the wallet; its content contains its authoritative wallet data; its context describes its use in this deposit or payout. A request, reservation and receipt are also Resources. Persistence is a requirement of particular Resources, not the definition of Resource.
This structure describes the Onli architecture your Adapter serves. The Appliance owns the Journey and its business rules. You implement the provider-backed operations beneath the Capability. The examples show what calls your code and what it must return.
Start with the outcome, then place each responsibility in this structure. The examples below apply it to depositing from an Owner’s wallet into the Appliance and paying from the Appliance to an approved recipient.
The purpose of the Openfort integration is a complete wallet on/off ramp for an Onli platform: provision its treasury wallets, automatically give every member their own wallet, and make that member wallet portable beyond the ecosystem.
You are a wallet provider implementing an Adapter for Onli. Follow both wallet types, the deposit and payout handoffs, and secure portability to see the full contract your provider must supply.
These excerpts show how the wallet implementation fits together. They are selected excerpts, not standalone programs. Each source path identifies where the complete code lives.
Start with the send example and the authentication sequence. Here you will trace that same request through the implementation. A Surface means the user interface; a binding is the selected version; continuity is the saved operation state used after an interruption.
Read the code by the outcome it delivers
The product is the complete platform and member wallet lifecycle. The engineering concepts explain how we organize that implementation: a Journey owns an outcome, Workflows coordinate responsibilities, Tools perform bounded operations, and the Recipe selects the provider configuration.
| What the platform or member needs | Where to follow the implementation | How it fits |
|---|---|---|
| Sign in and automatically open a member wallet | src/App.tsx → journey_open_member_wallet.ts → workflow_resolve_member_readiness.ts | The authenticated session starts onboarding. The Workflow reads readiness and either opens the existing wallet or requests wallet creation through the Capability. Provider provisioning happens behind that contract. |
| Operate the platform treasury | workflow_read_wallet_context.ts and server/gateway.mjs | The UI reads the Incoming, Master and Outgoing bindings. The Appliance owns treasury provisioning, authority and settlement; the provider supplies backend wallet operations. |
| Deposit from a member wallet to Incoming | workflow_review_transfer.ts → journey_send_transfer.ts → adapter_openfort.ts | Resolve the approved Incoming target, review the exact transfer and submit through the member’s embedded wallet. Appliance deposit settlement follows the verified arrival. |
| Pay an approved recipient | The deposit and payout sequences below | These define the Appliance-to-provider movement contracts. Browser treasury views are not transfer endpoints; backend movements require the Appliance’s authorized Journey. |
| Take the same member wallet elsewhere | journey_export_wallet_backup.ts → workflow_create_member_backup.ts → adapter_openfort.ts | Recover and export the permitted wallet key through the provider, encrypt the backup and deliver the file. Opening it follows the Onli authorization flow. |
Automatic member wallet creation follows readiness
This excerpt from src/workflow/workflow_resolve_member_readiness.ts shows the provider handoff. The preceding readiness checks decide whether creation is permitted; the Capability performs the request.
const wallet = await (readiness.member_wallet
? readMemberWallet(session)
: ensureMemberWallet(session))
return isCurrent() ? { wallet, readiness, reason: '' } : nullPortability is an outcome of its own
This excerpt from src/journey/journey_export_wallet_backup.ts composes backup creation and file delivery. The Workflow handles scoped provider access and encryption; the Journey delivers the requested encrypted wallet artifact.
const file = await workflow_create_member_backup(
context.session, context.wallet, context.isCurrent,
)
if (!context.isCurrent()) throw new Error('Session changed')
return tool_capability_deliver_file(
file, `species-wallet-${context.wallet.address}.encrypted.json`,
)For your provider, implement the operations behind these Capability contracts and bind them with a Recipe. Preserve the platform’s three treasury roles, automatic member provisioning and portable wallet identity across the whole lifecycle.
Two wallet types, two responsibilities
An Onli Appliance needs a personal wallet for each Owner and backend wallets for its treasury. They use different signing paths.
| Owner wallet | Appliance treasury | |
|---|---|---|
| Openfort implementation | Embedded wallet | Backend wallets: Incoming, Master and Outgoing |
| Who requests an action? | The authenticated Owner | An authorized administrator or Appliance Journey |
| Where does signing happen? | Through the embedded-wallet access and signing contract | Through the Appliance’s server-side backend-wallet Adapter |
| What does the browser receive? | Its permitted wallet access and observations | Account observations, operation references and receipts; no treasury signing credentials |
Choosing Admin changes the available Surface. It never turns the administrator’s personal wallet into a treasury signer.
The member’s wallet goes beyond the platform
A member receives their own wallet automatically during onboarding. That wallet is usable inside the platform and portable outside it. Exporting the wallet preserves its address and ownership; it does not create a new wallet or move the funds.
The Openfort example provides Download encrypted wallet and Open encrypted file. The member downloads the encrypted artifact, selects it, approves opening in OnliYou, and can copy the released key for import into Phantom. Key access is temporary and the file can be locked again.
A provider Adapter must define the export, encryption, identity verification, recovery and cleanup contracts. Keep this separate from treasury administration: exporting the member’s wallet does not grant control over Incoming, Master or Outgoing.
Implementation references: member backup Workflow, encrypted export Journey and OnliYou-approved file opening.
User wallet → Incoming: deposit into the Appliance
The Owner’s requested outcome is deposit funds into the Appliance. It crosses two signing paths: the Owner’s embedded wallet sends to Incoming; the Appliance’s backend wallet settles the received funds into Master.
Owner requests a deposit
→ resolve the Owner’s wallet and the Appliance’s Incoming target
→ review the exact amount, destination, network and fee
→ confirm and execute the embedded-wallet send
→ verify the exact arrival at Incoming
→ settle Incoming → Master through the backend-wallet Adapter
→ complete the deposit accounting and return its receipt| Unit | Deposit responsibility |
|---|---|
| Journey | Deposit into the Appliance; completion includes the settled account result. |
| Workflows | Resolve and review the deposit, execute the Owner’s send, verify arrival, then settle and reconcile the deposit. |
| Tools | Read the approved target, validate the transfer, estimate fees, submit one transfer, verify arrival, move one treasury leg and establish the accounting result. |
| Recipe | Provider bindings for both wallet types, network, denomination, Incoming/Master references and approval/finality rules. |
| Resources | Owner wallet, deposit intent and reference, exact transfer evidence, treasury movement and deposit receipt. |
Your Adapter’s part in the deposit
The embedded-wallet Adapter signs the approved Owner → Incoming transfer. The backend-wallet Adapter executes the specified Incoming → Master movement when the Appliance calls it. Both return evidence; the Appliance verifies arrival, owns accounting and decides whether the deposit outcome is complete.
What already exists in the wallet
In Send, select Appliance Incoming account. The wallet reads the target from the signed-in Owner’s readiness response and accepts USDC for that route. Review checks the target again, so a changed or unavailable destination requires a new review. The user reviews the amount, network and fee, then confirms the embedded-wallet transfer.
These excerpts are simplified from the target-resolution Workflow and the transfer-review Workflow. The complete source includes types and surrounding guards.
// Existing browser implementation: resolve the Appliance target.
// Readiness belongs to the signed-in Owner; it supplies the approved target.
export async function workflow_resolve_incoming_target(session, wallet) {
return incomingAddress(await readMemberReadiness(session), wallet, session.onli_id);
}
// Existing review Workflow: re-read the destination before making a quote.
if (options.destination === 'incoming') {
const latest = await options.loadIncoming();
if (!options.isCurrent()) return null;
if (!latest || latest.toLowerCase() !== options.recipient.toLowerCase())
throw new WalletError('The Incoming address changed or could not be checked. Check the destination and review again.');
if (options.asset !== 'USDC')
throw new WalletError('The Appliance Incoming account receives USDC.');
}
const quote = await workflow_prepare_transfer(
options.wallet, options.asset, options.recipient, options.amount,
);The confirmed quote enters journey_send_transfer. Its operation Resource preserves the exact intent and stable identity before submission; reconciliation observes the resulting transaction. This is the existing wallet-send portion of the deposit outcome.
Where the Appliance takes over
The Appliance must correlate the arrival to the deposit request and registered Owner wallet, verify the token, network, destination, amount and required finality, and refuse reused or mismatched evidence. A transaction hash or a higher Incoming balance alone does not establish which Owner’s deposit settled.
Only then does the deposit settlement Workflow use the backend-wallet Adapter for Incoming → Master and finish the corresponding account credit. It preserves stable references and reconciles an uncertain sweep before another attempt. The Owner’s wallet signer does not sign the treasury leg.
For 10 test USDC, the wallet send may be confirmed while Appliance settlement is still pending. Show those as separate observations. Do not report deposit complete until the Appliance’s verified settlement and accounting receipt establish the full outcome.
The current browser route supports sending to Incoming. Connecting that transfer to the Appliance’s deposit registration, verification and settlement contract is still required for an end-to-end deposit Journey; the browser send alone does not credit the Appliance account.
Two treasury Journeys
Settle deposit owns the outcome of a verified deposit becoming settled in the Appliance. Pay recipient owns the outcome of an approved recipient receiving the permitted payment.
Rebalancing is a step inside the payout Workflow. The administrator requests a payout; the Workflow checks the funds available for that payout in Outgoing and funds it from Master only when required. The administrator does not orchestrate the internal wallet movements.
Place each responsibility deliberately
| Unit | Responsibility | Why it belongs here |
|---|---|---|
| Journey | Pay an approved recipient | Owns one caller-visible outcome and coordinates the required Workflows. |
| Workflow | Resolve payout context, reserve funds, rebalance when needed, submit and reconcile | Chooses the Tools required by the current Resource context to accomplish its responsibility. |
| Tool | Verify authority, reserve funds, read funds, move one leg, submit one payout or observe evidence | Performs one bounded responsibility under an explicit contract. |
| Recipe | Provider binding, network, denomination, account references and policy references | Supplies the reusable arrangement and configuration; live decisions stay with the Journey or Workflow. |
| Resource | Approved payout intent, reservation, operation and settlement evidence | Provides independently addressable Identity, Content and Context for what the work uses or produces. |
Your Adapter’s part in the payout
Implement one authorized backend movement and its observation/reconciliation contract. Onli’s Workflow supplies the selected source, destination, amount and stable leg identity. The same provider operation can serve Master → Outgoing funding and Outgoing → approved recipient payment. The Workflow chooses the legs; your Adapter translates them to Openfort and returns the actual provider results.
A payout, with and without rebalancing
Suppose the payout is 10 test USDC. If Outgoing has 10 available for this operation, the Workflow proceeds to payment. If it has 4, the Workflow requests the permitted 6 from Master, verifies that funding settled, then pays 10. Available means funds usable by this payout after reservations and policy checks, not simply the balance displayed on screen.
How to assemble it
The following pseudocode defines the required Appliance-side architecture. The existing browser client implements the Owner’s embedded-wallet send; this example is the backend contract to implement for admin payout execution. These function names are explanatory and are not callable exports from the client.
// Architectural example: Appliance-side contracts to implement.
// These names are explanatory; they are not exported by this client.
async function journey_pay_recipient(request, recipe) {
const payout = await workflow_resolve_approved_payout(request, recipe);
return workflow_execute_payout(payout, recipe);
}
async function workflow_execute_payout(payout, recipe) {
// Recover the same durable operation before deciding on another effect.
const operation = await tool_resolve_payout_operation(payout);
if (operation.hasUnresolvedEffect || operation.isComplete)
return workflow_reconcile_payout(operation, recipe);
await tool_verify_payout_authority(payout, recipe.policyRef);
const reservation = await tool_reserve_payout_funds(operation);
const treasury = await tool_read_reserved_treasury_context(reservation);
const shortfall = Math.max(0, payout.amount - treasury.outgoingForThisPayout);
if (shortfall > 0) {
await tool_verify_rebalancing_limits(reservation, shortfall, recipe);
const funding = await tool_move_backend_funds({
operationId: operation.fundingId, // stable across retries
source: recipe.masterRef,
destination: recipe.outgoingRef,
amount: shortfall,
authority: reservation.authority,
});
if (!funding.settlementVerified)
return workflow_reconcile_payout(operation, recipe);
}
const payment = await tool_submit_backend_payout({
operationId: operation.paymentId,
source: recipe.outgoingRef,
recipientRef: payout.approvedRecipientRef,
amount: payout.amount,
authority: reservation.authority,
});
// Submission is pending. Observe evidence, finish accounting,
// and return completion only when the exact payout is settled.
return workflow_reconcile_payout(operation, recipe);
}Contracts before composition
Prove each Tool first: its required authority, exact inputs, effects, evidence and failure states. Then compose the payout Workflow and the Journey. The backend-wallet Capability reaches the selected server-side Openfort Adapter; the browser receives an operation reference and receipt, never treasury signing credentials.
Approval and interrupted effects
Bind approval to the exact payout, recipient, amount and network. The policy must cover any required internal funding; if it does not, obtain the additional required approval before that leg. Signing in or choosing Admin is not movement authority.
Persist the reservation, approved intent and stable leg identifiers before effects. On a timeout, preserve the unresolved operation and reconcile it. Do not create a new movement reference or release reserved funds while the outcome is unknown. A provider acknowledgement is pending; only verified settlement and completed accounting establish the Journey’s outcome.
1. Select Openfort with the Recipe
Provider selection is a Recipe responsibility. The versioned definition selects openfort/v1 for the recovered-wallet-session Capability. It contains no execution or secret values. The external Openfort service is reached through the selected Adapter.
src/recipe/wallet-provider.ts
export type WalletProviderRecipe = {
version: 'wallet-provider/v1'
adapter: 'openfort/v1'
capability: 'recovered-wallet-session/v1'
}
export const walletProviderRecipe: Readonly<WalletProviderRecipe> = Object.freeze({
version: 'wallet-provider/v1',
adapter: 'openfort/v1',
capability: 'recovered-wallet-session/v1',
})The separate wallet-network/v1 Recipe defines mainnet/Sepolia RPC, token and explorer settings. wallet-polling/v1 holds observation intervals and quote lifetime. The transfer records its selected bindings before any effect; recovery cannot silently substitute another selection.
2. Define the Resources and contracts
The wallet’s identity comes from Species. The client verifies the account reference, address, custody/type and any reported chain. A transfer Resource preserves operation identity, exact intent, bindings, hash and evidence. A quote contains the exact transaction and its fee/time limits.
The session interface names the operations Workflows need. It exposes no raw provider handle. Openfort implements this interface privately.
src/contracts/wallet-session.ts
import type { Wallet, WalletAccess } from './species.ts'
import type { Quote } from './wallet.ts'
import type { TransferConfirmation } from './transfer-confirmation.ts'
export type WalletSDK = {
waitForInitialization(): Promise<unknown>
recover(
account: string,
encryptionSession: string,
): Promise<{ id: string; address: string; chainId?: number; accountType?: string }>
logout(exportCompleted: boolean): Promise<unknown>
}
export type ExportSDK = WalletSDK & { exportPrivateKey(): Promise<string> }
/** Canonical scoped operations; provider handles remain private. */
export type RecoveredWalletSession = ExportSDK & {
sendTransfer(
wallet: Wallet,
quote: Quote,
check: () => void,
broadcastStarted: () => void,
confirmation: TransferConfirmation,
): Promise<string>
}
export type WalletSessionFactory = (
access: WalletAccess,
getAccessToken: () => Promise<string>,
) => RecoveredWalletSession3. Prove the small operations
| Responsibility | Source owner | Used for |
|---|---|---|
| Address, units and quote checks | tool_validate_transfer.ts | Prepare and execution |
| Wallet identity comparison | tool_compare_wallet_identity.ts | Access renewal and recovery |
| Exact confirmation check | tool_verify_transfer_confirmation.ts | Journey, execution and submission boundary |
| Operation creation | tool_create_transfer_operation.ts | Durable continuity before broadcast |
| Transfer evidence verification | tool_verify_transfer_evidence.ts | Completion/failure observation |
The confirmation Tool verifies the reviewed wallet, chain, quote time and exact transaction. Reusing this check at the effect boundary prevents a valid review from authorizing an edited payload.
src/tool/tool_verify_transfer_confirmation.ts
export function tool_verify_transfer_confirmation(
wallet: Wallet,
quote: Quote,
confirmation: TransferConfirmation | undefined,
now = Date.now(),
) {
assertQuote(wallet, quote, now)
if (
!confirmation ||
confirmation.kind !== 'explicit_transfer_confirmation' ||
!confirmation.operationId ||
confirmation.walletAddress.toLowerCase() !== wallet.address.toLowerCase() ||
confirmation.chainId !== wallet.chain_id ||
confirmation.quoteCreatedAt !== quote.createdAt ||
!Number.isFinite(confirmation.confirmedAt) ||
confirmation.confirmedAt < quote.createdAt ||
confirmation.confirmedAt > now ||
JSON.stringify(confirmation.transaction) !== JSON.stringify(quote.transaction)
)
throw new WalletError('Explicit confirmation of this exact transfer is required.')
}4. Compose reusable Workflows
Review selects the destination and checks existing unresolved work. Preparation validates intent, reads balances through the chain Capability and estimates an immutable transaction. Recovery owns the complete access-renewal, initialize, recover, identity-check, action and teardown lifecycle.
Execution composes recovery with send-specific checks. It does not import Openfort or obtain a raw provider. withWalletSDK is the wallet-session Capability entry point; runWalletAction aliases the shared recovery Workflow.
src/workflow/workflow_execute_transfer.ts
export async function workflow_execute_transfer(
session: Session,
wallet: Wallet,
quote: Quote,
isCurrent: () => boolean,
broadcastStarted: () => void,
confirmation: TransferConfirmation,
) {
tool_verify_transfer_confirmation(wallet, quote, confirmation)
return withWalletSDK((createSDK) =>
runWalletAction({
wallet,
isCurrent,
createSDK,
getAccess: () => readWalletAccess(session),
async action(sdk, check) {
const balance = await readBalances(wallet)
check()
assertQuote(wallet, quote)
if (
balance.eth < quote.fee + (quote.asset === 'ETH' ? quote.units : 0n) ||
(quote.asset === 'USDC' && balance.usdc < quote.units)
)
throw new WalletError('Your balance changed. Review the transfer again.')
return sdk.sendTransfer(wallet, quote, check, broadcastStarted, confirmation)
},
}),
)
}Member backup export reuses the same recovery lifecycle through workflow_export_wallet_key. We built recovery once, rather than separate Openfort login/recovery implementations for send and export. Context controls the scoped action.
5. Connect the Capability to the Adapter
The Capability resolves the Recipe’s Adapter binding, owns coordination across browser tabs on the same site and returns only canonical scoped operations. The provider registry is private to this owner.
src/capability/tool_capability_wallet_session.ts
export function createWalletSessionCapability(recipe: WalletProviderRecipe = walletProviderRecipe) {
const adapters = { 'openfort/v1': adapter_openfort_factory }
const selected = adapters[recipe.adapter]
if (!selected || recipe.version !== 'wallet-provider/v1' || recipe.capability !== 'recovered-wallet-session/v1')
throw new WalletOperationUnavailable('The selected wallet provider binding is unavailable.')The Adapter alone imports the Openfort SDK and translates the canonical recovery call into its automatic recovery API. Its storage is isolated per operation; the access token callback renews only the permitted handoff.
src/adapter/adapter_openfort.ts
export async function adapter_openfort_factory(cleanup: WalletCleanupGuard): Promise<WalletSessionFactory> {
const { Openfort, RecoveryMethod, ThirdPartyOAuthProvider } = await import('@openfort/openfort-js')
return (access: WalletAccess, getAccessToken: () => Promise<string>) => {
const storage = new WalletSessionStorage()
const sdk = new Openfort({
baseConfiguration: { publishableKey: access.publishable_key },
shieldConfiguration: { shieldPublishableKey: access.shield_publishable_key },
thirdPartyAuth: { provider: ThirdPartyOAuthProvider.CUSTOM, getAccessToken },
overrides: { storage },
})
return {
waitForInitialization: () => sdk.waitForInitialization(),
recover: (account: string, encryptionSession: string) =>
sdk.embeddedWallet.recover({
account,
recoveryParams: { recoveryMethod: RecoveryMethod.AUTOMATIC, encryptionSession },
}),The excerpt ends before export, send and logout methods. Send obtains the raw Ethereum provider privately, then calls the EVM submission Adapter. Its checks run again immediately before the effect.
src/adapter/adapter_evm_submit.ts
check()
tool_verify_transfer_confirmation(wallet, quote, confirmation)
assertQuote(wallet, quote)
const [chain, accounts] = await Promise.all([
provider.request({ method: 'eth_chainId' }),
provider.request({ method: 'eth_accounts' }),
])
check()
tool_verify_transfer_confirmation(wallet, quote, confirmation)
assertQuote(wallet, quote)
if (
typeof chain !== 'string' ||
BigInt(chain) !== BigInt(wallet.chain_id) ||
!Array.isArray(accounts) ||
accounts.length !== 1 ||
String(accounts[0]).toLowerCase() !== wallet.address.toLowerCase()
)
throw new WalletError('Signing wallet or network changed. Review the transfer again.')
// After this point an error may mean broadcast succeeded. Never automatically retry.
broadcastStarted()
const hash = await provider.request({ method: 'eth_sendTransaction', params: [quote.transaction] })
if (typeof hash !== 'string' || !/^0x[\da-fA-F]{64}$/.test(hash)) throw new Error('Unknown transaction outcome')
return hash
}broadcastStarted() persists continuity through the Journey’s callback. If that write fails, eth_sendTransaction is never called. Once it starts, an exception can mean the effect happened; uncertainty is preserved.
Logout and isolated storage disposal happen before releasing the origin lock. Failed cleanup activates a reload guard. This prevents a retained SDK session from starting another protected action after its scope ends.
6. See how the Journey calls your work
The conceptual outcome is journey_send_funds. This implementation is journey_send_transfer. The user interface supplies the reviewed quote, explicit confirmation and current-context callback; it presents results rather than sequencing provider calls.
src/usePersonalWallet.ts
async function confirm() {
if (!wallet || !session || !quote || lock.current || reloadRequired || ['pending','unknown'].includes(submission?.status || '')) return
lock.current = true; setBusy(true); setError('')
const current = generation.current, requested = quote, key = storageKey
try {
const result = await journey_send_transfer({ confirmation: createTransferConfirmation(requested), session, wallet, quote: requested, key, storage: localStorage, isCurrent: () => current === generation.current, send: sendWallet, changed: next => {The Journey creates the operation, acquires its lock and checks for prior work. A replay with the same ID returns the existing result; a different unresolved operation blocks replacement. This excerpt shows how it composes the execution Workflow through send and supplies the durability callback.
src/journey/journey_send_transfer.ts
const hash = await send(
session,
wallet,
quote,
isCurrent,
() => {
// Durability is required before the effect boundary; failure stops signing.
storage.setItem(key, JSON.stringify(operation))
started = true
changed(operation)
},
options.confirmation,
)
if (!/^0x[\da-fA-F]{64}$/.test(hash)) throw new Error('Invalid submission evidence')
operation.hash = hash
operation.evidence = [{ kind: 'broadcast-reference', reference: hash, observedAt: Date.now() }]
const pending: Submission = {
...operation,
hash,
status: 'pending',
state: 'pending',
evidence: [{ kind: 'broadcast-reference', reference: hash, observedAt: Date.now() }],
}
storage.setItem(key, JSON.stringify(pending))
changed(pending)
return {
state: 'pending',
operationId: operation.operationId!,
duty: operation.duty!,
evidence: pending.evidence!,
}The catch branch returns indeterminate after the broadcast boundary. It retains the pre-broadcast record and any known hash. It does not erase the guard or automatically submit a second transaction.
7. Establish the outcome
A hash is acknowledgment, not completion. workflow_reconcile_transfer calls the observation Capability. That Capability checks the original Recipe/RPC/token/wallet binding, reads the transaction and receipt, then invokes the evidence Tool.
The Tool checks hash, sender, target, input, value, chain, matching block and receipt status. USDC additionally needs the exact token Transfer event, recipient and units. A valid failed receipt establishes failure; unavailable observations leave the operation unresolved.
src/workflow/workflow_reconcile_transfer.ts
const next: Submission = {
...saved,
hash: options.operation.hash,
status: result.status,
state: result.status === 'confirmed' ? 'completed' : 'failed',
duty: undefined,
evidence: [...(saved.evidence ?? []), ...result.evidence],
}
options.storage.setItem(options.key, JSON.stringify(next))
return next
})
}Our declared completion contract is transfer-inclusion/v1: matching current inclusion. It does not claim irreversible finality, an Onli-side change or an Oracle update. Those need their own contracts and proof.