# Install MCP Source: https://build.onswig.com/build-with-ai ## Introduction MCP gives an AI assistant tools and context for Swig. Use Docs MCP to find current integration guidance, or run Wallet MCP locally when the assistant needs to inspect wallets and prepare operations. ## Examples ### Connect Docs MCP Add the hosted documentation server to your assistant. For Claude Code: ```bash theme={null} claude mcp add --transport http swig-docs https://build.onswig.com/mcp ``` ### Build Wallet MCP Install Bun and Node.js, then build the wallet tool server. ```bash theme={null} git clone https://github.com/anagrambuild/swig-ts.git cd swig-ts bun install bun run build ``` ### Connect Wallet MCP Add this entry to your MCP client, using the absolute path to the built checkout. ```json theme={null} { "mcpServers": { "swig-wallet": { "command": "node", "args": ["/absolute/path/to/swig-ts/packages/mcp-server/dist/index.js"] } } } ``` ### Verify the connection Open the assistant’s tools list, then ask it to locate the wallet-creation guide. ```text theme={null} Find the Developer SDK wallet-creation guide. Show the inputs and supported signing options. ``` ## Input | Server | Input | | :- | :- | | Docs MCP | Remote HTTP URL `https://build.onswig.com/mcp`; no API key. | | Wallet MCP | Local built entrypoint and the intended network’s RPC configuration. Start with [Wallet MCP setup](/tutorials/mcp). | | Wallet authority | Grant the agent only the [permissions](/developer-sdk/permissions) needed for its task; review prepared actions before signing. | ## Output | Connection | Expected result | | :- | :- | | Docs MCP | Documentation search tools are available in the assistant. | | Wallet MCP | `configure_rpc` and `fetch_swig_wallet` appear; configure the network before wallet calls. | | Text-only integration | [llms.txt](https://build.onswig.com/llms.txt) lists pages; [llms-full.txt](https://build.onswig.com/llms-full.txt) contains the combined documentation. | ## Errors | Error | Meaning | | :- | :- | | Server not found | The local entrypoint path is incorrect or the package has not been built. | | Tools absent | The client has not reconnected after the server configuration changed. | | RPC or wallet query fails | The network/RPC setting is missing or does not match the wallet. | # Role Source: https://build.onswig.com/developer-sdk/add-roles-and-permissions ## Introduction A role combines an authority with the actions it may perform. Use a separate role for each person, service, or participant set that needs wallet access. This lets an administrator grant a spending budget without sharing root access. Adding a role prepares a transaction. The existing administrator signs it; the new authority becomes usable after confirmation. ## SDK examples ### Add a scoped SOL-transfer role This role can invoke the System Program and spend a total of 1,000,000 lamports. Both actions are required: program access and asset spending are checked separately. Each successful transfer reduces the remaining one-time budget. Use the clients from [Client setup](/developer-sdk/integration-paths). `signAndSubmit` / `sign_and_submit` is your application's signing, submission, and confirmation helper, not an SDK method. Rust address inputs are `Pubkey` values. ```typescript TypeScript theme={null} import { SystemProgram } from '@solana/web3.js'; const wallet = swig.wallets.use(swigConfigAddress, { requesterAuthority: { ed25519: { publicKey: adminPublicKey }, }, }); const prepared = await wallet.roles.add({ feePayer, authority: { ed25519: { publicKey: newRolePublicKey }, }, actions: [ { type: 'program', programId: SystemProgram.programId.toBase58(), }, { type: 'solLimit', amount: 1_000_000n }, ], }); await signAndSubmit(prepared); ``` ```python Python theme={null} from solders.system_program import ID as SYSTEM_PROGRAM_ID from swig_developer_sdk import ProgramAction, SolLimitAction wallet = swig.wallets.use( swig_config_address, requester_authority={ "ed25519": {"publicKey": admin_public_key} }, ) prepared = await wallet.roles.add( fee_payer=fee_payer, authority={ "ed25519": {"publicKey": new_role_public_key} }, actions=( ProgramAction(program_id=str(SYSTEM_PROGRAM_ID)), SolLimitAction(amount=1_000_000), ), ) await sign_and_submit(prepared) ``` ```rust Rust theme={null} use solana_pubkey::pubkey; use swig_developer_sdk::{PrepareAddRoleArgs, WalletAuthority, WalletPermission}; let prepared = wallet .prepare_add_role(PrepareAddRoleArgs { swig_config_address, fee_payer, requester_authority: WalletAuthority::Ed25519 { public_key: admin_public_key, }, authority: WalletAuthority::Ed25519 { public_key: new_role_public_key, }, actions: vec![ WalletPermission::Program { program_id: pubkey!("11111111111111111111111111111111"), }, WalletPermission::SolLimit { amount: 1_000_000 }, ], }) .await?; ``` ### Confirm the role Use the returned role data to display existing authority and allowance. Rust decodes permissions into typed variants. ```typescript TypeScript theme={null} const { swigConfigAddress, walletAddress, roles } = await wallet.listRoles(); for (const role of roles) { console.log(role.roleId, role.authorityType, role.authorityValue); for (const action of role.actions) { console.log(action.actionIndex, action.actionCode, action.actionData); } } ``` ```python Python theme={null} result = await wallet.list_roles() for role in result.roles: print(role.role_id, role.authority_type, role.authority_value) for action in role.actions: print(action.action_index, action.action_code, action.action_data) ``` ```rust Rust theme={null} use swig_developer_sdk::SwigRolePermission; let result = wallet.list_roles(&swig_config_address).await?; for role in &result.roles { for action in &role.actions { if let SwigRolePermission::SolLimit { amount } = &action.permission { println!("Role {} has {amount} lamports remaining", role.role_id); } } } ``` ## Input | Operation | Parameter | Description | | :- | :- | :- | | Both | Wallet config address and network | Existing wallet, selected through the configured client | | Add | `requesterAuthority` / `requester_authority` | Existing Ed25519 or secp256r1 authority with `manageAuthority` or `all` | | Add | `feePayer` / `fee_payer` | Public key paying the fee | | Add | `authority` | New Ed25519, secp256k1, secp256r1, or ParticipantSet authority | | Add | `actions` | At least one typed [permission](/developer-sdk/permissions) | TypeScript/Python use public-key strings. Rust uses `Pubkey` for Ed25519 and compressed 33-byte SEC1 keys for secp256k1/secp256r1. A new ParticipantSet role takes the set address without a role ID (`role_id: None` in Rust). Swig assigns the new role ID. ## Output TypeScript fields are shown below; Python uses snake\_case names. Use the read after confirmation to verify the grant. Saved policy metadata is separate. | Field | Meaning | | :- | :- | | `swigConfigAddress`, `walletAddress` | Wallet configuration and asset-holding address | | `roles[].roleId` | Assigned role identifier | | `roles[].authorityType`, `authorityValue` | Encoded authority type and value | | `roles[].actions` | Action index, action code, and stored action data for each grant | Rust returns native typed authority and permission values through its role-list result. Use the returned role ID when preparing an operation for a participant set. ## Errors | Error | Meaning | | :- | :- | | Requester cannot add the role | Its authority type or management permission is unsupported. Use an existing Ed25519 or secp256r1 administrator with manageAuthority or all. | | Invalid new-role input | The action list is empty or the new authority is malformed. Supply at least one supported action and a valid public authority. | | New authority is not usable yet | Preparation alone has not installed the role. Sign, submit, and confirm the add-role transaction before using it. | # Authorization lock Source: https://build.onswig.com/developer-sdk/authorization-locks ## Introduction An authorization lock reserves an asset amount for a role until it is spent, released, or expires. Use it when an authorized operation needs a temporary hold on SOL or tokens while other roles continue using the wallet. The backend prepares unsigned transactions. Your application handles approval, signing, and submission. Hosted support remains under review in [TypeScript/Python PR #66](https://github.com/anagrambuild/swig-developer-sdk/pull/66) and [Rust PR #79](https://github.com/anagrambuild/swig-developer-sdk/pull/79), and requires matching backend routes and the authorization-lock program. ## SDK examples ### Choose the wallet These examples target the unpublished SDK changes linked above. Use a configured client and the role that will hold or release the lock. ```typescript TypeScript theme={null} const wallet = swig.wallets.use(swigConfigAddress, { requesterAuthority: { ed25519: { publicKey: requesterPublicKey } }, }); ``` ```python Python theme={null} wallet = swig.wallets.use( swig_config_address, requester_authority={"ed25519": {"public_key": requester_public_key}}, ) ``` ### Reserve SOL Prepare a temporary lamport hold for the acting role. ```typescript TypeScript theme={null} const prepared = await wallet.addAuthorizationLock({ feePayer, amount: '1000000', durationSlots: 150, }); ``` ```python Python theme={null} prepared = await wallet.add_authorization_lock( fee_payer=fee_payer, amount=1_000_000, duration_slots=150, ) ``` ```rust Rust theme={null} use swig_developer_sdk::{AuthorizationLockExpiry, PrepareAddAuthorizationLockArgs}; let prepared = wallet.prepare_add_authorization_lock(PrepareAddAuthorizationLockArgs { swig_config_address, fee_payer, requester_authority: requester_authority.clone(), mint: None, amount: 1_000_000, expiry: AuthorizationLockExpiry::DurationSlots(150), }).await?; ``` ### Reserve a token Choose a mint to reserve base units in the wallet’s associated token account. An absolute expiry is an alternative to a relative duration. ```typescript TypeScript theme={null} const prepared = await wallet.addAuthorizationLock({ feePayer, mint, amount: '10000000', expirySlot, }); ``` ```python Python theme={null} prepared = await wallet.add_authorization_lock( fee_payer=fee_payer, mint=mint, amount=10_000_000, expiry_slot=expiry_slot, ) ``` ```rust Rust theme={null} let prepared = wallet.prepare_add_authorization_lock(PrepareAddAuthorizationLockArgs { swig_config_address, fee_payer, requester_authority: requester_authority.clone(), mint: Some(mint), amount: 10_000_000, expiry: AuthorizationLockExpiry::ExpirySlot(expiry_slot), }).await?; ``` ### List holds Inspect remaining amounts after confirmation. Include inactive records when you need to reconcile or prune them. ```typescript TypeScript theme={null} const holds = await wallet.getAuthorizationLocks({ includeExpired: true }); ``` ```python Python theme={null} holds = await wallet.get_authorization_locks(include_expired=True) ``` ```rust Rust theme={null} let holds = wallet.get_authorization_locks(&swig_config_address, true).await?; ``` ### Release or prune a hold The holder releases its active hold. Eligible managing roles may prune expired or fully captured records. ```typescript TypeScript theme={null} const prepared = await wallet.removeAuthorizationLock({ feePayer, lockId }); ``` ```python Python theme={null} prepared = await wallet.remove_authorization_lock(fee_payer=fee_payer, lock_id=lock_id) ``` ```rust Rust theme={null} use swig_developer_sdk::PrepareRemoveAuthorizationLockArgs; let prepared = wallet.prepare_remove_authorization_lock(PrepareRemoveAuthorizationLockArgs { swig_config_address, fee_payer, requester_authority, lock_id, }).await?; ``` Add/remove calls return unsigned transactions. Complete participant approval when required, then [sign](/developer-sdk/signers), submit, and confirm before querying again. ## Input | Operation | Parameter | Description | | :- | :- | :- | | All | Wallet config and network | Existing wallet on the configured client | | Read | `includeExpired` / `include_expired` | Include expired and fully captured records | | Add/remove | Requester and fee payer | Authority for the operation and public fee-payer key | | Add | `amount` | Lamports or token base units; use an exact integer value | | Add | `mint` | Omit for SOL; supply a mint to hold tokens in the wallet's associated token account | | Add | `durationSlots` / `duration_slots` or `expirySlot` / `expiry_slot` | Choose exactly one; the role's maximum duration still applies | | Remove | `lockId` / `lock_id` | ID of the hold to release or prune | The acting role needs `ManageAuthorizationLocks { max_duration_slots }`, even with `All`, and a limited role also needs the asset's spending permission. Grant this through the [Protocol SDK](/protocol/authorization-locks); the hosted add-role API does not expose it. A delegated role cannot raise its own duration bound. Only the holder can release an active hold. The holder or an eligible managing role can prune expired or fully captured records. Normal spending by the holder captures the hold and reduces its remaining amount; zero is valid. TypeScript accepts exact decimal strings or bigint for large values. Python validates amounts/slots as unsigned 64-bit integers and lock IDs as unsigned 32-bit integers. Rust uses `u64` amounts/slots, `u32` IDs, and native addresses. ## Output | Read field | Meaning | | :- | :- | | `currentSlot` / `current_slot` | Slot used to evaluate the returned holds | | `nextLockId` / `next_lock_id` | Next lock identifier | | `locks[].lockId` / `lock_id` | Hold identifier | | `locks[].roleId` / `role_id` | Holder role | | `locks[].assetAccount` / `asset_account` | Account containing the reserved asset | | `locks[].mint` | Token mint; absent for native SOL | | `locks[].amount` | Remaining base-unit amount as an exact decimal string | | `locks[].expirySlot` / `expiry_slot` | Expiry slot as an exact decimal string | | `locks[].active` | True while unexpired with a nonzero remaining amount | ## Errors | Error | Meaning | | :- | :- | | Missing lock-management permission | The requester lacks ManageAuthorizationLocks, even if it has All. Grant the scoped permission through a compatible Protocol SDK integration. | | Invalid amount or expiry | An integer is out of range, expiry is ambiguous, or duration exceeds the role bound. Use exact base units and exactly one permitted duration or expiry slot. | | Active hold cannot be released | The requester is not the holder of that active lock. Use the holder role; eligible managing roles may prune inactive records. | | Hosted method unavailable | The installed SDK/backend does not include the linked lock changes. Use matching supported builds or the Protocol SDK recipe. | # Create a wallet Source: https://build.onswig.com/developer-sdk/create-wallets Reserve a wallet address or prepare creation with a root authority, initial authority, or saved policy. ## Introduction A Swig wallet holds assets and gives each authority a defined set of permissions. Use this flow when onboarding a user or creating an application-controlled wallet. You can supply an initial authority directly, reuse a saved policy template, or reserve an address from a root authority before creating the wallet. The SDK prepares transactions. Your application signs and submits them; the wallet exists on-chain after confirmation. Start with [Client setup](/developer-sdk/integration-paths). Address reservation requires TypeScript 0.12.0 or Python 0.11.0. The Rust reservation examples use the [SDK source](https://github.com/anagrambuild/swig-developer-sdk/tree/560660cf8119112d28f8ce7924c34e89517c5eed/rust), pending the next crates.io release. ## SDK examples ### Create with an initial authority Create an inline Ed25519 wallet. Use the configured `swig` client in TypeScript/Python and `wallet: WalletClient` in Rust. ```typescript TypeScript theme={null} const created = await swig.wallets.create({ feePayer, initialUser: { ed25519: { publicKey: userPublicKey, }, }, }); ``` ```python Python theme={null} created = await swig.wallets.create( fee_payer=fee_payer, initial_user={ "ed25519": { "publicKey": user_public_key, }, }, ) ``` ```rust Rust theme={null} use swig_developer_sdk::{PrepareCreateWalletArgs, WalletAuthority}; let created = wallet .prepare_create_wallet(PrepareCreateWalletArgs { fee_payer, policy_id: None, initial_user: Some(WalletAuthority::Ed25519 { public_key: user_public_key, }), }) .await?; ``` For a saved template, supply `policyId` / `policy_id`; in Rust, use `policy_id: Some(policy_id)` and set `initial_user` only when the template needs it. TypeScript/Python return wallet addresses and an ordered `transactions` list. Sign and submit every transaction in that order. Rust returns `WalletCreation` with one `transaction`. Complete embedded signature requests and inspect each transaction's required Solana signers, including its fee payer. An empty signature-request list can still require an Ed25519 signature. Continue with [Signing](/developer-sdk/signers) and [Paymaster](/developer-sdk/sponsor-and-submit) for sponsored submission. ### Create from a policy template Use the saved template ID. Supply the initial authority only when the template expects an application-provided key. ```typescript TypeScript theme={null} const created = await swig.wallets.create({ feePayer, policyId, initialUser: { ed25519: { publicKey: userPublicKey } }, }); ``` ```python Python theme={null} created = await swig.wallets.create( fee_payer=fee_payer, policy_id=policy_id, initial_user={"ed25519": {"publicKey": user_public_key}}, ) ``` ```rust Rust theme={null} use swig_developer_sdk::{PrepareCreateWalletArgs, WalletAuthority}; let created = wallet.prepare_create_wallet(PrepareCreateWalletArgs { fee_payer, policy_id: Some(policy_id), initial_user: Some(WalletAuthority::Ed25519 { public_key: user_public_key, }), }).await?; ``` ### Reserve an address Derive the wallet's addresses from a root authority and an optional account index or salt. Address lookup creates no wallet or reservation record; the request counts toward API usage. Keep the same authority and options for activation. ```typescript TypeScript theme={null} const reserved = await swig.wallets.reserveAddress({ rootAuthority: { ed25519: { publicKey: userPublicKey } }, addressOptions: { accountIndex: 0 }, }); const walletAddress = reserved.wallet.walletAddress; const swigConfigAddress = reserved.wallet.swigConfigAddress; ``` ```python Python theme={null} reserved = await swig.wallets.reserve_address( root_authority={"ed25519": {"public_key": user_public_key}}, account_index=0, ) wallet_address = reserved.wallet.wallet_address swig_config_address = reserved.wallet.swig_config_address ``` ```rust Rust theme={null} use swig_developer_sdk::{ ReservationAddressOptions, ReserveWalletAddressArgs, WalletAuthority, }; let reserved = wallet.reserve_address(ReserveWalletAddressArgs { root_authority: WalletAuthority::Ed25519 { public_key: user_public_key }, address_options: Some(ReservationAddressOptions::AccountIndex(0)), }).await?; let wallet_address = reserved.wallet.wallet_address; let swig_config_address = reserved.wallet.swig_config_address; ``` `walletAddress` / `wallet_address` is the SOL deposit address and token-account owner. `swigConfigAddress` / `swig_config_address` identifies the wallet's roles. Confirm that the selected network supports [counterfactual creation](/solana/reservation-addresses) before funding an address. ### Create the reserved wallet Use the same root authority and index or salt. The protocol initializes role `0` with that authority and `All` permission. A funded external fee payer signs the activation transaction; the root authority does not need to sign it. ```typescript TypeScript theme={null} const created = await swig.wallets.createReserved({ rootAuthority: { ed25519: { publicKey: userPublicKey } }, addressOptions: { accountIndex: 0 }, feePayer, }); ``` ```python Python theme={null} created = await swig.wallets.create_reserved( root_authority={"ed25519": {"public_key": user_public_key}}, account_index=0, fee_payer=fee_payer, ) ``` ```rust Rust theme={null} use swig_developer_sdk::{ PrepareCreateReservedWalletArgs, ReservationAddressOptions, WalletAuthority, }; let created = wallet.prepare_create_reserved_wallet(PrepareCreateReservedWalletArgs { root_authority: WalletAuthority::Ed25519 { public_key: user_public_key }, address_options: Some(ReservationAddressOptions::AccountIndex(0)), fee_payer, }).await?; ``` The result contains the reserved addresses and one prepared transaction: `created.creationTransaction` in TypeScript, `created.creation_transaction` in Python, or `created.transaction` in Rust. Sign with the fee payer, submit, and confirm through the existing [Signing](/developer-sdk/signers) and [Paymaster](/developer-sdk/sponsor-and-submit) flow. Preparation records the create-wallet intent and prepared response, and counts toward API usage. Reusing the reservation preserves the address. Repeated on-chain activation preserves existing roles and balances; retain the original inputs after owner rotation. A closed wallet cannot be recreated from its reservation. ## Flow ```text theme={null} Choose creation path ├─ Authority / policy │ └─ Prepare creation └─ Reserve address └─ Prepare creation Sign and submit └─ Confirm ``` ## Input | Parameter | Required | Description | | :- | :- | :- | | `feePayer` / `fee_payer` | For creation | Public key paying transaction fees and account rent | | `initialUser` / `initial_user` | For inline creation | Initial authority: Ed25519, secp256k1, or secp256r1 public key; also required when a saved policy asks for it | | `policyId` / `policy_id` | No | Saved policy ID; omit for inline creation | | `rootAuthority` / `root_authority` | For reservation and activation | Direct Ed25519, secp256k1, or secp256r1 public key; sessions and ParticipantSet roots are unsupported | | Account index | No | Integer from `0` through `4294967295`; defaults to `0`. TypeScript: `addressOptions.accountIndex`; Python: `account_index`; Rust: `ReservationAddressOptions::AccountIndex` | | Salt | Alternative to an index | Exactly 32 bytes. TypeScript: `addressOptions.salt` as `Uint8Array`; Python: `salt` as `bytes`; Rust: `ReservationAddressOptions::Salt([u8; 32])`. Supply either an index or a salt | | `network` | Yes, on the call or client | `mainnet` or `devnet`; Rust uses its configured `Network` | TypeScript/Python use address strings. Rust uses `Pubkey` for Ed25519 and compressed 33-byte SEC1 keys for secp256k1/secp256r1. An application supplies passkey or EVM public keys; credential creation remains in your signing layer. Reservation and activation use `rootAuthority` / `root_authority`; inline or policy creation uses `initialUser` / `initial_user`. Reserved activation has a fixed root role and accepts no policy template. ## Errors | Error | Meaning | | :- | :- | | Missing network or initial authority | Creation has no resolved network or the template needs an authority. Set the client network and supply the required initial authority. | | Invalid public key | The key cannot be decoded or is invalid for its curve. Use the correct authority type; Rust secp256 keys must be compressed 33-byte SEC1 keys. | | Unsupported creation plan in Rust | Ordinary wallet creation returned zero or multiple transactions. Use the TypeScript/Python ordered-plan flow for a multi-transaction creation. Reserved creation returns one transaction. | | Invalid reservation options | The account index is outside the unsigned 32-bit range, the salt is not 32 bytes, or both are supplied. Reuse the same valid options for lookup and creation. | | Invalid reserved-wallet response | The response has malformed addresses, a different network, an inconsistent transaction, or an unexpected transaction count or kind. Preparation has not submitted anything. | | Request or preparation failed | The API request or a preparation dependency failed. Retrying the same reservation inputs derives the same addresses; each admitted request counts toward API usage. | # Custom transaction Source: https://build.onswig.com/developer-sdk/custom-execution Prepare a wallet transaction from your own Solana instructions. ## Introduction A custom transaction executes your Solana instructions through an existing Swig wallet. Use it to integrate a program that the transfer and swap helpers do not cover. The acting role's program and asset permissions still apply. The backend prepares the transaction; your application reviews, signs, and submits it. Use the [Protocol SDK](/products-and-sdks) for direct instruction construction. ## SDK examples ### Prepare custom instructions Use a wallet handle with its requester authority in TypeScript/Python, or `WalletClient` in Rust. See [Client setup](/developer-sdk/integration-paths). ```typescript TypeScript theme={null} const prepared = await wallet.buildTransaction({ feePayer, instructions: [ { programId: targetProgramId, accounts: [ { pubkey: writableAccount, isWritable: true, }, { pubkey: readonlyAccount, }, ], data: Buffer.from(instructionData).toString('base64'), }, ], addressLookupTableAccounts: [lookupTableAddress], }); ``` ```python Python theme={null} from swig_developer_sdk import SolanaAccountMeta, SolanaInstructionInput prepared = await wallet.build_transaction( fee_payer=fee_payer, instructions=( SolanaInstructionInput( program_id=target_program_id, accounts=( SolanaAccountMeta( pubkey=writable_account, is_writable=True, ), SolanaAccountMeta(pubkey=readonly_account), ), data=instruction_data, ), ), address_lookup_table_accounts=(lookup_table_address,), ) ``` ```rust Rust theme={null} use swig_developer_sdk::{AccountMeta, Instruction, PrepareTransactionArgs}; let prepared = wallet .prepare_transaction(PrepareTransactionArgs { swig_config_address, fee_payer, requester_authority: requester_authority.clone(), instructions: vec![Instruction { program_id: target_program_id, accounts: vec![ AccountMeta::new(writable_account, false), AccountMeta::new_readonly(readonly_account, false), ], data: instruction_data, }], address_lookup_table_accounts: vec![lookup_table_address], }) .await?; ``` Review the returned transaction and complete [Signing](/developer-sdk/signers). ParticipantSet operations first need [approval compilation](/developer-sdk/participant-sets). An empty embedded-signature list does not remove native Ed25519 signer requirements. ## Input | Parameter | Required | Description | | :- | :- | :- | | Wallet config address and network | Yes | Bind through the configured wallet client | | Requester authority | Yes | Ed25519, secp256r1, or ParticipantSet authority | | `feePayer` / `fee_payer` | Yes | Public key paying the transaction fee | | `instructions` | Yes | Nonempty ordered list of program IDs, account metadata, and instruction data | | Account metadata | For each instruction | Public key and signer/writable flags | | `addressLookupTableAccounts` / `address_lookup_table_accounts` | No | Distinct lookup-table addresses; must be empty for ParticipantSet requests | A signer account must be the derived Swig wallet address, fee payer, or Ed25519 requester. TypeScript accepts base64 instruction data; Python and Rust examples use bytes. Rust uses native `Instruction` and `AccountMeta` values. ## Errors | Error | Meaning | | :- | :- | | Invalid instruction input | The instruction list is empty or its account metadata is unsupported. Supply instructions with valid program IDs, data, and permitted signer accounts. | | Unsupported lookup-table use | A ParticipantSet requester includes address lookup tables. Keep the lookup-table list empty for that requester. | | Permission check fails | The operation exceeds the acting role's program or asset grants. Inspect the target program, asset amount, and role permissions before signing. | # Finance Source: https://build.onswig.com/developer-sdk/finance ## Introduction Finance operations fund wallets, move assets, stake SOL, or pay transaction fees. Use the guides below for the lifecycle of each operation. A prepared transaction is a proposal; the wallet authority authorizes it before submission. ## SDK examples ### Prepare a wallet transfer Use an existing wallet handle with its requester authority. Select the intended fee payer during preparation. ```typescript TypeScript theme={null} const prepared = await wallet.transfer.sol({ feePayer, destination, amount: 1_000_000n, }); ``` ```python Python theme={null} prepared = await wallet.transfer.sol( fee_payer=fee_payer, destination=destination, amount=1_000_000, ) ``` ```rust Rust theme={null} use swig_developer_sdk::PrepareTransferSolArgs; let prepared = wallet.prepare_transfer_sol(PrepareTransferSolArgs { swig_config_address, fee_payer, requester_authority, destination, amount: 1_000_000, }).await?; ``` ### Track the wallet balance After chain confirmation, use indexed balances for the portfolio view. Index updates may arrive later than confirmation. ```typescript TypeScript theme={null} const balances = await wallet.listTokenBalances(); ``` ```python Python theme={null} balances = await wallet.list_token_balances() ``` ```rust Rust theme={null} let balances = wallet.list_token_balances(&swig_config_address).await?; ``` ## Input | Flow | Input / choice | | :- | :- | | [Ramp](/developer-sdk/ramp) | Fiat/crypto amount, route, customer context, and a persisted order request ID. | | [Transfer](/developer-sdk/transfers-and-swaps) | SOL/token amount and recipient; group multiple transfers when needed. | | [Swap](/developer-sdk/swaps-and-batches) | Input/output assets, exact amount, and slippage limit. | | [Yield](/developer-sdk/yield) | Validator, delegated principal, and a role allowed to stake. | | [Paymaster](/developer-sdk/sponsor-and-submit) | Configured fee payer and signed transaction; retain the sponsorship idempotency key. | | [x402](/developer-sdk/x402) | Approved payment challenge and facilitator-supported wallet transaction. | ## Output | Result | Meaning | | :- | :- | | Prepared transaction | Unsigned transaction plus signer metadata; complete [Signing](/developer-sdk/signers) or [Participant set](/developer-sdk/participant-sets). | | Submission identifier | Track chain confirmation separately from request acceptance. | | Ramp order | Checkout and settlement lifecycle separate from the sell transfer. | | Indexed balance or position | A recorded view, potentially behind the latest chain state. | ## Errors | Error | Meaning | | :- | :- | | Permission failure | The acting role must permit the relevant programs and asset movement. | | Funding failure | Wallet principal, transaction fees, and account rent have separate funding requirements. | | Uncertain submission | Reconcile the existing attempt before creating another payment or order. | # Grant access Source: https://build.onswig.com/developer-sdk/grant-access ## Introduction Request an owner-approved role through One Business when your application does not hold the wallet’s administrator key. TypeScript and Python provide URL and callback helpers. The owner reviews the request and approves the on-chain grant; the helpers alone do not authenticate a callback or create a role. ## SDK examples ### Request owner-approved access TypeScript and Python can build a One Business grant-access link for a new authority. Your application supplies the requested One Business action objects and a saved, unpredictable callback state. The owner reviews the grant. ```typescript TypeScript theme={null} import { buildOneBusinessGrantAccessUrl } from '@swig-wallet/developer-sdk'; const grantUrl = buildOneBusinessGrantAccessUrl({ swigPubkey: swigConfigAddress, authorityPublicKey: newRolePublicKey, actions: requestedActions, appName: 'Wallet integration', redirectUri: callbackUrl, state: savedState, }); ``` ```python Python theme={null} from swig_developer_sdk import build_one_business_grant_access_url grant_url = build_one_business_grant_access_url( swig_pubkey=swig_config_address, authority_public_key=new_role_public_key, actions=requested_actions, app_name="Wallet integration", redirect_uri=callback_url, state=saved_state, ) ``` Return the URL through your application. Browser integrations can use `redirectToOneBusinessGrantAccess`; Python accepts an application-provided location adapter through `redirect_to_one_business_grant_access`. These helpers navigate; they do not grant a role themselves. ### Parse the grant callback Validate the returned state and wallet/key against the saved request, then verify the confirmed role. Callback parsing alone does not prove an on-chain grant. ```typescript TypeScript theme={null} import { completeOneBusinessGrantAccess } from '@swig-wallet/developer-sdk'; const grant = completeOneBusinessGrantAccess(returnedCallbackUrl); if (grant.state !== savedState || grant.swigPubkey !== swigConfigAddress || grant.authorityPublicKey !== newRolePublicKey) { throw new Error('Grant callback does not match the requested access'); } const currentRoles = await swig.wallets.use(swigConfigAddress).roles.list(); // Verify grant.roleId, the authority, and its actual actions in currentRoles. ``` ```python Python theme={null} from swig_developer_sdk import complete_one_business_grant_access grant = complete_one_business_grant_access(returned_callback_url) if (grant.state != saved_state or grant.swig_pubkey != swig_config_address or grant.authority_public_key != new_role_public_key): raise ValueError("Grant callback does not match the requested access") current_roles = await swig.wallets.use(swig_config_address).roles.list() # Verify grant.role_id, the authority, and its actual actions in current_roles. ``` ## Input | Input | Requirement | | :- | :- | | Wallet and authority | Config address and public key for the new authority. | | `requestedActions` / `requested_actions` | Application-supplied One Business JSON action objects; these differ from hosted `AddRoleAction` inputs. | | Callback URI and state | Trusted application callback and saved unpredictable state bound to the authenticated session. Consume it once. | | Confirmed role data | Verify the returned role ID, authority, and actual grants before enabling access. | ## Output | Callback field | Meaning | | :- | :- | | `status`, `swigPubkey`, `walletAddress`, `roleId`, `authorityPublicKey` | Parsed result identity; not proof of a grant. | | Optional `signature`, `state` | Transaction reference and application correlation value. Python uses snake\_case. | ## Errors | Error | Meaning | | :- | :- | | `OneBusinessGrantAccessCallbackError` | The callback carries an owner/provider error. | | Malformed callback | Required identity fields are missing or the role ID is invalid. | | Request mismatch | State, wallet, or authority differs from the saved request. | | Grant not confirmed | The confirmed wallet state does not contain the expected role and permissions. | # Client setup Source: https://build.onswig.com/developer-sdk/integration-paths ## Introduction A configured client authenticates hosted requests and selects the Solana network. Use one in the server runtime that owns your integration. Query methods return data; preparation methods return transactions for your application to sign. Install the latest package from the [Developer SDK homepage](/). ## Examples ### Initialize clients Create and reuse the clients in your server runtime. ```typescript TypeScript theme={null} import { SwigClient } from '@swig-wallet/developer-sdk'; const apiKey = process.env.SWIG_API_KEY; if (!apiKey) throw new Error('SWIG_API_KEY is required'); const swig = new SwigClient({ apiKey, network: 'devnet', }); ``` ```python Python theme={null} import os from swig_developer_sdk import SwigClient swig = SwigClient( api_key=os.environ["SWIG_API_KEY"], network="devnet", ) ``` ```rust Rust theme={null} use std::env; use swig_developer_sdk::{ClientConfig, Network, PaymasterClient, WalletClient}; let config = ClientConfig::new(env::var("SWIG_API_KEY")?, Network::Devnet); let wallet = WalletClient::new(config.clone())?; let paymaster = PaymasterClient::new(config.clone())?; ``` ### Bind an existing wallet Binding a handle makes no hosted request. The config address identifies the wallet; add a requester only when preparing a write. ```typescript TypeScript theme={null} const wallet = swig.wallets.use(swigConfigAddress, { requesterAuthority: { ed25519: { publicKey: requesterPublicKey } }, }); ``` ```python Python theme={null} wallet = swig.wallets.use( swig_config_address, requester_authority={"ed25519": {"public_key": requester_public_key}}, ) ``` ### Bind an IdP session After your application verifies its [IdP session](/idp-sdk/sessions-and-security), use its addresses and requester to bind a wallet handle. This helper does not authenticate the session. ```typescript TypeScript theme={null} const wallet = swig.wallets.fromIdpSession(session, { network: 'mainnet' }); ``` ```python Python theme={null} wallet = swig.wallets.from_idp_session(session, network="mainnet") ``` ### Manage the Python client lifetime Use a context manager for a bounded task, or call `aclose()` during application shutdown. Wallet handles share their parent client’s lifetime. ```python Python theme={null} import os from swig_developer_sdk import SwigClient async with SwigClient( api_key=os.environ["SWIG_API_KEY"], network="devnet", ) as swig: wallet = swig.wallets.use(swig_config_address) balances = await wallet.list_token_balances() ``` ### Configure eligible retries Set retry limits when your application needs a different policy. Operation-specific exclusions still apply, such as Ramp transfer preparation/submission. ```typescript TypeScript theme={null} const swig = new SwigClient({ apiKey, network: 'devnet', retryOptions: { maxRetries: 2, retryDelay: 500, backoffMultiplier: 2 }, }); ``` ```python Python theme={null} from swig_developer_sdk import RetryOptions, SwigClient swig = SwigClient( api_key=api_key, network="devnet", retry_options=RetryOptions(max_retries=2, retry_delay=0.5, backoff_multiplier=2), timeout=5.0, ) ``` TypeScript retry delays are milliseconds; Python retry delays and inactivity timeout are seconds. Every admitted retry counts toward the relevant usage allowance. ## Input | Input | Requirement | | :- | :- | | API key | Supply `SWIG_API_KEY` through your server’s configuration. See [API key](/examples/dev-portal/create-api-key). | | Network | `mainnet` or `devnet`; Rust uses `Network::Mainnet` or `Network::Devnet`. Match your wallet and confirmation RPC. | | Addresses | TypeScript/Python use strings. Rust uses native `Pubkey` values. | | Signing | TypeScript helpers are in `/signers`; Python exports callbacks from its package; Rust uses native signing types. See [Signing](/developer-sdk/signers). | ## Output | Capability | TypeScript / Python | Rust | | :- | :- | :- | | Wallet creation, roles, balances, history, policy | `swig.wallets` | `WalletClient` | | Paymaster balance / sponsorship | `swig.paymaster` / `swig.transactions` | `PaymasterClient` | | Participant set | `swig.participantSets` / `swig.participant_sets` | `WalletClient` | | Ramp | `swig.ramp` | `RampClient` | | DEX | `swig.dex` | Unavailable | | Yield | `swig.yield` / `swig.yields` | Unavailable | | Rent claimer | TypeScript only | Unavailable | ### Rust Use Rust 1.87 or later. Set `package.rust-version = "1.87"` and `workspace.resolver = "3"` in `Cargo.toml`; commit `Cargo.lock`. Run snippets inside an async, `Result`-returning function with a runtime such as Tokio. Add the crates directly imported by your examples. Ramp uses its own [client configuration](/developer-sdk/ramp#required-configuration). ## Errors | Error | Meaning | | :- | :- | | Missing API key | Client construction needs the server credential; do not replace missing configuration with an empty string. | | Network mismatch | Wallet state and prepared transactions belong to the selected network. | | Unsupported operation | A method absent from the installed language package needs the supported language or a compatible direct protocol integration. | # Participant set Source: https://build.onswig.com/developer-sdk/participant-sets Require multiple members to approve one wallet operation. ## Introduction A participant set lets independent members authorize one Swig role with an M-of-N threshold. Use it for shared control, such as requiring two members to approve a transfer. The set determines who approves; the role's permissions determine what they may do. Each set belongs to one Swig config. Members can use Ed25519, secp256r1/passkeys, or secp256k1. Approvals bind the same operation and shared nonce. ## SDK examples Use [Client setup](/developer-sdk/integration-paths). The examples use two Ed25519 members. `signAndSubmit` / `sign_and_submit` is your application's helper; it signs, submits, and waits for confirmation. Rust inputs use native `Pubkey` values. ### Create the set and add its role Confirm set creation before adding its role. This role needs both System Program access and a one-time SOL budget; each successful transfer reduces that budget. After adding the role, read its assigned ID for the Rust operation below. ```typescript TypeScript theme={null} import { SystemProgram } from '@solana/web3.js'; const createdSet = await swig.participantSets.create({ swigConfigAddress, feePayer, threshold: 2, members: [ { ed25519: { publicKey: participantAPublicKey } }, { ed25519: { publicKey: participantBPublicKey } }, ], }); await signAndSubmit(createdSet.transaction); const wallet = swig.wallets.use(swigConfigAddress, { requesterAuthority: { ed25519: { publicKey: adminPublicKey }, }, }); const addRole = await wallet.roles.add({ feePayer, authority: { participantSet: { address: createdSet.participantSetAddress }, }, actions: [ { type: 'program', programId: SystemProgram.programId.toBase58(), }, { type: 'solLimit', amount: 1_000_000n }, ], }); await signAndSubmit(addRole); ``` ```python Python theme={null} from swig_developer_sdk import ProgramAction, SolLimitAction from solders.system_program import ID as SYSTEM_PROGRAM_ID created_set = await swig.participant_sets.create( swig_config_address=swig_config_address, fee_payer=fee_payer, threshold=2, members=( {"ed25519": {"publicKey": participant_a_public_key}}, {"ed25519": {"publicKey": participant_b_public_key}}, ), ) await sign_and_submit(created_set.transaction) wallet = swig.wallets.use( swig_config_address, requester_authority={ "ed25519": {"publicKey": admin_public_key} }, ) add_role = await wallet.roles.add( fee_payer=fee_payer, authority={ "participantSet": {"address": created_set.participant_set_address} }, actions=( ProgramAction(program_id=str(SYSTEM_PROGRAM_ID)), SolLimitAction(amount=1_000_000), ), ) await sign_and_submit(add_role) ``` ```rust Rust theme={null} use solana_pubkey::Pubkey; use swig_developer_sdk::{ PrepareAddRoleArgs, PrepareCreateParticipantSetArgs, WalletAuthority, WalletPermission, }; let created_set = wallet .prepare_create_participant_set(PrepareCreateParticipantSetArgs { swig_config_address, fee_payer, threshold: 2, members: vec![ WalletAuthority::Ed25519 { public_key: participant_a_public_key, }, WalletAuthority::Ed25519 { public_key: participant_b_public_key, }, ], set_id: None, }) .await?; sign_and_submit(created_set.transaction).await?; let add_role = wallet .prepare_add_role(PrepareAddRoleArgs { swig_config_address, fee_payer, authority: WalletAuthority::ParticipantSet { address: created_set.participant_set_address, role_id: None, }, requester_authority: WalletAuthority::Ed25519 { public_key: admin_public_key, }, actions: vec![ WalletPermission::Program { program_id: Pubkey::from_str_const("11111111111111111111111111111111"), }, WalletPermission::SolLimit { amount: 1_000_000 }, ], }) .await?; sign_and_submit(add_role).await?; ``` ### Prepare an operation ```typescript TypeScript theme={null} const participantWallet = swig.wallets.use(swigConfigAddress, { requesterAuthority: { participantSet: { address: createdSet.participantSetAddress }, }, }); const prepared = await participantWallet.transfer.sol({ feePayer, destination, amount: 1_000n, }); const plan = prepared.participantSetApprovalPlan; if (!plan) throw new Error('ParticipantSet approval plan is missing'); ``` ```python Python theme={null} participant_wallet = swig.wallets.use( swig_config_address, requester_authority={ "participantSet": {"address": created_set.participant_set_address} }, ) prepared = await participant_wallet.transfer.sol( fee_payer=fee_payer, destination=destination, amount=1_000, ) plan = prepared.participant_set_approval_plan if plan is None: raise RuntimeError("ParticipantSet approval plan is missing") ``` ```rust Rust theme={null} use swig_developer_sdk::{PrepareTransferSolArgs, WalletAuthority}; let prepared = wallet .prepare_transfer_sol(PrepareTransferSolArgs { swig_config_address, fee_payer, destination, amount: 1_000, requester_authority: WalletAuthority::ParticipantSet { address: created_set.participant_set_address, role_id: Some(role_id), }, }) .await?; let plan = prepared .participant_set_approval_plan .as_ref() .ok_or("ParticipantSet approval plan is missing")?; ``` ### Collect member approvals Distribute each request to its member and collect the returned approval. The TypeScript/Python examples keep both callbacks together to show the full flow. For Rust, run the signer for each selected member's request from `plan.members` and collect the results into `approvals`. ```typescript TypeScript theme={null} import { createParticipantEd25519Signer, signParticipantSetApproval, } from '@swig-wallet/developer-sdk/signers'; const memberSigners = new Map([ [ participantAPublicKey, createParticipantEd25519Signer({ publicKey: participantAPublicKey, signMessage: participantASignMessage, }), ], [ participantBPublicKey, createParticipantEd25519Signer({ publicKey: participantBPublicKey, signMessage: participantBSignMessage, }), ], ]); const approvals = await Promise.all( plan.members.map(async (request) => { if (!('ed25519' in request.authority)) { throw new Error('Expected an Ed25519 ParticipantSet member'); } const signer = memberSigners.get(request.authority.ed25519.publicKey); if (!signer) throw new Error('Approval plan returned an unknown member'); return signParticipantSetApproval(request, signer); }), ); ``` ```python Python theme={null} from swig_developer_sdk.signers import ( create_participant_ed25519_signer, sign_participant_set_approval, ) member_signers = { participant_a_public_key: create_participant_ed25519_signer( public_key=participant_a_public_key, sign_message=participant_a_sign_message, ), participant_b_public_key: create_participant_ed25519_signer( public_key=participant_b_public_key, sign_message=participant_b_sign_message, ), } approvals = [] for request in plan.members: authority = request.authority.get("ed25519") if authority is None: raise RuntimeError("Expected an Ed25519 ParticipantSet member") public_key = authority["publicKey"] signer = member_signers.get(public_key) if signer is None: raise RuntimeError("Approval plan returned an unknown member") approvals.append(await sign_participant_set_approval(request, signer)) ``` ```rust Rust theme={null} use std::sync::Arc; use swig_developer_sdk::{Ed25519ParticipantSigner, ParticipantSigner}; let signer = Ed25519ParticipantSigner::new(Arc::clone(&keypair)); let approval = signer.approve(request).await?; ``` Ed25519 signs the decoded challenge. The secp256k1 participant helper signs its lowercase hexadecimal form with EIP-191. The Rust P-256 participant helper creates a software WebAuthn proof; it does not establish browser user presence. Use application-owned credential selection and RP ID/origin checks for passkeys. ### Compile and submit Compilation validates the approvals and simulates the transaction. It does not sponsor, broadcast, or confirm it. ```typescript TypeScript theme={null} const compiled = await swig.transactions.compileParticipantSetApprovals({ preparedTransaction: prepared, approvals, }); console.log(compiled.authorizationExpirationSlot); await signAndSubmit(compiled.transaction); ``` ```python Python theme={null} compiled = await swig.transactions.compile_participant_set_approvals( prepared_transaction=prepared, approvals=approvals, ) print(compiled.authorization_expiration_slot) await sign_and_submit(compiled.transaction) ``` ```rust Rust theme={null} use swig_developer_sdk::CompileParticipantSetApprovalsArgs; let compiled = wallet .compile_participant_set_approvals(CompileParticipantSetApprovalsArgs { prepared_transaction: prepared, approvals, }) .await?; ``` Add remaining [Solana signatures](/developer-sdk/signers#ed25519-and-application-defined-signers) after compilation, then submit before `authorizationExpirationSlot` / `authorization_expiration_slot`. Use [Paymaster](/developer-sdk/sponsor-and-submit) for sponsorship. Keep approvals with their original plan and nonce. ## Flow ```text theme={null} Prepared operation ├─ Member approval ├─ Member approval └─ Threshold reached └─ Compile approvals └─ Sign + submit ``` ## Input | Step | Parameter | Description | | :- | :- | :- | | Create | Wallet config, network, fee payer | Existing wallet and public fee-payer address | | Create | `members` | Public authorities of the selected members | | Create | `threshold` | Number of distinct approvals required; the example uses 2 of 2 | | Create | `setId` / `set_id` | Optional set identifier | | Add role | Set address and `actions` | Give the set a role using an existing Ed25519 or secp256r1 administrator | | Prepare | Set requester and operation inputs | Use the assigned role ID in Rust; retain the returned approval plan | | Approve | Member request and matching signer | Send each member its own challenge with the operation visible | | Compile | Original preparation and approvals | Supply distinct, valid approvals meeting the threshold | Serialize operations per set. Concurrent plans share the next nonce; once one lands, prepare and approve the others again. Supported flows include SOL/token transfers, transfer batches, and custom instructions without lookup tables. Swaps and lookup-table transactions need a direct requester. Hosted recovery preparation is not supported. ## Errors | Error | Meaning | | :- | :- | | Insufficient or duplicate approvals | The submitted proofs do not satisfy the threshold with distinct members. Collect valid approvals from enough different members. | | Stale nonce or expired plan | Another operation consumed the nonce or the approval window passed. Prepare a new operation and collect fresh approvals. | | Member signer mismatch | The signer type or public key differs from its request. Send each request to its matching member signer. | | Unsupported preparation | The operation is a swap, lookup-table custom transaction, or hosted recovery. Use a supported operation or the appropriate direct protocol integration. | # Permission Source: https://build.onswig.com/developer-sdk/permissions Choose the actions and limits granted to a wallet role. ## Introduction A permission defines an action a wallet role may perform, such as invoking a program or spending a bounded amount. Use the smallest set of grants needed by a person, service, or participant set. The same model applies to each authority type. Program access and asset spending are checked separately. A SOL transfer needs System Program access and a SOL allowance; program access alone grants no unlimited spending budget. ## SDK examples ### Limit a SOL budget These actions allow System Program invocation and a total spend of 1,000,000 lamports. Pass them to the `actions` parameter in the [Role example](/developer-sdk/add-roles-and-permissions). ```typescript TypeScript theme={null} import { type AddRoleAction } from '@swig-wallet/developer-sdk'; const actions = [ { type: 'program', programId: '11111111111111111111111111111111' }, { type: 'solLimit', amount: 1_000_000n }, ] satisfies AddRoleAction[]; ``` ```python Python theme={null} from swig_developer_sdk import ProgramAction, SolLimitAction actions = ( ProgramAction(program_id="11111111111111111111111111111111"), SolLimitAction(amount=1_000_000), ) ``` ```rust Rust theme={null} use solana_pubkey::pubkey; use swig_developer_sdk::WalletPermission; let actions = vec![ WalletPermission::Program { program_id: pubkey!("11111111111111111111111111111111"), }, WalletPermission::SolLimit { amount: 1_000_000 }, ]; ``` ### Renew a SOL allowance Allow a budget per slot window instead of a lifetime total. The window is measured in slots, not seconds. ```typescript TypeScript theme={null} const actions = [ { type: 'program', programId: '11111111111111111111111111111111' }, { type: 'solRecurringLimit', recurringAmount: 1_000_000n, window: 10_000n }, ] satisfies AddRoleAction[]; ``` ```python Python theme={null} from swig_developer_sdk import ProgramAction, SolRecurringLimitAction actions = ( ProgramAction(program_id="11111111111111111111111111111111"), SolRecurringLimitAction(recurring_amount=1_000_000, window=10_000), ) ``` ```rust Rust theme={null} let actions = vec![ WalletPermission::Program { program_id: pubkey!("11111111111111111111111111111111"), }, WalletPermission::SolRecurringLimit { recurring_amount: 1_000_000, window: 10_000, }, ]; ``` ### Restrict a token and recipient Limit spending to a mint and its exact recipient token account. The token-program public key must match that mint. ```typescript TypeScript theme={null} const actions = [ { type: 'program', programId: tokenProgramId }, { type: 'tokenDestinationLimit', mint, amount: 10_000_000n, destination: recipientTokenAccount }, ] satisfies AddRoleAction[]; ``` ```python Python theme={null} from swig_developer_sdk import ProgramAction, TokenDestinationLimitAction actions = ( ProgramAction(program_id=token_program_id), TokenDestinationLimitAction( mint=mint, amount=10_000_000, destination=recipient_token_account, ), ) ``` ```rust Rust theme={null} let actions = vec![ WalletPermission::Program { program_id: token_program_id }, WalletPermission::TokenDestinationLimit { mint, amount: 10_000_000, destination: recipient_token_account, }, ]; ``` ### Delegate role management Grant authority administration only when that person or service should be able to assign other roles. ```typescript TypeScript theme={null} const actions = [{ type: 'manageAuthority' }] satisfies AddRoleAction[]; ``` ```python Python theme={null} from swig_developer_sdk import ManageAuthorityAction actions = (ManageAuthorityAction(),) ``` ```rust Rust theme={null} let actions = vec![WalletPermission::ManageAuthority]; ``` ## Input Pass an `actions` list when [adding a role](/developer-sdk/add-roles-and-permissions). The tables use TypeScript names. Python uses constructors such as `SolLimitAction(amount=...)`; Rust uses `WalletPermission` variants and snake\_case fields. The Developer SDK exposes the following 18 actions. ### Amounts, addresses, and windows * Express SOL and staking amounts in lamports, and token amounts in the mint's smallest units. For a token with six decimals, `1_000_000` represents one token. * TypeScript accepts `bigint`, integer strings, or numbers. Use `bigint` or integer strings when a value exceeds JavaScript's safe integer range. Python accepts integers or integer strings. * Express `window` in Solana slots, not seconds. A recurring allowance resets according to its on-chain window; it is not a per-transaction limit or an exact wall-clock schedule. * In TypeScript and Python, supply public addresses as base58 strings. A SOL `destination` is the recipient account. A token `destination` is the recipient **token account**, such as its associated token account, rather than the owner's wallet address. ### Management permissions | TypeScript action | Required fields | Permission | | :- | :- | :- | | `all` | None | Full wallet authority, including asset operations and authority management. | | `allButManageAuthority` | None | Broad wallet execution and asset access, excluding authority and sub-account management. It does not grant key replacement. | | `manageAuthority` | None | Add, remove, and update authorities. This is broad administrative access rather than delegation to recover one role. | An authority that can manage roles can grant powerful permissions to another key. Choose it when the signer should administer the wallet. ### SOL permissions | TypeScript action | Required fields | Permission | | :- | :- | :- | | `solLimit` | `amount` | A total SOL allowance that decreases as it is spent. | | `solRecurringLimit` | `recurringAmount`, `window` | A SOL allowance renewed per slot window. | | `solDestinationLimit` | `amount`, `destination` | A total SOL allowance for one recipient account. | | `solRecurringDestinationLimit` | `recurringAmount`, `window`, `destination` | A recurring SOL allowance for one recipient account. | ### Token permissions | TypeScript action | Required fields | Permission | | :- | :- | :- | | `tokenLimit` | `mint`, `amount` | A total allowance for one token mint. | | `tokenRecurringLimit` | `mint`, `recurringAmount`, `window` | A recurring allowance for one token mint. | | `tokenDestinationLimit` | `mint`, `amount`, `destination` | A total allowance for one mint and recipient token account. | | `tokenRecurringDestinationLimit` | `mint`, `recurringAmount`, `window`, `destination` | A recurring allowance for one mint and recipient token account. | For example, a token transfer can combine the appropriate token program permission with `tokenDestinationLimit` to restrict both the asset and its recipient. The destination account in the permission must match the account used by the transfer. ### Program permissions | TypeScript action | Required fields | Permission | | :- | :- | :- | | `program` | `programId` | Invoke one specified program through the wallet. The Protocol SDK calls this permission `programLimit`. | | `programAll` | None | Invoke any program through the wallet, subject to the role's other permission checks. | | `programCurated` | None | Invoke programs in the protocol's built-in curated list, subject to the role's other permission checks. | The curated list is defined by the protocol version. It is not a list supplied by the application, and it does not imply approval of every operation that a listed program exposes. ### Staking and sub account permissions | TypeScript action | Required fields | Permission | | :- | :- | :- | | `stakeLimit` | `amount` | A total allowance for measured staking and unstaking changes, in lamports. | | `stakeRecurringLimit` | `recurringAmount`, `window` | A recurring allowance for measured staking and unstaking changes. | | `stakeAll` | None | Staking operations without a staking amount limit. | | `subAccount` | None | The protocol's original sub-account permission, initialized when its sub-account is created. It is distinct from the newer scoped V2 sub-account permissions. | Adding an action grants permission; it does not create a stake account or a sub-account, or prepare its operations automatically. Use the appropriate protocol instructions for those operations. The hosted add-role surface does not expose `ReplaceAuthority`, `ProgramScope`, `CloseSwigAuthority`, or scoped V2 sub-account grants. Use a compatible Protocol SDK integration when those permissions are needed. Role reads may include permissions outside this creation surface. ## Errors | Error | Meaning | | :- | :- | | Unsupported action | The requested grant is outside the hosted add-role surface. Use one of the listed actions or a compatible Protocol SDK integration. | | Program invocation rejected | The role lacks permission for the invoked program. Grant the appropriate program access in addition to the asset allowance. | | Spend rejected | The amount, destination, mint, or slot window exceeds the role grant. Check the remaining allowance and exact destination/account units. | # Buy crypto Source: https://build.onswig.com/developer-sdk/ramp ## Introduction Buy crypto with fiat and deliver it to a Swig wallet. This flow covers route selection and order creation; the customer completes the provider checkout. [Query Ramp options](/query/ramp) first to populate supported country, currency, asset, and payment-method choices. Use [Client setup](/developer-sdk/integration-paths) and the provider configuration. Sandbox is a provider environment, not a Solana devnet setting; sell transfers use mainnet even in sandbox. ## SDK examples ### Required configuration TypeScript and Python use the configured `swig` client. Rust binds the provider configuration to a separate client. ```rust Rust theme={null} use swig_developer_sdk::{RampClient, RampConfig, RampEnvironment}; let ramp = RampClient::new(config, Some(RampConfig { configuration_id, environment: RampEnvironment::Sandbox, }))?; ``` ### Quote a buy Get current buy offers for the selected asset, amount, and location. ```typescript TypeScript theme={null} const quotes = await swig.ramp.getQuotes({ configurationId, environment: 'sandbox', location: { countryCode: 'US' }, order: { type: 'buy', spend: { currencyCode: 'USD', minorUnits: 10_000n }, receive: { type: 'token', mint: usdcMint }, }, }); ``` ```python Python theme={null} from swig_developer_sdk import FiatAmountInput, RampBuyOrderRequest, RampLocation, SplTokenAsset quotes = await swig.ramp.get_quotes( configuration_id=configuration_id, environment="sandbox", location=RampLocation(country_code="US"), order=RampBuyOrderRequest( spend=FiatAmountInput(currency_code="USD", minor_units=10_000), receive=SplTokenAsset(mint=usdc_mint), ), ) ``` ```rust Rust theme={null} use swig_developer_sdk::{ CryptoAsset, FiatAmount, GetRampQuotesArgs, RampLocation, RampOrderRequest, }; let quotes = ramp .get_quotes(GetRampQuotesArgs { location: RampLocation { country_code: "US".into(), subdivision_code: None, }, order: RampOrderRequest::Buy { spend: FiatAmount { currency_code: "USD".into(), minor_units: 10_000, }, receive: CryptoAsset::Token { mint: usdc_mint }, }, }) .await?; ``` An empty list means no offer is available. Present the returned `route` and `details` for selection; the next example uses the customer-approved `selectedRoute` / `selected_route`. Quotes have no ID and are re-priced at order creation. ### Create a buy order Create checkout using the selected quote route and the same amount, asset, and location. Supply a previously saved request ID. ```typescript TypeScript theme={null} const order = await swig.ramp.createOrder({ requestId, configurationId, environment: 'sandbox', context: { customerId, swigConfigAddress, location: { countryCode: 'US' }, }, route: selectedRoute, order: { type: 'buy', spend: { currencyCode: 'USD', minorUnits: 10_000n }, receive: { type: 'token', mint: usdcMint }, }, }); ``` ```python Python theme={null} from swig_developer_sdk import RampOrderContext order = await swig.ramp.create_order( request_id=request_id, configuration_id=configuration_id, environment="sandbox", context=RampOrderContext( customer_id=customer_id, swig_config_address=swig_config_address, location=RampLocation(country_code="US"), ), route=selected_route, order=RampBuyOrderRequest( spend=FiatAmountInput(currency_code="USD", minor_units=10_000), receive=SplTokenAsset(mint=usdc_mint), ), ) ``` ```rust Rust theme={null} use swig_developer_sdk::{ CreateRampOrderArgs, CryptoAsset, FiatAmount, RampLocation, RampOrderContext, RampOrderRequest, }; let order = ramp .create_order(CreateRampOrderArgs { request_id, context: RampOrderContext { customer_id, swig_config_address, location: RampLocation { country_code: "US".into(), subdivision_code: None, }, }, route: selected_route, order: RampOrderRequest::Buy { spend: FiatAmount { currency_code: "USD".into(), minor_units: 10_000, }, receive: CryptoAsset::Token { mint: usdc_mint }, }, }) .await?; ``` Give the returned launch URL only to the customer who owns the order. It is a private checkout session, not a loggable transaction identifier. ## Flow ```text theme={null} Quote └─ Select route └─ Create checkout └─ Settle ``` ## Input | Operation | Input | Requirement | | :- | :- | :- | | Options / quote / create | `configurationId`, `environment` | Provider configuration and `sandbox` or `production`. Rust supplies `RampConfig` at construction; existing-order reads may use a client without it. | | Quote | `location`, `order` | Country plus subdivision when needed. Buy: fiat spend and crypto receive. Sell: crypto amount and fiat receive currency. | | Amounts | `minorUnits`, `baseUnits` | Fiat minor units (USD cents) and crypto base units. Use the returned currency exponent and asset decimals. TypeScript supports exact decimal strings/bigint; Rust uses `u64`. | | Assets | `type`, optional `mint` | Native SOL is `{ type: "sol" }`; a token is `{ type: "token", mint }`. Python uses `NativeSolAsset` or `SplTokenAsset`. | | Create | `requestId`, `context`, `route`, `order` | Persist one request ID per order attempt. Context contains customer ID, wallet config, location, and network. Reuse identical input on retries. | ## Output | Operation | Field | Meaning | | :- | :- | :- | | Quote | `route`, `details` | Provider/payment method plus buy/sell priced amounts, fee, and exchange rate. | | Order | `id`, `type`, `status`, `createdAt`, `updatedAt`, `quote`, optional `launchUrl` | Stored checkout with its current priced amounts and lifecycle status. | Use [order status](/query/ramp#get-order-status) to follow settlement. Quotes are re-priced at order creation. Python uses snake\_case; Rust returns native typed variants. ## Errors | Error | Meaning | | :- | :- | | Invalid configuration or amount | Configuration, environment, asset, amount scale, or location is invalid for the request. | | Idempotency conflict | A saved request ID was reused with different creation input. | | Provider or network failure | The provider, RPC, or transfer confirmation is unavailable; preserve attempt identifiers and signed bytes. | # Sell crypto Source: https://build.onswig.com/developer-sdk/ramp-sell ## Introduction Sell wallet crypto for fiat through provider checkout. Quote the amount, let the customer select a route, and create a sell order with a persisted request ID. After checkout supplies a deposit, continue with [Sell transfer](/developer-sdk/ramp-transfer). Use [Client setup](/developer-sdk/integration-paths) and the provider configuration. Sandbox is a provider environment, not a Solana devnet setting; sell transfers use mainnet even in sandbox. ## SDK examples ### Quote and create a sell Use a separate saved request ID for a sell. After quote selection, create checkout and let the customer complete its required steps. ```typescript TypeScript theme={null} const sellQuotes = await swig.ramp.getQuotes({ configurationId, environment: 'sandbox', location: { countryCode: 'US' }, order: { type: 'sell', sell: { asset: { type: 'token', mint: usdcMint }, baseUnits: 10_000_000n }, receiveFiatCurrencyCode: 'USD', }, }); // selectedSellRoute is the customer-approved route from sellQuotes. const sellOrder = await swig.ramp.createOrder({ requestId: sellRequestId, configurationId, environment: 'sandbox', context: { customerId, swigConfigAddress, network: 'mainnet', location: { countryCode: 'US' }, }, route: selectedSellRoute, order: { type: 'sell', sell: { asset: { type: 'token', mint: usdcMint }, baseUnits: 10_000_000n }, receiveFiatCurrencyCode: 'USD', }, }); ``` ```python Python theme={null} from swig_developer_sdk import ( CryptoAmountInput, RampLocation, RampOrderContext, RampSellOrderRequest, SplTokenAsset, ) sell_quotes = await swig.ramp.get_quotes( configuration_id=configuration_id, environment="sandbox", location=RampLocation(country_code="US"), order=RampSellOrderRequest( sell=CryptoAmountInput( asset=SplTokenAsset(mint=usdc_mint), base_units=10_000_000 ), receive_fiat_currency_code="USD", ), ) # selected_sell_route is approved by the customer from sell_quotes. sell_order = await swig.ramp.create_order( request_id=sell_request_id, configuration_id=configuration_id, environment="sandbox", context=RampOrderContext( customer_id=customer_id, swig_config_address=swig_config_address, network="mainnet", location=RampLocation(country_code="US"), ), route=selected_sell_route, order=RampSellOrderRequest( sell=CryptoAmountInput( asset=SplTokenAsset(mint=usdc_mint), base_units=10_000_000 ), receive_fiat_currency_code="USD", ), ) ``` ```rust Rust theme={null} use swig_developer_sdk::{ CreateRampOrderArgs, CryptoAmount, CryptoAsset, GetRampQuotesArgs, RampOrderRequest, }; let sell_quotes = ramp .get_quotes(GetRampQuotesArgs { location: context.location.clone(), order: RampOrderRequest::Sell { sell: CryptoAmount { asset: CryptoAsset::Token { mint: usdc_mint }, base_units: 10_000_000, }, receive_fiat_currency_code: "USD".into(), }, }) .await?; let sell_order = ramp .create_order(CreateRampOrderArgs { request_id, context, route: selected_route, order: RampOrderRequest::Sell { sell: CryptoAmount { asset: CryptoAsset::Token { mint: usdc_mint }, base_units: 10_000_000, }, receive_fiat_currency_code: "USD".into(), }, }) .await?; ``` ### Get the order status Refresh an order to track checkout, processing, settlement, or refund. A sell must reach `awaiting-transfer` and have deposit details before preparation. ```typescript TypeScript theme={null} const current = await swig.ramp.getOrder({ orderId: sellOrder.id }); ``` ```python Python theme={null} current = await swig.ramp.get_order(order_id=sell_order.id) ``` ```rust Rust theme={null} let current = ramp.get_order(&order_id).await?; ``` ## Flow ```text theme={null} Quote a sell └─ Select route └─ Complete checkout └─ Deposit ready └─ Transfer ``` ## Input | Operation | Input | Requirement | | :- | :- | :- | | Options / quote / create | `configurationId`, `environment` | Provider configuration and `sandbox` or `production`. Rust supplies `RampConfig` at construction; existing-order reads may use a client without it. | | Quote | `location`, `order` | Country plus subdivision when needed. Buy: fiat spend and crypto receive. Sell: crypto amount and fiat receive currency. | | Amounts | `minorUnits`, `baseUnits` | Fiat minor units (USD cents) and crypto base units. Use the returned currency exponent and asset decimals. TypeScript supports exact decimal strings/bigint; Rust uses `u64`. | | Assets | `type`, optional `mint` | Native SOL is `{ type: "sol" }`; a token is `{ type: "token", mint }`. Python uses `NativeSolAsset` or `SplTokenAsset`. | | Create | `requestId`, `context`, `route`, `order` | Persist one request ID per order attempt. Context contains customer ID, wallet config, location, and network. Reuse identical input on retries. | | Get order | `orderId` | Stored order ID. Poll non-final orders to refresh provider status; a settled order can later be refunded. | Rust uses the [configured Ramp client](/developer-sdk/ramp#required-configuration) with `Network::Mainnet`. `context` and `selected_route` are the approved customer context and sell quote route. ## Output | Operation | Field | Meaning | | :- | :- | :- | | Quote | `route`, `details` | Provider/payment method plus buy/sell priced amounts, fee, and exchange rate. | | Order | `id`, `type`, `status`, `createdAt`, `updatedAt`, `quote`, optional `launchUrl` | Stored checkout with its current priced amounts and lifecycle status. | | Sell order | Optional `deposit`, `transfer` | Provider deposit becomes available during checkout; transfer metadata appears after preparation. | ## Errors | Error | Meaning | | :- | :- | | Invalid configuration or amount | Configuration, environment, asset, amount scale, or location is invalid for the request. | | Idempotency conflict | A saved request ID was reused with different creation input. | | Provider or network failure | The provider, RPC, or transfer confirmation is unavailable; preserve attempt identifiers and signed bytes. | # Sell transfer Source: https://build.onswig.com/developer-sdk/ramp-transfer ## Introduction Move the approved crypto amount from a Swig wallet to the provider’s deposit for an existing sell order. The order must be `awaiting-transfer` and include deposit details. Use this flow after [sell checkout](/developer-sdk/ramp-sell), including recovery of a submitted attempt after an uncertain response. The examples use the same mainnet client, saved sell order, and configured requester authority. Application callbacks own signing and durable storage. ## SDK examples ### Prepare and submit the sell transfer Review the provider’s current deposit against the approved order. `signTransaction` and `saveTransferAttempt` (snake\_case in Python/Rust) are application-owned callbacks for signing and durable storage. ```typescript TypeScript theme={null} import { signPreparedTransaction } from '@swig-wallet/developer-sdk/signers'; const prepared = await swig.ramp.prepareTransfer({ orderId: sellOrder.id, requesterAuthority: { ed25519: { publicKey: requester } }, feePayer, }); const signed = await signPreparedTransaction(prepared.preparedTransaction, { signTransaction, }); await saveTransferAttempt({ orderId: sellOrder.id, transferId: prepared.transfer.transferId, signedTransaction: signed.transaction, }); const transfer = await swig.ramp.submitTransfer({ orderId: sellOrder.id, transferId: prepared.transfer.transferId, signedTransaction: signed.transaction, }); ``` ```python Python theme={null} from swig_developer_sdk.signers import sign_prepared_transaction prepared = await swig.ramp.prepare_transfer( order_id=sell_order.id, requester_authority={"ed25519": {"publicKey": requester}}, fee_payer=fee_payer, ) signed = await sign_prepared_transaction( prepared.prepared_transaction, sign_transaction=sign_transaction, ) await save_transfer_attempt( order_id=sell_order.id, transfer_id=prepared.transfer.transfer_id, signed_transaction=signed.transaction, ) transfer = await swig.ramp.submit_transfer( order_id=sell_order.id, transfer_id=prepared.transfer.transfer_id, signed_transaction=signed.transaction, ) ``` ```rust Rust theme={null} use swig_developer_sdk::{ PrepareRampTransferArgs, SubmitRampTransferArgs, WalletAuthority, }; let prepared = ramp .prepare_transfer(PrepareRampTransferArgs { order_id: order_id.clone(), requester_authority: WalletAuthority::Ed25519 { public_key: requester_public_key, }, fee_payer, }) .await?; let signed_transaction = sign_transaction(&prepared.prepared_transaction).await?; save_transfer_attempt( &order_id, &prepared.transfer.transfer_id, &signed_transaction, ).await?; let transfer = ramp .submit_transfer(SubmitRampTransferArgs { order_id: order_id.clone(), transfer_id: prepared.transfer.transfer_id.clone(), signed_transaction: Some(signed_transaction), }) .await?; ``` Preparation returns transaction bytes once. Save the order ID, transfer ID, and exact signed bytes before submission. The Rust signing callback returns a native `VersionedTransaction`. ### Resolve a submitted transfer For an attempt already in `submitted`, resolve the same transfer without signing or paying again. ```typescript TypeScript theme={null} await swig.ramp.submitTransfer({ orderId: sellOrder.id, transferId: prepared.transfer.transferId, }); ``` ```python Python theme={null} await swig.ramp.submit_transfer( order_id=sell_order.id, transfer_id=prepared.transfer.transfer_id, ) ``` ```rust Rust theme={null} use swig_developer_sdk::SubmitRampTransferArgs; let transfer = ramp .submit_transfer(SubmitRampTransferArgs { order_id, transfer_id, signed_transaction: None, }) .await?; ``` ## Flow ```text theme={null} Prepare deposit transfer └─ Review and sign └─ Save exact bytes └─ Submit └─ Resolve ``` ## Input | Operation | Input | Requirement | | :- | :- | :- | | Prepare transfer | `orderId`, `requesterAuthority`, `feePayer` | Eligible sell with a ready deposit. Rust supports Ed25519/secp256r1 on mainnet, without ParticipantSet approvals. | | Submit transfer | `orderId`, `transferId`, optional `signedTransaction` | A prepared attempt requires saved signed bytes. A submitted attempt can be resolved without bytes. Keep the same IDs throughout. | TypeScript names are shown; Python uses snake\_case. Preparation and transfer submission are not retried automatically; Rust quotes also send once. Only prepare a replacement after the previous attempt is failed or expired and the order is still eligible. An uncertain response alone is insufficient. ## Output | Operation | Field | Meaning | | :- | :- | :- | | Preparation | `preparedTransaction`, `deposit`, `transfer` | Unsigned transaction and the exact transfer attempt. Order reads cannot recover its transaction bytes. | | Transfer | `transferId`, `state`, `expiresAt`, optional `solanaSignature` | Prepared, submitted, landed, failed, or expired. Landed means confirmed or better; order settlement is tracked separately. | ## Errors | Error | Meaning | | :- | :- | | `the deposit address is not ready` | Checkout has not produced a transferable deposit; preparation must wait. | | Transfer not eligible | Order or attempt state does not permit preparation, resubmission, or replacement. | | Uncertain submission | The same transfer may already have broadcast. Resolve its stored IDs and state before considering another attempt. | | Provider or network failure | The provider, RPC, or transfer confirmation is unavailable; preserve attempt identifiers and signed bytes. | # Rent claimer Source: https://build.onswig.com/developer-sdk/rent-claimers Inspect or set the recipient of recovered rent for a V2 Swig wallet. ## Introduction The rent claimer is the recipient configured to receive reclaimed rent from a V2 Swig wallet. Set it when your application needs an explicit rent recipient, including a sponsor that funds account creation. The TypeScript SDK supports reading the recipient and preparing its one-time setter. The backend checks finalized chain state. Python and Rust do not currently expose this hosted operation. ## SDK examples Use the configured `swig` client and public address strings. ### Get the rent claimer Inspect the configured recipient before preparing its one-time setter. ```typescript TypeScript theme={null} const wallet = swig.wallets.use(swigConfigAddress, { requesterAuthority: { ed25519: { publicKey: requesterPublicKey } }, }); const recipient = await wallet.getRentClaimer(); ``` ### Set the rent claimer Prepare the recipient once. Sign with the requester and fee payer, submit, then wait for finality. ```typescript TypeScript theme={null} const prepared = await wallet.setRentClaimer({ feePayer, rentClaimer: rentClaimerPublicKey, }); ``` ### Confirm the recipient After the setter reaches finality, fetch the recipient again. ```typescript TypeScript theme={null} const confirmedRecipient = await wallet.getRentClaimer(); if (confirmedRecipient !== rentClaimerPublicKey) { throw new Error('Confirmed rent claimer differs from the requested recipient'); } ``` Preparation changes no chain state. Concurrent preparations may succeed, but only the first valid setter can land. The setter is not automatically retried. ## Input | Operation | Parameter | Description | | :- | :- | :- | | Both | Wallet config address and network | Use a configured wallet handle on `mainnet` or `devnet` | | Set | `requesterAuthority` | Direct Ed25519 role with `All` or `CloseSwigAuthority`; `ManageAuthority` alone is insufficient | | Set | `feePayer` | Public key paying the transaction fee | | Set | `rentClaimer` | Recipient public key; cannot be zero, the Swig config, or its wallet-address PDA | The recipient can be set only once, including when a second request names the same recipient. Session, passkey, EVM, and ParticipantSet requesters are unsupported. ## Output | Read result | Meaning | | :- | :- | | Public-key string | Configured rent recipient | | `null` | Valid config with no recipient set | ## Errors | Error | Meaning | | :- | :- | | Recipient already set | The on-chain recipient cannot be changed, even to the same key. Read the current recipient and use that confirmed value. | | Requester not allowed | The setter requires direct Ed25519 with All or CloseSwigAuthority. Choose an eligible role; ManageAuthority alone is insufficient. | | Invalid recipient | The address is zero, the Swig config, or its wallet-address PDA. Supply a valid separate rent-recipient account. | | Account read failed | State is missing, malformed, unsupported, or unavailable. Check the config and network. Only a valid unset config returns null. | # Signing Source: https://build.onswig.com/developer-sdk/signers Authorize a prepared transaction with your application's signer. ## Introduction Signing proves that an authorized wallet member approves a prepared operation. Use this step after preparation and before submission. Your application owns user approval, signer selection, and key custody; the hosted API key stays on your server. TypeScript's `/signers` entrypoint and Python's helpers use application callbacks. Rust's native signers hold local keys through `Arc`. These helpers make no hosted API calls. Inspect transaction intent, permissions, and freshness before signing. ## SDK examples ### Ed25519 and application-defined signers TypeScript/Python callbacks receive the base64 transaction and prepared record, and return signed base64. Rust adds a signature to the correct native slot. Use `prepared.transaction` after resolving participant and embedded signatures. Repeat for each required application-owned Ed25519 signer. ```typescript TypeScript theme={null} import { signPreparedTransaction, type PreparedTransaction, } from '@swig-wallet/developer-sdk/signers'; declare const prepared: PreparedTransaction; const signed = await signPreparedTransaction(prepared, { signTransaction: async (transaction) => { return applicationSigner.signSerializedTransaction(transaction); }, }); ``` ```python Python theme={null} from swig_developer_sdk import sign_prepared_transaction async def sign_with_application(transaction, _prepared): return await application_signer(transaction) signed = await sign_prepared_transaction( prepared, sign_transaction=sign_with_application, ) ``` ```rust Rust theme={null} use std::io; use solana_signer::Signer; let mut signed_transaction = transaction; signed_transaction.sanitize()?; let required = usize::from(signed_transaction.message.header().num_required_signatures); let signer_index = signed_transaction .message .static_account_keys() .iter() .take(required) .position(|public_key| public_key == &signer.pubkey()) .ok_or_else(|| io::Error::other("key is not a required transaction signer"))?; let signature = signer.try_sign_message(&signed_transaction.message.serialize())?; let slot = signed_transaction .signatures .get_mut(signer_index) .ok_or_else(|| io::Error::other("required signature slot is missing"))?; *slot = signature; ``` ### Secp256r1 and passkeys TypeScript runs the passkey ceremony in a WebAuthn environment. Python uses your assertion callback. Rust signs raw P-256 authority requests with a local key; it does not run a browser passkey ceremony. ```typescript TypeScript theme={null} import { createSecp256r1PasskeySigningFn, signPreparedSwigTransaction, } from '@swig-wallet/developer-sdk/signers'; const passkeySigner = createSecp256r1PasskeySigningFn({ allowCredentials: [{ id: credentialId, type: 'public-key' }], userVerification: 'preferred', }); const signed = await signPreparedSwigTransaction(prepared, { secp256r1: passkeySigner, }); ``` ```python Python theme={null} from swig_developer_sdk import ( create_secp256r1_passkey_signing_fn, sign_prepared_swig_transaction, ) passkey_signer = create_secp256r1_passkey_signing_fn(get_webauthn_assertion) signed = await sign_prepared_swig_transaction( prepared, secp256r1=passkey_signer, ) ``` ```rust Rust theme={null} use std::sync::Arc; use swig_developer_sdk::{Secp256r1TransactionSigner, TransactionSigner}; let signer = Secp256r1TransactionSigner::new(Arc::clone(&signing_key)); let transaction = signer.sign_prepared_transaction(prepared).await?; ``` ### Secp256k1 and EVM wallets TypeScript/Python use an application-supplied EIP-1193 provider's `personal_sign`. `eip1193Provider` / `eip1193_provider` is the connected wallet provider. Rust uses raw secp256k1 authority signing, which differs from the EIP-191 format used by a [participant signer](/developer-sdk/participant-sets#collect-member-approvals). ```typescript TypeScript theme={null} import { createSecp256k1EvmSigningFn, signPreparedSwigTransaction, } from '@swig-wallet/developer-sdk/signers'; const evmSigner = createSecp256k1EvmSigningFn({ provider: eip1193Provider, address: evmAddress, }); const signed = await signPreparedSwigTransaction(prepared, { secp256k1: evmSigner, }); ``` ```python Python theme={null} from swig_developer_sdk import ( create_secp256k1_evm_signing_fn, sign_prepared_swig_transaction, ) evm_signer = create_secp256k1_evm_signing_fn( provider=eip1193_provider, address=evm_address, ) signed = await sign_prepared_swig_transaction( prepared, secp256k1=evm_signer, ) ``` ```rust Rust theme={null} use std::sync::Arc; use swig_developer_sdk::{Secp256k1TransactionSigner, TransactionSigner}; let signer = Secp256k1TransactionSigner::new(Arc::clone(&signing_key)); let transaction = signer.sign_prepared_transaction(prepared).await?; ``` Return the signed transaction through an authenticated application route, then submit through your RPC provider or [Paymaster](/developer-sdk/sponsor-and-submit). Track confirmation separately. Keep the API key, private keys, and credential material inside their owning trust boundaries. ### Sign an ordered preparation plan Resolve the embedded requests in every transaction using the same registered signer callbacks. The helper preserves order and stops on failure. ```typescript TypeScript theme={null} import { signPreparedSwigTransactions } from '@swig-wallet/developer-sdk/signers'; const signedPlan = await signPreparedSwigTransactions(created.transactions, { secp256r1: passkeySigner, }); ``` ```python Python theme={null} from swig_developer_sdk import sign_prepared_swig_transactions signed_plan = await sign_prepared_swig_transactions( created.transactions, secp256r1=passkey_signer, ) ``` Complete each transaction’s required native Solana signatures after embedded signing, then submit in the original order. These helpers do not submit or confirm the plan. ## Flow ```text theme={null} Prepared transaction ├─ Embedded signatures └─ Solana signatures └─ Submit └─ Confirm ``` Complete only the steps requested by the preparation. Changing instruction data after outer Solana signing invalidates those signatures. ## Input | Parameter | Description | | :- | :- | | Prepared transaction | Original result from wallet preparation, including signature requests and any participant approval plan | | Signer | Must match the requester authority and public key used during preparation | | Application approval | Validate the wallet, operation, recipient, amount, and expiry before asking for a signature | | Fee-payer signature | Add after the message is final; a paymaster can supply its own signature during sponsorship | An empty `signatureRequests` / `signature_requests` list does **not** mean the transaction is fully signed. Embedded secp256k1/secp256r1 requests are separate from native Ed25519 requirements in the serialized transaction. Rust's `TransactionSigner` consumes a `PreparedTransaction` and returns a `VersionedTransaction`. All embedded requests must match that signer. ## Errors | Error | Meaning | | :- | :- | | Authority or public-key mismatch | The signer does not match an embedded request. Select the signer matching the original preparation. | | Pending participant approvals | Rust native transaction signing receives an uncompiled approval plan. Collect and compile participant approvals first. | | Outer signatures already present | Embedded data still needs patching, which changes the signed message. Resolve embedded signatures first, then collect outer Solana signatures. | | Missing native signature | An empty embedded-request list was mistaken for a fully signed transaction. Inspect the serialized required signer set and fill each required slot. | # Paymaster Source: https://build.onswig.com/developer-sdk/sponsor-and-submit Check funding and sponsor application-signed transactions. ## Introduction A paymaster pays a transaction's Solana fee on behalf of your user. Use it when your application should cover fees so the user can transact without holding SOL for gas. Your user still authorizes the wallet operation. ## SDK examples Use the clients from [Client setup](/developer-sdk/integration-paths). Rust uses separate `WalletClient` and `PaymasterClient` instances on the same network. ### Check paymaster funding ```typescript TypeScript theme={null} const balance = await swig.paymaster.getBalance({ network: 'mainnet', kind: 'api', }); if (!balance.configured) throw new Error('API paymaster is not configured'); // balance.configured, balance.address, balance.balanceLamports, balance.balanceSol ``` ```python Python theme={null} balance = await swig.paymaster.get_balance(network="mainnet", kind="api") if not balance.configured: raise RuntimeError("API paymaster is not configured") # balance.configured, balance.address, balance.balance_lamports, balance.balance_sol ``` ```rust Rust theme={null} let balance = paymaster.get_balance().await?; ``` Use `getIdpBalance()` / `get_idp_balance()` for IdP funding. TypeScript/Python resolve network from the call, then client, then mainnet for paymaster calls. Rust always uses its configured network. ### Sponsor one transaction For TypeScript/Python, `signedBase64Transaction` / `signed_base64_transaction` is your already-signed preparation. Rust's `sign_transaction` is an application-owned async helper following [Signing](/developer-sdk/signers). ```typescript TypeScript theme={null} const submitted = await swig.transactions.sponsor({ transaction: signedBase64Transaction, network: 'mainnet', idempotencyKey, }); // submitted.requestId // submitted.signature // submitted.spentByPaymaster ``` ```python Python theme={null} from swig_developer_sdk import SponsorSignedTransactionArgs submitted = await swig.transactions.sponsor( SponsorSignedTransactionArgs( transaction=signed_base64_transaction, network="mainnet", idempotency_key=idempotency_key, ) ) # submitted.request_id # submitted.signature # submitted.spent_by_paymaster ``` ```rust Rust theme={null} use swig_developer_sdk::{PrepareTransferSolArgs, SponsorSignedTransactionArgs}; let funding = paymaster.get_balance().await?; let prepared = wallet .prepare_transfer_sol(PrepareTransferSolArgs { swig_config_address, fee_payer: funding.address, destination, amount: lamports, requester_authority, }) .await?; let signed_transaction = sign_transaction(&prepared).await?; let submitted = paymaster .sponsor(SponsorSignedTransactionArgs { transaction: signed_transaction, idempotency_key, }) .await?; ``` The result contains the request ID, submitted signature, and paymaster spend. RPC acceptance is not confirmation; track confirmation or finality separately. Rust returns a native `Signature`; `spent_by_paymaster` is an `i64` and may be negative. ### Sponsor a bundle Use an ordered bundle for one to five signed transactions that must land together. Bundles are mainnet-only. Before collecting signatures: * Include transfers totaling at least 1,000 lamports from the API paymaster to backend-recognized Jito tip accounts. * Keep tip destinations in static account keys, outside lookup tables. * Keep the paymaster out of every other instruction's account list, including read-only accounts. The SDK does not add the tip for you. ```typescript TypeScript theme={null} const bundle = await swig.transactions.sponsorBundle({ transactions: [signedFirstBase64, signedSecondBase64], network: 'mainnet', idempotencyKey, }); // bundle.requestId // bundle.bundleId // bundle.signatures // bundle.estimatedSpentByPaymaster ``` ```python Python theme={null} from swig_developer_sdk import SponsorSignedTransactionBundleArgs bundle = await swig.transactions.sponsor_bundle( SponsorSignedTransactionBundleArgs( transactions=(signed_first_base64, signed_second_base64), network="mainnet", idempotency_key=idempotency_key, ) ) # bundle.request_id # bundle.bundle_id # bundle.signatures # bundle.estimated_spent_by_paymaster ``` ```rust Rust theme={null} use swig_developer_sdk::SponsorSignedTransactionBundleArgs; let bundle = paymaster .sponsor_bundle(SponsorSignedTransactionBundleArgs { transactions: signed_transactions, idempotency_key, }) .await?; ``` The response preserves signature order. A `bundleId` means acceptance by Jito, not confirmation; `estimatedSpentByPaymaster` is an estimate, not a settled charge. The same transaction-and-key retry rules apply. ### Check IdP funding Query the separate IdP paymaster when your integration sponsors IdP operations. ```typescript TypeScript theme={null} const idpBalance = await swig.paymaster.getIdpBalance({ network: 'mainnet' }); if (!idpBalance.configured) throw new Error('IdP paymaster is not configured'); ``` ```python Python theme={null} idp_balance = await swig.paymaster.get_idp_balance(network="mainnet") if not idp_balance.configured: raise RuntimeError("IdP paymaster is not configured") ``` ```rust Rust theme={null} let idp_balance = paymaster.get_idp_balance().await?; ``` ## Flow ```text theme={null} Prepare with paymaster └─ User signs └─ Sponsor fees └─ Confirm ``` ## Input | Operation | Parameter | Description | | :- | :- | :- | | Both | `network` | `mainnet` or `devnet`; use the same network for wallet and paymaster clients | | Balance | `kind` | `api` for transaction sponsorship; `idp` for IdP funding | | Sponsor | `transaction` | Signed base64 transaction in TypeScript/Python; native `VersionedTransaction` in Rust | | Sponsor | `idempotencyKey` / `idempotency_key` | Stable key for this exact transaction; reuse it for retries | Use the API paymaster's returned address as `feePayer` / `fee_payer` during preparation. Complete participant approval and embedded signatures, then every required application-owned Solana signature. Sponsorship adds the paymaster's signature; it does not replace the other signers. Keep the same signed transaction and key on retry. A matching retry returns the original result without another spend. Resolve an uncertain attempt before starting another. In Rust, `Some(nonempty_key)` enables eligible retries; `None` or an empty key disables them. ## Output The balance read returns the following fields. Python uses snake\_case attributes. | Field | TypeScript/Python type | Meaning | | :- | :- | :- | | `configured` | boolean | Distinguishes an absent paymaster from one with zero SOL | | `kind` | string | `api`, `idp`, or `unspecified` | | `id`, `address`, `label` | string | Identifier, public key, and display label | | `balanceLamports` / `balance_lamports` | string | Exact balance in lamports | | `balanceSol` / `balance_sol` | number | SOL balance for display | Rust returns `PaymasterBalance` with a `Pubkey` address and `u64` lamport balance. It has no `configured` field. Each admitted balance call consumes one API request, including retries and admitted errors. Reading funding does not spend the sponsorship budget. ## Errors | Error | Meaning | | :- | :- | | API paymaster not configured | TypeScript/Python return configured=false; Rust returns GetPaymasterBalanceError::NotConfigured. Create an API paymaster for this network. IdP funding is a separate balance. | | Insufficient funding or spending limit reached | The paymaster cannot cover this request within its configured limits. Check its balance and limits in the Developer Portal. | | Missing signature or incorrect fee payer | The transaction is not ready for this paymaster to sponsor. Prepare with the API paymaster address and complete all other required signatures. | | Idempotency conflict or lost response | The outcome of this attempt needs reconciliation. Keep the original transaction and key; resolve the attempt before starting a replacement. | # Swap Source: https://build.onswig.com/developer-sdk/swaps-and-batches ## Introduction Swap exchanges one token for another from a Swig wallet. Use it for portfolio rebalancing or payments that need a different asset. The SDK prepares a swap transaction; review its amounts and destination before signing and submitting. ## SDK examples ### Prepare a swap Use a wallet handle with its requester authority, or `WalletClient` in Rust. ```typescript TypeScript theme={null} const preparedSwap = await wallet.swap.jupiter({ feePayer, inputMint, outputMint, amount: 10_000n, slippageBps: 100, destinationAccount, wrapAndUnwrapSol: true, }); ``` ```python Python theme={null} prepared_swap = await wallet.swap.jupiter( fee_payer=fee_payer, input_mint=input_mint, output_mint=output_mint, amount=10_000, slippage_bps=100, destination_account=destination_account, wrap_and_unwrap_sol=True, ) ``` ```rust Rust theme={null} use swig_developer_sdk::{PrepareSwapArgs, SwapOptions}; let prepared_swap = wallet .prepare_swap(PrepareSwapArgs { swig_config_address, fee_payer, requester_authority: requester_authority.clone(), input_mint, output_mint, amount: 10_000, options: Some(SwapOptions { slippage_bps: Some(100), destination_owner: Some(destination_owner), wrap_and_unwrap_sol: Some(true), ..SwapOptions::default() }), }) .await?; ``` ### Bound execution settings Limit routing account count and transaction lifetime when preparing a swap for your application’s execution budget. ```typescript TypeScript theme={null} const prepared = await wallet.swap({ feePayer, inputMint, outputMint, amount: '10000000', slippageBps: 50, destinationAccount: recipientOwner, wrapAndUnwrapSol: true, maxAccounts: 32, blockhashSlotsToExpiry: 30, }); ``` ```python Python theme={null} prepared = await wallet.swap( fee_payer=fee_payer, input_mint=input_mint, output_mint=output_mint, amount=10_000_000, slippage_bps=50, destination_account=recipient_owner, wrap_and_unwrap_sol=True, max_accounts=32, blockhash_slots_to_expiry=30, ) ``` ## Input | Input | Requirement | | :- | :- | | Wallet, network, requester | Existing wallet with input-asset spending and required program permissions. Rust accepts Ed25519 or secp256r1. | | `feePayer` / `fee_payer` | Public key paying transaction fees and required account rent. | | `inputMint`, `outputMint`, `amount` | Source/destination mints and positive exact input base units. Python uses snake\_case. | | `slippageBps` / `slippage_bps` | Allowed slippage in basis points; 50 means 0.5%. | | `destinationAccount` / `destination_account` | Recipient owner; the backend resolves its output ATA or native SOL destination. Rust names this `destination_owner`. | | `wrapAndUnwrapSol` / `wrap_and_unwrap_sol` | Whether to wrap or unwrap native SOL. | | Execution options | Tips, maximum accounts, blockhash expiry slots, and compute-unit-price percentile. Percentile is at most 10,000 basis points. | ## Errors | Error | Meaning | | :- | :- | | Invalid swap input | Missing/invalid mints, nonpositive amount, or an out-of-range execution option. | | No usable route | The requested asset pair, amount, or routing constraints cannot produce a swap. | | Permission or balance failure | The role lacks required program/asset permission or the wallet/fee payer cannot fund the operation. | | Expired or changed market state | A prepared transaction can expire or fail its execution constraints. Reconcile submission before preparing a replacement. | # Transfer Source: https://build.onswig.com/developer-sdk/transfers-and-swaps ## Introduction Transfer moves SOL or tokens from a Swig wallet to another account. Use it for payments, withdrawals, or distributing funds to several recipients. The SDK prepares transactions for the selected role; your application signs and submits them. Use clients from [Client setup](/developer-sdk/integration-paths). ## SDK examples ### Choose the wallet Use an existing config and the authority that will authorize the transfer. ```typescript TypeScript theme={null} const wallet = swig.wallets.use({ swigConfigAddress, walletAddress, requesterAuthority: { ed25519: { publicKey: authorityPublicKey }, }, }); ``` ```python Python theme={null} from swig_developer_sdk import WalletReference wallet = swig.wallets.use( WalletReference( swig_config_address=swig_config_address, wallet_address=wallet_address, requester_authority={ "ed25519": {"publicKey": authority_public_key}, }, ) ) ``` ### Transfer SOL Send a positive amount in lamports to a Solana address. ```typescript TypeScript theme={null} const prepared = await wallet.transfer.sol({ feePayer, destination, amount: 1_000_000n, }); ``` ```python Python theme={null} prepared = await wallet.transfer.sol( fee_payer=fee_payer, destination=destination, amount=1_000_000, ) ``` ```rust Rust theme={null} use swig_developer_sdk::PrepareTransferSolArgs; let prepared = wallet .prepare_transfer_sol(PrepareTransferSolArgs { swig_config_address, fee_payer, requester_authority: requester_authority.clone(), destination, amount: 1_000_000, }) .await?; ``` ### Transfer a token Send base units to a recipient owner. The backend resolves associated token accounts and prepares destination-account creation when needed. ```typescript TypeScript theme={null} const prepared = await wallet.transfer.token({ feePayer, mint, destinationOwner, amount: 10_000n, }); ``` ```python Python theme={null} prepared = await wallet.transfer.token( fee_payer=fee_payer, mint=mint, destination_owner=destination_owner, amount=10_000, ) ``` ```rust Rust theme={null} use swig_developer_sdk::PrepareTransferTokenArgs; let prepared = wallet .prepare_transfer_token(PrepareTransferTokenArgs { swig_config_address, fee_payer, requester_authority: requester_authority.clone(), mint, destination_owner, amount: 10_000, }) .await?; ``` ### Group transfers Prepare an ordered plan containing multiple SOL and token transfers. ```typescript TypeScript theme={null} const prepared = await wallet.prepare({ feePayer, operations: [ { type: 'transferSol', destination, amount: 1_000_000n, }, { type: 'transferToken', mint, destinationOwner, amount: 10_000n, }, ], }); ``` ```python Python theme={null} from swig_developer_sdk import TransferSolOperation, TransferTokenOperation prepared = await wallet.prepare( fee_payer=fee_payer, operations=( TransferSolOperation( destination=destination, amount=1_000_000, ), TransferTokenOperation( mint=mint, destination_owner=destination_owner, amount=10_000, ), ), ) ``` ```rust Rust theme={null} use swig_developer_sdk::{PrepareOperation, PrepareTransfersArgs}; let prepared = wallet .prepare_transfers(PrepareTransfersArgs { swig_config_address, fee_payer, requester_authority: requester_authority.clone(), operations: vec![ PrepareOperation::TransferSol { destination, amount: 1_000_000, }, PrepareOperation::TransferToken { mint, destination_owner, amount: 10_000, }, ], }) .await?; ``` TypeScript/Python return an ordered transaction list. Sign and submit it in order. Rust accepts a response containing exactly one transaction, even when that transaction holds multiple operations. ## Input | Operation | Input | Requirement | | :- | :- | :- | | All | Wallet config, network, requester authority | Existing wallet and a role permitted to invoke the target program and spend the asset. Rust supplies these on each call. | | All | `feePayer` / `fee_payer` | Public key paying fees and any destination-account rent. | | SOL | `destination`, `amount` | Recipient public key and positive integer lamports. | | Token | `mint`, `destinationOwner` / `destination_owner`, `amount` | Token mint, recipient owner (not an arbitrary token account), and positive base units. | | Grouped | `operations` | Nonempty ordered list of SOL/token operations; same requester and fee payer. | Use `bigint` or decimal strings for large TypeScript amounts, Python integers, and Rust `u64`. Rust supports Ed25519, secp256r1, and ParticipantSet requesters. For a participant set, [compile member approvals](/developer-sdk/participant-sets) before signing the outer transaction. See [Signing](/developer-sdk/signers) for embedded requests and native signer requirements. ## Errors | Error | Meaning | | :- | :- | | Invalid amount or address | Amounts must be positive base-unit integers and addresses must match the operation’s account type. | | Permission denied | The role lacks program access or sufficient spending allowance; both are checked. | | Insufficient funds | The wallet cannot cover the transfer or the fee payer cannot cover fees/account rent. | | Unsupported Rust plan | Rust rejects zero or multiple returned transactions. TypeScript/Python can consume ordered plans. | # Guardian recovery Source: https://build.onswig.com/developer-sdk/use-cases/guardian-recovery Delegate replacement of one role's key while preserving its permissions. ## Introduction Guardian recovery lets a designated authority replace a lost signer's key while preserving the wallet and the protected role's permissions. Use it for an independent backup path, configured while an authorized administrator is still available. Creating a new passkey alone cannot recover an unconfigured wallet. The protocol permission is `ReplaceAuthority { role_id }`, used with `ReplaceAuthorityV1`. It preserves the target role's ID, authority type, and actions. A passkey role therefore receives another P-256 key. Older names were `RecoveryAuthority` and `RecoverAuthorityV1`. ## SDK examples The Developer SDK does not currently expose scoped replacement permission or a working recovery preparation method. Compatibility recovery types do not supply that flow. Use a compatible [Protocol SDK integration](/protocol/recovery-model) with the [scoped permission definition](https://github.com/anagrambuild/swig-wallet/blob/3e0411f0c2980b26296903eaa4aa0c2d07869316/state/src/action/replace_authority.rs). After confirmation, verify that the target role uses the new key and retains its permissions. Replacing a session authority also clears its session key and expiry. For multiple guardians, one participant-controlled recovery role would hold the scoped permission. Giving each guardian a separate recovery role permits each to recover independently. Connecting threshold approval to the replacement-specific proof requires additional integration; ordinary [Participant set](/developer-sdk/participant-sets) approval is not that proof. Hosted participant recovery is not currently supported. ### Verify the recovered role After a compatible protocol integration confirms replacement, inspect the target role’s key and retained permissions. ```typescript TypeScript theme={null} const result = await swig.wallets.use(swigConfigAddress).roles.list(); ``` ```python Python theme={null} result = await swig.wallets.use(swig_config_address).roles.list() ``` ```rust Rust theme={null} let result = wallet.list_roles(&swig_config_address).await?; ``` ## Flow ```text theme={null} Grant scoped recovery └─ New key └─ Guardian approval └─ Replace key └─ Confirm ``` ## Input | Step | Input | Requirement | | :- | :- | :- | | Configure | Target role ID | The one role the guardian may recover | | Configure | Guardian public authority | Independently available key, held by a backup device, person, or service | | Configure | Administrator | Existing authority with `All` or `ManageAuthority` grants the scoped permission | | Replace | New public key | Same authority type as the protected role | | Replace | Guardian authorization | Bind approval to the wallet, target role, and exact replacement key | The guardian's role needs only `ReplaceAuthority` for the protected role. It does not need the lost key or broad management access to perform replacement. It can choose the key that inherits the role's power, so protect it accordingly. A delay or cancellation mechanism requires a separate recovery policy. ## Errors | Error | Meaning | | :- | :- | | No surviving recovery path | No authorized signer can configure or exercise the required delegation. Configure scoped recovery while an administrator is available; a new key alone cannot restore access. | | Replacement not authorized | The guardian lacks ReplaceAuthority for the exact target role. Use the previously configured recovery role for that wallet and role ID. | | Hosted preparation unavailable | The Developer SDK has no working scoped-replacement method. Use a compatible protocol integration; compatibility types are not a recovery flow. | # x402 Source: https://build.onswig.com/developer-sdk/x402 ## Introduction x402 lets a Swig wallet pay for an HTTP resource that returns `402 Payment Required`. Use it for paid APIs and services whose facilitator supports Swig smart-wallet verification. The SDK prepares the payment; the resource provider’s facilitator verifies and settles it after the paid retry. Use the configured clients from [Client setup](/developer-sdk/integration-paths). `signTransaction` / `sign_transaction` is your application’s signing callback. Approve the exact recipient, mint, amount, and network before signing. ## SDK examples ### Pay for a resource This GET example preserves the resource URL and sends a payment header after signing. Keep the original method, body, and headers for other request types. ```typescript TypeScript theme={null} import { createX402Payment, } from '@swig-wallet/developer-sdk'; import { signPreparedTransaction } from '@swig-wallet/developer-sdk/signers'; const wallet = swig.wallets.use({ swigConfigAddress, walletAddress, requesterAuthority: { ed25519: { publicKey: developerPublicKey }, }, }); const challenge = await fetch(resourceUrl, { redirect: 'manual' }); const prepared = await wallet.x402.prepareFromResponse(challenge); const signed = await signPreparedTransaction( prepared.preparedTransaction, { signTransaction }, ); const payment = createX402Payment(prepared, signed); const paidResponse = await fetch(resourceUrl, { headers: payment.paymentSignatureHeaders, redirect: 'manual', }); if (!paidResponse.ok) { throw new Error(`Paid request failed: ${paidResponse.status}`); } const resource = await paidResponse.json(); const paymentResponse = paidResponse.headers.get('PAYMENT-RESPONSE'); ``` ```python Python theme={null} import asyncio import httpx from swig_developer_sdk import create_x402_payment from swig_developer_sdk.signers import sign_prepared_transaction wallet = swig.wallets.use( swig_config_address, requester_authority={ "ed25519": {"publicKey": developer_public_key}, }, ) async def main() -> None: async with httpx.AsyncClient(follow_redirects=False) as http: challenge = await http.get(resource_url) prepared = await wallet.x402.prepare_from_response(challenge) signed = await sign_prepared_transaction( prepared.prepared_transaction, sign_transaction=sign_transaction, ) payment = create_x402_payment(prepared, signed) paid_response = await http.get( resource_url, headers=payment.payment_signature_headers, ) paid_response.raise_for_status() resource = paid_response.json() payment_response = paid_response.headers.get("PAYMENT-RESPONSE") if __name__ == "__main__": asyncio.run(main()) ``` ```rust Rust theme={null} use reqwest::Client; use swig_developer_sdk::{ x402::{create_x402_payment, parse_payment_required}, PrepareX402PaymentArgs, WalletAuthority, }; let http = Client::builder() .redirect(reqwest::redirect::Policy::none()) .build()?; let challenge = http.get(&resource_url).send().await?; if challenge.status().is_redirection() { return Err("resource redirect requires a new payment flow".into()); } let payment_required = parse_payment_required(challenge.status(), challenge.headers())?; let prepared = wallet .prepare_x402_payment(PrepareX402PaymentArgs { swig_config_address, requester_authority: WalletAuthority::Ed25519 { public_key: requester_public_key, }, payment_required, accepted_index: None, }) .await?; let signed_transaction = sign_transaction(&prepared.prepared_transaction).await?; let payment = create_x402_payment( prepared.payment_required, prepared.accepted_index, signed_transaction, )?; let response = http .get(&resource_url) .headers(payment.payment_signature_headers) .send() .await?; if response.status().is_redirection() { return Err("resource redirected after payment submission".into()); } let paid_response = response.error_for_status()?; ``` ### Choose a payment offer Select an explicit zero-based offer index when the customer has approved that offer. Omit it to select the first supported offer on the wallet’s network. ```typescript TypeScript theme={null} const prepared = await wallet.x402.prepareFromResponse(challenge, { acceptedIndex: 2, }); ``` ```python Python theme={null} prepared = await wallet.x402.prepare_from_response( challenge, accepted_index=2, ) ``` ```rust Rust theme={null} use swig_developer_sdk::{PrepareX402PaymentArgs, WalletAuthority}; let prepared = wallet .prepare_x402_payment(PrepareX402PaymentArgs { swig_config_address, requester_authority: WalletAuthority::Ed25519 { public_key: requester_public_key, }, payment_required, accepted_index: Some(2), }) .await?; ``` ## Flow ```text theme={null} Request resource └─ Receive 402 challenge └─ Approve and sign └─ Paid retry └─ Settle ``` ## Input | Input | Requirement | | :- | :- | | Wallet and requester | Existing wallet with an Ed25519 or secp256r1 role allowed to invoke the token program and spend the mint. | | Challenge | x402 version 2 with the `exact` scheme on the wallet’s Solana mainnet/devnet network. Preserve the original `accepts` indexes. | | `acceptedIndex` / `accepted_index` | Optional index of the approved offer. An incompatible explicit choice errors rather than silently selecting another. | | Token accounts | Already-created canonical ATAs for the wallet and recipient. Wallet ATA must hold enough tokens. | | Token support | Legacy SPL Token or Token-2022 mint without extensions; token-account extensions may be absent or only `ImmutableOwner`. | | Fee payer | Use the offer’s fee payer, different from the requester. Leave its signature empty for facilitator settlement; sign only application-owned slots. | | Facilitator | Must support Swig verification; passkey payments also require its support for the secp256r1 verification program. | | Paid request | Original request plus `PAYMENT-SIGNATURE`. Disable redirects so payment headers are not forwarded to another destination. | ## Output `prepareFromResponse()` / `prepare_from_response()` returns these fields. Rust's `prepare_x402_payment` returns them as `X402PaymentPreparation`: | Field | Description | | :- | :- | | `preparedTransaction` / `prepared_transaction` | The unsigned Swig payment transaction and any embedded signature requests | | `paymentRequired` / `payment_required` | The validated x402 payment challenge used during preparation | | `acceptedIndex` / `accepted_index` | The selected offer's position in the original `accepts` array | Rust's `prepare_x402_payment` sends its POST once. This flow does not use the Swig paymaster. After signing, `createX402Payment()` / `create_x402_payment()` returns: | Field | Description | | :- | :- | | `paymentPayload` / `payment_payload` | The x402 payment payload containing the selected offer and signed transaction | | `paymentSignatureHeaders` / `payment_signature_headers` | A `PAYMENT-SIGNATURE` header ready to merge into the resource retry | Rust's `create_x402_payment` checks the selected offer, transaction structure, and encoded size limits (1,232 transaction bytes and 8,000 header bytes). It does not verify signatures or transaction intent. The facilitator verifies and settles the payment when the paid request reaches the resource provider. ## Errors | Error | Meaning | | :- | :- | | Invalid payment challenge | Expected HTTP 402 and a valid `PAYMENT-REQUIRED` header with supported version/scheme/network. | | Unsupported selected offer | The explicit index is out of range or names an incompatible offer. | | Account, permission, or token failure | Missing/unfunded ATA, unsupported Token-2022 extension, or insufficient role permission. | | Invalid signed payload | Transaction structure or encoded size is invalid. Rust limits transactions to 1,232 bytes and payment headers to 8,000 bytes. | | Failed or missing paid response | Settlement may already have happened. Reconcile with the resource service before paying again; the SDK does not reconcile automatically. | | Redirect | A different destination needs fresh approval and a new challenge. Preserve the previous payment outcome; do not forward its header. | # Yield deposit Source: https://build.onswig.com/developer-sdk/yield ## Introduction Stake SOL from a Swig wallet with an allowlisted validator. Use this flow to choose a validator, authorize a staking role, and deposit principal. TypeScript and Python support yield; Rust has no yield client. Use [configured clients](/developer-sdk/integration-paths) on the wallet’s network. Writes prepare unsigned transactions. [Sign](/developer-sdk/signers), submit, and confirm each transaction before its dependent step. ## SDK examples ### List yield options Choose an allowlisted validator that accepts new deposits. These examples use `swig` configured for the wallet’s network; TypeScript binds it once as `yieldClient`. Address variables are public keys. ```typescript TypeScript theme={null} const yieldClient = swig.yield.forWallet({ swigConfigAddress: swigConfigAddress, network: 'mainnet', }); const options = await yieldClient.listOptions(); const validator = options.find((option) => option.acceptsDeposits); if (!validator) throw new Error('No validator currently accepts deposits'); // validator.rate?.estimatedNetAprBps: 600 = 6% APR after commission ``` ```python Python theme={null} options = await swig.yields.list_options( network="mainnet", swig_config_address=swig_config_address, ) validator = next((option for option in options if option.accepts_deposits), None) if validator is None: raise ValueError("No validator currently accepts deposits") # If validator.rate is not None: # validator.rate.estimated_net_apr_bps: 600 = 6% APR after commission ``` ### Prepare a role that can stake Reuse a qualifying role or prepare a narrowly scoped role for your yield authority. ```typescript TypeScript theme={null} const role = await yieldClient.prepareRole({ feePayer: feePayer, yieldAuthority: { ed25519: { publicKey: agentKey } }, validatorVoteAddress: validator.voteAddress, maxDeposit: 10_000_000_000n, // Only needed to create a role. roleManagerAuthority: { ed25519: { publicKey: adminKey } }, }); if (role.type === 'create') { // Sign role.transaction with the role manager and fee payer, submit it, and // wait for confirmation. Then call prepareRole again without roleId. } ``` ```python Python theme={null} from swig_developer_sdk import PreparedYieldRoleCreation role = await swig.yields.prepare_role( network="mainnet", swig_config_address=swig_config_address, fee_payer=fee_payer, yield_authority={"ed25519": {"public_key": agent_key}}, validator_vote_address=validator.vote_address, max_deposit=10_000_000_000, role_manager_authority={"ed25519": {"public_key": admin_key}}, ) if isinstance(role, PreparedYieldRoleCreation): ... # sign, submit and confirm role.transaction, then call prepare_role again ``` A `create` result contains an unsigned AddRole transaction. Complete [signing](/developer-sdk/signers), submit, and confirm it before continuing. An `existing` result is ready to use. ### Deposit SOL Prepare a new position funded by the wallet. The fee payer supplies rent and fees. ```typescript TypeScript theme={null} const deposit = await yieldClient.deposit({ feePayer: feePayer, requesterAuthority: { ed25519: { publicKey: agentKey } }, amount: 5_000_000_000n, // principal, excluding rent and fees validatorVoteAddress: validator.voteAddress, positionSeed: positionSeed, }); // deposit.positionAddress, deposit.rentLamports (funded by the fee payer) ``` ```python Python theme={null} deposit = await swig.yields.deposit( network="mainnet", swig_config_address=swig_config_address, fee_payer=fee_payer, requester_authority={"ed25519": {"public_key": agent_key}}, amount=5_000_000_000, validator_vote_address=validator.vote_address, position_seed=position_seed, ) ``` Sign and submit `deposit.transaction`, then wait for confirmation. Keep the returned position address to track activation. ## Flow ```text theme={null} Choose validator └─ Authorize role └─ Deposit └─ Confirm ``` ## Input | Operation | Input | Requirement | | :- | :- | :- | | All | Wallet config and network | Use [Client setup](/developer-sdk/integration-paths). TypeScript uses `swig.yield`; Python uses `swig.yields`. Rust has no yield client. | | Write | `feePayer`, `requesterAuthority`, optional `roleId` | Public fee payer and authorized wallet authority. Python uses snake\_case names. Omit role ID to select the lowest capable role. | | Role | `yieldAuthority`, `maxDeposit`, `validatorVoteAddress` | Authority to grant access, positive lamport budget, and a validator accepting deposits. Optional `roleId` checks a specific candidate. | | Role creation | `roleManagerAuthority` | Ed25519 or secp256r1 authority with `All` or `ManageAuthority`; needed only when no reusable role exists. | | Deposit | `amount`, `positionSeed`, `validatorVoteAddress` | Positive principal in lamports, at least the network minimum. ASCII seed of 1–32 bytes; persist it for this attempt. Wallet retains its rent reserve. | `prepareRole` reuses `All` or `AllButManageAuthority`, or a role with System and Stake program access, a general SOL allowance covering `maxDeposit`, and `StakeAll`. A finite stake limit can authorize an individual operation but does not qualify for automatic reuse because withdrawals may include rewards. New roles receive exactly `Program(System)`, `Program(Stake)`, `SolLimit(maxDeposit)`, and `StakeAll`. `StakeAll` alone cannot invoke the Stake program; `ProgramCurated` does not cover it. Existing roles remain unchanged. ## Output | Operation | Field | Meaning | | :- | :- | :- | | Options | `voteAddress`, `name`, `acceptsDeposits`, optional `rate` | Allowlisted validators, including those closed to new deposits. Existing positions can exit while the validator remains allowlisted. | | Rate | `estimatedNetAprBps`, `commissionBps`, `lastUpdatedAt` | 600 APR basis points means 6% after commission. Observation time and rate may be absent; rates can change. | | Role | `type`, `roleId` or `transaction`, `actions` | `existing` identifies a qualifying role; `create` returns the AddRole transaction and exact new grants. | | Deposit | `transaction`, `positionAddress`, `delegatedLamports`, `rentLamports` | Unsigned deposit and the fee payer’s rent contribution. | ### Track the deposit Use [Yield position](/query/yield) to follow activation and earning balances, [Yield reward](/query/yield-rewards) for credited rewards, and [Yield withdrawal](/developer-sdk/yield-withdrawal) to exit and return funds. ## Errors | Error | Meaning | | :- | :- | | `INVALID_ARGUMENT` | Malformed input, unsupported validator, or invalid amount/seed. | | `NOT_FOUND` | The wallet is not owned by the API key’s organization. | | `PERMISSION_DENIED` | The selected role lacks program access, stake permission, or remaining SOL allowance; role creation needs a managing authority. | | `FAILED_PRECONDITION` | Insufficient funds, stake lockup, or an incompatible position state, including withdrawal before cooldown completes. | | `ALREADY_EXISTS` | The deposit or split seed identifies an existing account. Reconcile the earlier submission before choosing another seed. | | `UNAVAILABLE` | RPC, rate, or index data is temporarily unavailable. | # Yield withdrawal Source: https://build.onswig.com/developer-sdk/yield-withdrawal ## Introduction Exit a native staking position, wait for cooldown, then withdraw SOL to the Swig wallet. Use a full exit to close out the delegation, or a partial exit to keep part earning rewards. TypeScript and Python prepare these transactions. The acting role needs Stake program access and sufficient staking permission. Each example prepares a transaction; sign, submit, and confirm it before the next step. [Query positions](/query/yield) to check state between steps. ## SDK examples ### Exit a position TypeScript uses `yieldClient = swig.yield.forWallet({ swigConfigAddress, network: 'mainnet' })`; Python uses the configured `swig` client and `swig_config_address`. Prepare deactivation of the whole position. Withdrawal becomes available after cooldown. ```typescript TypeScript theme={null} const exit = await yieldClient.exit({ feePayer, requesterAuthority: { ed25519: { publicKey: agentKey } }, positionAddress, amount: 'all', }); // exit.exitingPositionAddress is the position entering cooldown ``` ```python Python theme={null} exit = await swig.yields.exit( network="mainnet", swig_config_address=swig_config_address, fee_payer=fee_payer, requester_authority={"ed25519": {"public_key": agent_key}}, position_address=position_address, amount="all", ) ``` ### Exit part of a position Split a fully active position and deactivate the split. Both parts must meet the network’s minimum delegation. ```typescript TypeScript theme={null} const partialExit = await yieldClient.exit({ feePayer, requesterAuthority: { ed25519: { publicKey: agentKey } }, positionAddress, amount: { lamports: 2_000_000_000n, positionSeed: exitSeed }, }); ``` ```python Python theme={null} from swig_developer_sdk import PartialYieldExit partial_exit = await swig.yields.exit( network="mainnet", swig_config_address=swig_config_address, fee_payer=fee_payer, requester_authority={"ed25519": {"public_key": agent_key}}, position_address=position_address, amount=PartialYieldExit(lamports=2_000_000_000, position_seed=exit_seed), ) ``` Submit and confirm `partialExit.transaction` / `partial_exit.transaction`. Track its `exitingPositionAddress` / `exiting_position_address` during cooldown. ### Withdraw a position After the exiting position becomes inactive, return its SOL above the rent reserve to the wallet. ```typescript TypeScript theme={null} const withdrawal = await yieldClient.withdraw({ feePayer, requesterAuthority: { ed25519: { publicKey: agentKey } }, positionAddress: exit.exitingPositionAddress, }); // withdrawal.withdrawalLamports, withdrawal.destinationWalletAddress ``` ```python Python theme={null} withdrawal = await swig.yields.withdraw( network="mainnet", swig_config_address=swig_config_address, fee_payer=fee_payer, requester_authority={"ed25519": {"public_key": agent_key}}, position_address=exit.exiting_position_address, ) ``` Sign, submit, and confirm `withdrawal.transaction`. The returned `withdrawalLamports` / `withdrawal_lamports` is the amount this transaction returns; the rent reserve remains in the stake account. ## Flow ```text theme={null} Exit position ├─ Full: deactivate └─ Partial: split └─ Deactivate Wait for cooldown └─ Withdraw above rent ``` ## Input | Operation | Input | Requirement | | :- | :- | :- | | All | Wallet config and network | Use [Client setup](/developer-sdk/integration-paths). TypeScript uses `swig.yield`; Python uses `swig.yields`. Rust has no yield client. | | Write | `feePayer`, `requesterAuthority`, optional `roleId` | Public fee payer and authorized wallet authority. Python uses snake\_case names. Omit role ID to select the lowest capable role. | | Exit | `positionAddress`, `amount` | Use `all`, or a lamport amount and fresh split seed for a fully active position. Fee payer funds split-account rent. | | Withdrawal | `positionAddress` | Inactive position with withdrawable balance. Use the exiting position address returned by full or partial exit. | ## Output | Operation | Field | Meaning | | :- | :- | :- | | Exit | `transaction`, `exitingPositionAddress`, `deactivatingLamports`, `additionalRentLamports` | Original or split position entering cooldown, plus any new rent. | | Withdrawal | `transaction`, `withdrawalLamports`, `destinationWalletAddress` | Exact planned return above rent to the Swig wallet. | TypeScript fields are shown; Python uses snake\_case. Returned lamport amounts are exact decimal strings. Indexed withdrawable amounts may include rent, but the prepared withdrawal keeps the rent reserve. ## Errors | Error | Meaning | | :- | :- | | `INVALID_ARGUMENT` | Malformed input, unsupported validator, or invalid amount/seed. | | `NOT_FOUND` | The wallet is not owned by the API key’s organization. | | `PERMISSION_DENIED` | The selected role lacks program access, stake permission, or remaining SOL allowance; role creation needs a managing authority. | | `FAILED_PRECONDITION` | Insufficient funds, stake lockup, or an incompatible position state, including withdrawal before cooldown completes. | | `ALREADY_EXISTS` | The deposit or split seed identifies an existing account. Reconcile the earlier submission before choosing another seed. | | `UNAVAILABLE` | RPC, rate, or index data is temporarily unavailable. | # Add a role Source: https://build.onswig.com/evm/add-role Grant a delegate a native-currency spending allowance. ## Introduction Adding a role pairs a new authority with the permissions it may use on an existing wallet. * **Use when:** another signer needs limited access to wallet assets. * **For:** apps delegating spending to a user, service, or automation. ## How it works 1. Connect the signer for a role with authority-management permission. 2. Encode the new authority and a permission set for its task. 3. Submit `addRole` and wait for a successful receipt. 4. Read the assigned role ID from `RoleAdded` and retain it for later operations. ## Role fields | Field | Type | Meaning | | - | - | - | | `managerRoleId` | Integer | Existing role approving the addition | | `delegate` | Address | EOA that will authorize the new role | | `amount` | Integer, wei | Total native-currency allowance | | `roleId` | Integer | New ID returned by the confirmed event | A fixed allowance decreases with successful spending; it is not a per-transaction limit or a deposit. Amounts fit `uint64`. Fund the wallet's vault separately. ## SDK example This creates a native-currency spending role without role-management permission. The connected manager pays gas. Supply `100n` for a total allowance of 100 wei. ```typescript theme={null} import { type Address, type LocalAccount, createPublicClient, createWalletClient, getAddress, http, parseEventLogs, } from "viem"; import { encodeAuthority, encodePermission, getSwigConfig, swigConfigAbi, } from "../src/index.js"; export async function addSpendingRole( rpcUrl: string, manager: LocalAccount, accountAddress: Address, managerRoleId: number, delegate: Address, amount: bigint, ) { const client = createPublicClient({ transport: http(rpcUrl) }); const wallet = createWalletClient({ account: manager, transport: http(rpcUrl) }); const config = getSwigConfig(accountAddress, { public: client, wallet }); const authority = encodeAuthority({ type: "secp256k1", address: delegate }); const hash = await config.write.addRole([ managerRoleId, authority.authorityType, authority.key, authority.keyExtra, [encodePermission({ type: "nativeLimit", amount })], ], { chain: null }); const receipt = await client.waitForTransactionReceipt({ hash }); if (receipt.status !== "success") throw new Error("Role creation failed"); const [event] = parseEventLogs({ abi: swigConfigAbi, eventName: "RoleAdded", logs: receipt.logs.filter((log) => getAddress(log.address) === getAddress(accountAddress)), }); if (!event) throw new Error("RoleAdded event missing"); return { roleId: event.args.roleId, transactionHash: hash }; } ``` Use the confirmed ID, not a predicted counter. [Read the role](/evm/read-role) to verify its authority and permissions before using the delegate. Complete examples: [TypeScript](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/typescript/examples/add-role.ts), [Rust](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/rust/examples/add_role.rs), [Python](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/python/examples/add_role.py). # Bundler compatibility Source: https://build.onswig.com/evm/bundler-compatibility Choose a bundler that accepts your deployed Swig account. ## Introduction Bundler compatibility determines whether a provider can admit and execute sponsored operations for your Swig deployment. * **Use when:** you are enabling sponsorship or changing the provider for an existing account. * **For:** app integrators coordinating account support with their bundler operator. ## How it works 1. Confirm support for the chain, canonical EntryPoint v0.9, and your Swig account implementation. 2. Have the operator register the account under its supported validation policy. 3. Check the endpoint's EntryPoint list, then verify an actual sponsored operation in your environment. 4. During fleet upgrades, coordinate pending operations and prepare fresh authorizations afterward. ## Compatibility checks | Check | Meaning | | - | - | | EntryPoint | Endpoint lists v0.9; necessary but not proof of account acceptance | | Account validation | Provider supports Swig's shared-beacon account architecture | | Registration | Your specific config address is admitted by that provider | | Sponsorship | Paymaster accepts the account, operation, chain, and EntryPoint | Swig's shared beacon enables fleet upgrades without individual wallet upgrades. It also requires a compatible bundler policy. The SDK's tested Rundler configuration uses an explicit account-scoped validation exception; support by a hosted provider must be confirmed separately. A successful local SDK test does not establish public-mempool acceptance. ## SDK example Check the EntryPoints exposed by a proposed endpoint using the Viem dependency from [Environment setup](/evm/setup): ```typescript theme={null} import { createBundlerClient, entryPoint09Address } from "viem/account-abstraction"; import { http, isAddressEqual } from "viem"; export async function checkEntryPoint(bundlerUrl: string) { const bundler = createBundlerClient({ transport: http(bundlerUrl) }); const entryPoints = await bundler.getSupportedEntryPoints(); return { entryPoints, supportsV09: entryPoints.some((address) => isAddressEqual(address, entryPoint09Address)), }; } ``` Then run the [sponsored transfer flow](/evm/send-sponsored-transfer) against your admitted account and check the operation result. ### During an upgrade * Pause new submissions while the operator handles affected pending operations. * A queued operation may become invalid when the shared implementation changes. * Once the operator confirms readiness, prepare and sign fresh operations against current state. * Check the original operation's status before retrying; the SDK does not automatically manage provider registration or reputation. # Create a wallet Source: https://build.onswig.com/evm/create-wallet Create a wallet with an owner and fund its asset vault. ## Introduction Wallet creation deploys a config and vault with an initial authority and permissions. * **Use when:** a user or application needs a new wallet on your selected EVM deployment. * **For:** onboarding flows using a compatible Swig factory. ## How it works 1. Encode the root authority and give it `All` permission. 2. Choose a public wallet identifier and salt, then predict the config address. 3. Submit factory deployment with any initial vault funding. 4. Confirm the receipt and read the config and vault addresses from `SwigDeployed`. ## Inputs and result | Field | Type | Meaning | | - | - | - | | `factoryAddress` | Address | Compatible Swig factory | | `walletName` | String | Public value hashed into the wallet ID and salt in this example | | `initialBalance` | Integer, wei | Native currency deposited into the new vault | | `accountAddress` | Address | Returned config address for reads and transactions | | `vaultAddress` | Address | Returned asset-holding address | | `transactionHash` | Hash | Confirmed creation transaction | Reusing the same name and root settings targets the same address; deploying it twice reverts. The signer pays initial funding and transaction gas. ## SDK example Supply a Viem `LocalAccount`, RPC URL, and factory address after [Environment setup](/evm/setup). ```typescript theme={null} import { type Address, type LocalAccount, createPublicClient, createWalletClient, getAddress, http, keccak256, parseEventLogs, toBytes, } from "viem"; import { encodeAuthority, encodePermission, getSwigConfigFactory, swigConfigFactoryAbi, } from "../src/index.js"; export async function createWallet( rpcUrl: string, signer: LocalAccount, factoryAddress: Address, walletName: string, initialBalance: bigint, ) { const client = createPublicClient({ transport: http(rpcUrl) }); const wallet = createWalletClient({ account: signer, transport: http(rpcUrl) }); const factory = getSwigConfigFactory(factoryAddress, { public: client, wallet }); const authority = encodeAuthority({ type: "secp256k1", address: signer.address }); const id = keccak256(toBytes(walletName)); const args = [ id, id, authority.authorityType, authority.key, authority.keyExtra, [encodePermission({ type: "all" })], ] as const; const predicted = await factory.read.computeConfigAddress(args); const hash = await factory.write.deploy(args, { chain: null, value: initialBalance }); const receipt = await client.waitForTransactionReceipt({ hash }); if (receipt.status !== "success") throw new Error("Wallet creation failed"); const [event] = parseEventLogs({ abi: swigConfigFactoryAbi, eventName: "SwigDeployed", logs: receipt.logs.filter((log) => getAddress(log.address) === getAddress(factoryAddress)), }); if (!event || getAddress(event.args.config) !== getAddress(predicted)) { throw new Error("Wallet deployment did not match the predicted address"); } return { accountAddress: event.args.config, vaultAddress: event.args.vault, transactionHash: hash, }; } ``` Store the account address for [adding roles](/evm/add-role). Send later asset deposits to the vault address. Complete examples: [TypeScript](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/typescript/examples/create-wallet.ts), [Rust](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/rust/examples/create_wallet.rs), [Python](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/python/examples/create_wallet.py). # EVM Protocol SDK Source: https://build.onswig.com/evm/index Create wallets, assign roles, and execute direct or sponsored transactions. ## Introduction The EVM Protocol SDK connects your application to Swig wallets through your own RPC connection and signing keys. * **Use when:** you need direct control of wallet creation, permissions, and transaction execution. * **For:** app developers integrating a compatible EVM deployment in TypeScript, Rust, or Python. ## How it works 1. Connect to a compatible deployment and choose an application signer. 2. Create a wallet with a root authority, then fund its vault. 3. Add roles with permissions for the tasks their signers need. 4. Execute through the wallet config and check the transaction or UserOperation result. ## Wallet structure | Concept | Purpose | | - | - | | Account / config | Holds roles and receives wallet execution requests | | Vault | Holds the assets the wallet spends | | Authority | Identifies who may approve a role's operations | | Permission | Sets a role's capabilities and spending allowance | | Role ID | Selects the authority and permissions used for an operation | ## Execution paths | Path | Authorization | Gas payer | | - | - | - | | [Direct transfer](/evm/send-transfer) | Role's EOA sends a transaction | That EOA | | [Sponsored transfer](/evm/send-sponsored-transfer) | Role signs a UserOperation | Paymaster through a compatible bundler | Both paths spend assets from the vault and enforce the selected role's permissions. ## SDK example The EVM SDKs are currently consumed from source. Obtain the repository first: ```bash theme={null} git clone https://github.com/anagrambuild/swig-protocol-sdk.git cd swig-protocol-sdk ``` Then install the language you use: ```bash TypeScript theme={null} cd evm/typescript bun install --frozen-lockfile ``` ```bash Rust theme={null} cd evm cargo build --locked -p swig-evm --examples ``` ```bash Python theme={null} cd evm/python uv sync --locked ``` Start with [Environment setup](/evm/setup), then [create a wallet](/evm/create-wallet). The examples use Secp256k1 authorities; sponsored operations require an already deployed account, EntryPoint v0.9, and a compatible provider. # Read a role Source: https://build.onswig.com/evm/read-role Read an authority and decode its current permissions. ## Introduction Reading a role shows who may authorize it and which permissions are attached. * **Use when:** you need to display access, choose a signer, or inspect a remaining allowance. * **For:** wallet settings screens and transaction-preparation flows. ## How it works 1. Connect a public RPC client to the wallet config address. 2. Read `getRole` for the on-chain role ID and decode the result. 3. Use its action count to read and decode each permission. 4. Use the resulting fields to explain the role's current access. ## Returned structure | Field | Type | Meaning | | - | - | - | | `id` | Integer | Role ID | | `authority` | Object | Authority type and signer information | | `actionCount` | Integer | Number of attached permissions | | `permissions` | List | Decoded permissions read separately by the example | A native-limit permission contains `type: "nativeLimit"` and `amount`, its remaining allowance in wei. Recurring permissions contain the allowance, window, last reset, and current amount. EVM recurring windows use timestamp seconds. ## SDK example This is a read-only operation: no signer or gas is required. ```typescript theme={null} import { type Address, createPublicClient, http } from "viem"; import { decodePermission, decodeRole, getSwigConfig } from "../src/index.js"; export async function readRole(rpcUrl: string, accountAddress: Address, roleId: number) { const client = createPublicClient({ transport: http(rpcUrl) }); const config = getSwigConfig(accountAddress, client); const role = decodeRole(await config.read.getRole([roleId])); const permissions = await Promise.all( Array.from({ length: role.actionCount }, async (_, index) => decodePermission(await config.read.getAction([roleId, index])), ), ); return { ...role, permissions }; } ``` Illustrative structure for a delegate that has spent 7 of its 100 wei allowance: ```typescript theme={null} const exampleRole = { id: 1, authority: { type: "secp256k1", address: "0x1111111111111111111111111111111111111111", }, actionCount: 1, permissions: [{ type: "nativeLimit", amount: 93n }], }; ``` The repository's [TypeScript](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/typescript/examples/read-role.ts), [Rust](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/rust/examples/read_role.rs), and [Python](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/python/examples/read_role.py) examples read the authority and action count. The example above also fetches each permission. # Send a sponsored transfer Source: https://build.onswig.com/evm/send-sponsored-transfer Authorize a vault transfer while a paymaster pays gas. ## Introduction A sponsored transfer packages the wallet action as a signed UserOperation for a bundler and paymaster. * **Use when:** users should spend wallet assets without holding native currency in their signing EOA for gas. * **For:** apps with an already deployed Swig account and a compatible sponsorship provider. ## How it works 1. Connect the role signer to `toSwigSmartAccount` with an explicit validity window. 2. Connect the bundler and ERC-7677 paymaster clients. 3. Send one call through the smart-account adapter; the selected role's permissions still apply. 4. Check the UserOperation's success result and containing transaction hash. ## Requirements | Item | Requirement | | - | - | | Account | Already deployed and registered with a compatible bundler | | EntryPoint | Canonical v0.9 configured on the wallet | | Authority | Secp256k1 role or active Secp256k1 session | | Sponsor | Paymaster endpoint supporting the account, chain, and EntryPoint | | Transfer | One call; sufficient vault funds and role allowance | The current adapter requires sponsorship and does not deploy accounts inside the operation. Confirm [bundler compatibility](/evm/bundler-compatibility) before using a hosted endpoint. ## Flow ```text theme={null} Role signs ↓ Bundler submits ↓ EntryPoint validates ├─ Paymaster pays gas └─ Wallet executes ``` ## SDK example After [Environment setup](/evm/setup), supply the chain, endpoints, role signer, and deployed account. The selected role must allow this native transfer to an EOA recipient with no code. ```typescript theme={null} import { type Address, type Chain, type LocalAccount, createPublicClient, http, } from "viem"; import { createBundlerClient, createPaymasterClient } from "viem/account-abstraction"; import { toSwigSmartAccount } from "../src/index.js"; export async function sendSponsoredTransfer( chain: Chain, rpcUrl: string, bundlerUrl: string, paymasterUrl: string, signer: LocalAccount, accountAddress: Address, roleId: number, recipient: Address, amount: bigint, ) { const client = createPublicClient({ chain, transport: http(rpcUrl) }); const account = await toSwigSmartAccount({ client, address: accountAddress, roleId, signer, validAfter: 0, validUntil: Number((await client.getBlock()).timestamp) + 600, }); const bundler = createBundlerClient({ account, client, transport: http(bundlerUrl), paymaster: createPaymasterClient({ transport: http(paymasterUrl) }), }); const fees = await client.estimateFeesPerGas(); const hash = await bundler.sendUserOperation({ calls: [{ to: recipient, value: amount }], ...fees, verificationGasLimit: 200_000n, }); const receipt = await bundler.waitForUserOperationReceipt({ hash }); if (!receipt.success) throw new Error("UserOperation execution failed"); return { userOperationHash: hash, transactionHash: receipt.receipt.transactionHash }; } ``` * Size gas limits for your deployment and operation; this example uses the SDK example's verification limit. * Inclusion does not guarantee execution success. A failed included operation can still consume a nonce and charge the sponsor. * Obtain fresh sponsorship and authorization when rebuilding an expired operation. * The Viem and [permissionless.js example](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/typescript/examples/send-sponsored-transfer-permissionless.ts) use the same Swig adapter. * The [Rust](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/rust/examples/send_sponsored_transfer.rs) and [Python](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/python/examples/send_sponsored_transfer.py) examples use a local fixture sponsor. Hosted use requires the provider's fee and sponsorship data before signing. # Send a transfer Source: https://build.onswig.com/evm/send-transfer Send native currency from the vault with the role signer paying gas. ## Introduction A direct transfer spends from the wallet vault while the authorized EOA submits the transaction and pays gas. * **Use when:** you want a simple native-currency payment without a bundler or paymaster. * **For:** apps using a Secp256k1 role with a native spending allowance. ## How it works 1. Connect the EOA authorized by the selected role. 2. Choose an EOA recipient with no deployed code and an amount within the remaining allowance. 3. Call `signV2` on the config with no calldata and direct-caller authorization. 4. Wait for a successful receipt before treating the payment as complete. ## Transfer fields | Field | Type | Meaning | | - | - | - | | `accountAddress` | Address | Wallet config receiving the execution request | | `roleId` | Integer | Role that authorizes the spend | | `recipient` | Address | Receiving EOA | | `amount` | Integer, wei | Native currency taken from the vault | | `transactionHash` | Hash | Submitted transaction | The vault needs the transfer amount. The signer needs gas separately. A 7-wei payment from a 100-wei fixed allowance leaves 93 wei. ## SDK example Use the delegate from [Add a role](/evm/add-role). The two `"0x"` arguments mean empty call data and direct EOA authorization; the connected sender must be the role's authority. ```typescript theme={null} import { type Address, type LocalAccount, createPublicClient, createWalletClient, http, } from "viem"; import { getSwigConfig } from "../src/index.js"; export async function sendTransfer( rpcUrl: string, signer: LocalAccount, accountAddress: Address, roleId: number, recipient: Address, amount: bigint, ) { const client = createPublicClient({ transport: http(rpcUrl) }); const wallet = createWalletClient({ account: signer, transport: http(rpcUrl) }); const config = getSwigConfig(accountAddress, { public: client, wallet }); const hash = await config.write.signV2( [roleId, recipient, amount, "0x", "0x"], { chain: null }, ); const receipt = await client.waitForTransactionReceipt({ hash }); if (receipt.status !== "success") throw new Error("Transfer failed"); return { transactionHash: hash }; } ``` * The outer transaction sends no value; the amount comes from the vault. * If an included transaction reverts, asset movement and allowance changes revert, while gas is still charged. * Use [Sponsored transfers](/evm/send-sponsored-transfer) when a paymaster should pay gas. Complete examples: [TypeScript](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/typescript/examples/send-transfer.ts), [Rust](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/rust/examples/send_transfer.rs), [Python](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/python/examples/send_transfer.py). # Environment setup Source: https://build.onswig.com/evm/setup Connect the Protocol SDK to a compatible EVM deployment. ## Introduction Environment setup supplies the RPC connection, deployment addresses, and signer used by the SDK examples. * **Use when:** you are connecting an application to Swig for the first time or changing networks. * **For:** developers consuming the source-available EVM SDK. ## How it works 1. Install your language SDK from [Overview](/evm#sdk-example). 2. Obtain the network RPC and a compatible factory address from your deployment operator. 3. Create a read client and, for writes, connect an application-owned signer. 4. Use the config address for wallet operations and the vault address for asset balances. ## Configuration | Value | Type | Purpose | | - | - | - | | RPC URL | URL | Read chain state and submit direct transactions | | Factory address | Address | Create wallets using the matching deployment | | Account address | Address | Read and execute through an existing wallet config | | Signer | Account | Authorize writes; fund its EOA for direct transaction gas | | Chain | Chain configuration | Select the same network as the RPC and deployment | Obtain deployment details from your operator or [contact Swig](/links-and-contact). Match the SDK's [contract revision](https://github.com/anagrambuild/swig-protocol-sdk/blob/718f343/evm/abi/source.json); these guides do not assume a public factory address. ## SDK example The TypeScript examples use Viem and import the source SDK from `../src/index.js`. Save example files under `evm/typescript/examples` in the checkout and run them with `bun run examples/.ts`. Create clients from an existing signer; keep its key management in your application: ```typescript theme={null} import { type Chain, type LocalAccount, createPublicClient, createWalletClient, http, } from "viem"; export function connect(rpcUrl: string, chain: Chain, signer: LocalAccount) { const transport = http(rpcUrl); return { client: createPublicClient({ chain, transport }), wallet: createWalletClient({ chain, transport, account: signer }), }; } ``` * Read-only calls need only the public client. * Direct writes need gas in the signer's EOA. Funding the vault does not fund that EOA. * Sponsored writes additionally need a compatible bundler and paymaster; follow [Sponsored transfers](/evm/send-sponsored-transfer). # API key Source: https://build.onswig.com/examples/dev-portal/create-api-key ## Introduction An API key authenticates your server to Swig’s hosted services and attributes usage to your organization. Use it for Developer SDK queries and preparation. Wallet authority signatures are still required for writes. Create a key in **API Keys** in the [Developer Portal](https://dashboard.onswig.com/). Copy its secret when shown and store it in server configuration; keep it out of browser bundles. ## SDK examples ### Use the key Read the stored secret when constructing the client. Replace a revoked key in the same server configuration. ```typescript TypeScript theme={null} import { SwigClient } from '@swig-wallet/developer-sdk'; const apiKey = process.env.SWIG_API_KEY; if (!apiKey) throw new Error('SWIG_API_KEY is required'); const swig = new SwigClient({ apiKey, network: 'devnet', }); ``` ```python Python theme={null} import os from swig_developer_sdk import SwigClient swig = SwigClient( api_key=os.environ["SWIG_API_KEY"], network="devnet", ) ``` ```rust Rust theme={null} use std::env; use swig_developer_sdk::{ClientConfig, Network, PaymasterClient, WalletClient}; let config = ClientConfig::new(env::var("SWIG_API_KEY")?, Network::Devnet); let wallet = WalletClient::new(config.clone())?; let paymaster = PaymasterClient::new(config.clone())?; ``` ## Input | Input | Requirement | | :- | :- | | Key name | A descriptive name for the server/integration. | | Expiration | Optional expiration selected at creation; expired keys cannot authenticate. | | `SWIG_API_KEY` | The full secret, available when the key is created. Keep it in the runtime making hosted calls. | ## Errors | Error | Meaning | | :- | :- | | Missing key | The server configuration has no API key; client setup cannot complete. | | Authentication failed | The key is invalid, expired, or revoked. | | Access denied | The authenticated organization cannot access the requested wallet or resource. | | Quota exhausted | The organization’s admission cap is reached; [Pricing & quotas](/query) defines its allowances. | # Policy template Source: https://build.onswig.com/examples/dev-portal/create-policy Save reusable configuration for new Swig wallets. ## Introduction A policy template stores the initial authority and actions used when creating a wallet. Use it when your application creates many wallets with the same setup. The Developer Portal calls this **Wallet templates**. A template is saved configuration. Editing it does not change permissions on an existing wallet; use [Role](/developer-sdk/add-roles-and-permissions) for that. ## SDK examples ### Create a wallet from a template Template creation is a portal action. Use the saved policy ID with the SDK to prepare a wallet. This example assumes the template asks for an Ed25519 initial user. Omit that authority when the template already supplies it. ```typescript TypeScript theme={null} const created = await swig.wallets.create({ feePayer, policyId, initialUser: { ed25519: { publicKey: userPublicKey } }, }); ``` ```python Python theme={null} created = await swig.wallets.create( fee_payer=fee_payer, policy_id=policy_id, initial_user={"ed25519": {"publicKey": user_public_key}}, ) ``` ```rust Rust theme={null} use swig_developer_sdk::{PrepareCreateWalletArgs, WalletAuthority}; let created = wallet.prepare_create_wallet(PrepareCreateWalletArgs { fee_payer, policy_id: Some(policy_id), initial_user: Some(WalletAuthority::Ed25519 { public_key: user_public_key, }), }).await?; ``` Use the clients from [Client setup](/developer-sdk/integration-paths). [Sign and submit the creation plan](/developer-sdk/create-wallets), then add each additional role and verify its confirmed permissions. To inspect saved template metadata, use [Fetch template](/examples/dev-portal/fetch-policy). ### Inspect the template Fetch saved metadata to verify the template selected by your application. ```typescript TypeScript theme={null} const template = await swig.wallets.getPolicy(policyId); ``` ```python Python theme={null} template = await swig.wallets.get_policy(policy_id) ``` ```rust Rust theme={null} let template = wallet.get_policy(&policy_id).await?; ``` ## Input | Field | Required | Description | | :- | :- | :- | | Name | Yes | Identifies the template | | Description | No | Explains its purpose | | Initial authority | Yes, now or at wallet creation | Choose the public-key type; save a key or let the application supply it later | | Additional user | No | Public key and at least one allowed action; provision this role separately after wallet creation | The portal gives the initial user full root access (`All`). Its form does not provide an initial-user spending-limit editor. Additional users saved in the template are **not automatically added** by Developer SDK wallet creation. Open **Wallet templates** in the [Developer Portal](https://dashboard.onswig.com), select **New template**, enter the fields above, and save the policy ID. Recovery-guardian setup in that form is currently unavailable; see [Guardian recovery](/developer-sdk/use-cases/guardian-recovery). ## Errors | Error | Meaning | | :- | :- | | Template lookup is denied or missing | The policy ID is unavailable to the server API key. Check the ID and resource access using Fetch template. | | Initial authority missing at creation | The template expects the application to supply its key. Set initialUser / initial\_user when preparing the wallet. | | Additional role absent after creation | Stored additional users are not provisioned by template-based creation. Add each role after wallet creation confirms, then inspect its permissions. | # Fetch template Source: https://build.onswig.com/examples/dev-portal/fetch-policy Inspect saved wallet-creation policy metadata. ## Introduction A policy lookup returns the authority and action configuration saved for wallet creation. Use it to inspect a template before creating a wallet or displaying its setup in your application. It describes saved metadata, not a wallet's current on-chain permissions. TypeScript, Python, and Rust expose this lookup. Your API key must have access to the template; a wallet signature is not required. ## SDK examples ### Fetch a saved template Use the server client from [Client setup](/developer-sdk/integration-paths). ```typescript TypeScript theme={null} const policy = await swig.wallets.getPolicy(policyId); ``` ```python Python theme={null} policy = await swig.wallets.get_policy(policy_id) ``` ```rust Rust theme={null} let policy = wallet.get_policy(&policy_id).await?; ``` Pass the ID into [Create a wallet](/developer-sdk/create-wallets) when ready. Use the [role list](/developer-sdk/add-roles-and-permissions#confirm-the-role) to inspect permissions already on-chain. ### Inspect the saved actions Display the template’s saved grants before creation. On-chain grants are queried separately through the Role page. ```typescript TypeScript theme={null} for (const action of policy.actions ?? []) { console.log(action); } ``` ```python Python theme={null} for action in policy.actions: print(action) ``` ```rust Rust theme={null} for action in &policy.actions { if let swig_developer_sdk::WalletPermission::SolLimit { amount } = action { println!("Saved SOL allowance: {amount} lamports"); } } ``` ## Input | Parameter | Required | Description | | :- | :- | :- | | `policyId` / `policy_id` | Yes | ID saved when [creating the template](/examples/dev-portal/create-policy) | | API key | Client setting | Server credential with access to the template | ## Output TypeScript names are shown below. Python exposes a `Policy` object with snake\_case top-level fields. | Field | Type | Meaning | | :- | :- | :- | | `id`, `name` | string | Template identifier and display name | | `description` | string or null | Saved description | | `authority` | object, null, or absent | Stored initial authority; your application supplies one when the template requires it | | `actions` | array, optional | Saved action data for the initial user | | `initialKeySource` | string, optional | Whether the initial key is stored or supplied at creation | | `guardianEnabled`, `guardianAuthority`, `guardianKeySource`, `guardianDelaySeconds` | Optional compatibility fields | Retained recovery metadata; presence does not establish an available recovery flow | This lookup does not return additional users saved in the portal. Store the configuration needed to provision those roles in your application. Saved actions use stored names and shapes; map them to typed [permission](/developer-sdk/permissions) inputs when adding a role rather than forwarding them unchanged. Rust returns typed `WalletAuthority` and `WalletPermission` values. Its `description` is a string and guardian fields are concrete compatibility metadata. An unknown policy returns `GetPolicyError::PolicyNotFound`. ## Errors | Error | Meaning | | :- | :- | | 401 or 403 | The API key is invalid or lacks access. Check the server key and its resource access. | | 404 | The policy ID is not found or is not visible to the caller. Confirm the saved policy ID and organization access. | # Choose an Auth Method Source: https://build.onswig.com/idp-sdk/auth-methods The IDP SDK supports three end-user sign-in channels, but not every channel is exposed the same way on every platform. ## OAuth Use OAuth when users should sign in with a provider such as Google or another configured IdP. * available in Expo / React Native through `startOAuth()` * available in browser apps through `createSwigWebClient()` and `redirectToOAuth()` * supports provider discovery through `listProviders({ clientId })` ## Email OTP Use email OTP when users should verify ownership of an email address without a separate OAuth provider flow. * available in Expo / React Native through `startEmailOtp()` * the user enters the address and verification code inside the isolated host * the host app does not receive the email address, OTP code, or callback JWT ## SMS OTP Use SMS OTP when users should verify ownership of a phone number. * available in Expo / React Native through `startSmsOtp()` * the user enters the phone number and verification code inside the isolated host * the host app does not receive the phone number, OTP code, or callback JWT ## Inputs you will see most often Most auth starts are built around: * `clientId` * `policyId` * `provider` * `flow` Most product flows use `flow: "role"` because the resulting callback carries the Swig wallet and role context. The web start API also exposes `flow: "session"`, but the primary documented path here is role-based auth. # Authority and Agent Flows Source: https://build.onswig.com/idp-sdk/authority-and-agents The browser client also includes helpers for authority-management flows that go beyond basic sign-in. ## Add an authority to a role Use: * `getAddAuthorityStartUrl()` * `redirectToAddAuthority()` These start the same isolated-host redirect pattern, but the goal is to add an authority to a Swig role instead of starting a plain user sign-in flow. ## Revoke an agent role Use: * `getRevokeAgentStartUrl()` * `redirectToRevokeAgent()` * `completeAgentRevokeFromUrl()` The revoke flow is a direct isolated-host action. It does not begin with a new provider-auth redirect. ## Inspect or update agents Use: * `listAgents()` * `updateAgentReputation()` These methods let a browser app inspect the configured agents on a Swig config and update agent reputation metadata through the backend API. ## When to use this page Use these helpers when your app needs identity-linked authority management in addition to basic login. # Expo and React Native Apps Source: https://build.onswig.com/idp-sdk/expo-and-react-native For mobile apps, the IDP SDK is a provider plus hook API. ## Main integration surface Use: * `SwigIdpProvider` * `useSwigIdp()` The hook exposes: * `startOAuth()` * `startEmailOtp()` * `startSmsOtp()` * `listProviders()` * `getSession()` * `logout()` ## Basic shape ```tsx TypeScript theme={null} import { Button } from "react-native"; import { SwigIdpProvider, useSwigIdp } from "@swig-wallet/expo-idp-sdk"; function LoginButton() { const { startOAuth, authPhase } = useSwigIdp(); return (