Skip to main content
Version: Current

Linking Accounts

If you’ve built dApps on Flow, or any blockchain for that matter, you’re painfully aware of the user onboarding process and successive pain of prompting user signatures for on-chain interactions.

As a developer, this leaves you with two options - handle custody and act on the user's behalf or go with the self-custodial status quo, hope your new users are Web3 native and authenticate them via their existing wallet. Either choice will force significant compromise, fragmenting user experience and leaving much to be desired compared to the broader status quo of Web2 identity authentication and single-click onboarding flow.

In this doc, we’ll dive into a progressive onboarding flow, including the Cadence scripts & transactions that go into its implementation in your dApp. These components will enable any implementing dApp to create a custodial account, mediate the user’s on-chain actions on their behalf, and later delegate access of that dApp-created account to the user’s wallet. We’ll refer to this custodial pattern as the Hybrid Account Model and the process of delegating control of the dApp account as Account Linking.

danger

Note that the documentation on Hybrid Custody covers the current state and will likely differ from the final implementation. Builders should be aware that breaking changes may follow before reaching a final community consensus on implementation. Interested in shaping the conversation? Join in!.

Objectives

  • Create a walletless onboarding transaction
  • Link an existing app account as a child to a newly authenticated parent account
  • Get your dApp to recognize “parent” accounts along with any associated “child” accounts
  • Put it all together to create a blockchain-native onboarding transaction
  • View fungible and non-fungible Token metadata relating to assets across all of a user’s associated accounts - their wallet-mediated “parent” account and any hybrid custody model “child” accounts
  • Facilitate transactions acting on assets in child accounts

Point of Clarity

Before diving in, let's make a distinction between "account linking" and "linking accounts".

Account Linking

info

Note that since account linking is a sensitive action, transactions where an account may be linked are designated by a topline pragma #allowAccountLinking. This lets wallet providers inform users that their account may be linked in the signed transaction.

Very simply, account linking is a feature in Cadence that let's an AuthAccount create a Capability on itself. You can do so in the following transaction:

link_account.cdc

_15
#allowAccountLinking
_15
_15
transaction(linkPathSuffix: String) {
_15
prepare(account: AuthAccount) {
_15
// Create the PrivatePath where we'll create the link
_15
let linkPath = PrivatePath(identifier: linkPathSuffix)
_15
?? panic("Could not construct PrivatePath from given identifier: ".concat(linkPathSuffix))
_15
// Check if an AuthAccount Capability already exists at the specified path
_15
if !account.getCapability<&AuthAccount>(linkPath).check() {
_15
// If not, unlink anything that may be there and link the AuthAccount Capability
_15
account.unlink(linkpath)
_15
account.linkAccount(linkPath)
_15
}
_15
}
_15
}

From there, the signing account can retrieve the privately linked AuthAccount Capability and delegate it to another account, unlinking the Capability if they wish to revoke delegated access.

Note that in order to link an account, a transaction must state the #allowAccountLinking pragma in the top line of the transaction. This is an interim safety measure so that wallet providers can notify users they're about to sign a transaction that may create a Capability on their AuthAccount.

info

If you haven't yet, it may be helpful to checkout the Account Model to get a mental model of the objects and account relationships discussed in this doc.

Linking Accounts

Linking accounts leverages this account link, otherwise known as an AuthAccount Capability, and encapsulates it. The components and actions involved in this process - what the Capability is encapsulated in, the collection that holds those encapsulations, etc. is what we'll dive into in this doc.

Terminology

Parent-Child accounts - For the moment, we’ll call the account created by the dApp the “child” account and the account receiving its AuthAccount Capability the “parent” account. Existing methods of account access & delegation (i.e. keys) still imply ownership over the account, but insofar as linked accounts are concerned, the account to which both the user and the dApp share access via AuthAccount Capability will be considered the “child” account.

Walletless onboarding - An onboarding flow whereby a dApp creates an account for a user, onboarding them to the dApp, obviating the need for user wallet authentication.

Blockchain-native onboarding - Similar to the already familiar Web3 onboarding flow where a user authenticates with their existing wallet, a dApp onboards a user via wallet authentication while additionally creating a dApp account and linking it with the authenticated account, resulting in a hybrid custody model.

Hybrid Custody Model - A custodial pattern in which a dApp and a user maintain access to a dApp created account and user access to that account has been mediated by account linking.

Account Linking - Technically speaking, account linking in our context consists of giving some other account an AuthAccount Capability from the granting account. This Capability is maintained in standardized resource called a HybridCustody.Manager, providing its owning user access to any and all of their linked accounts.

Progressive Onboarding - An onboarding flow that walks a user up to self-custodial ownership, starting with walletless onboarding and later linking the dApp account with the user’s authenticated wallet once the user chooses to do so.

Restricted Child Account - An account delegation where the access on the delegating account is restricted according to rules set by the linking child account. The distinctions between this and the subsequent term ("owned" account) will be expanding on later.

Owned Account - An account delegation where the delegatee has unrestricted access on the delegating child account, thereby giving the delegatee presiding authority superseding any other "restricted" parent accounts.

Account Linking

Linking an account is the process of delegating account access via AuthAccount Capability. Of course, we want to do this in a way that allows the receiving account to maintain that Capability and allows easy identification of the accounts on either end of the linkage - the user's main "parent" account and the linked "child" account. This is accomplished in the (still in flux) HybridCustody contract which we'll continue to use in this guidance.

Pre-requisites

Since account delegation is mediated by developer-defined rules, you should make sure to first configure the resources that contain those rules. Contracts involved in defining and enforcing this ruleset are CapabilityFilter and CapabilityFactory. The former enumerates those types that are/aren't accessible from a child account while the latter enables the access of those allowable Capabilities such that the returned values can be properly typed - e.g. retrieving a Capability that can be cast to Capability<&NonFungibleToken.Collection> for example.

Here's how you would configure an AllowlistFilter and add allowed types to it:

setup_allow_all_filter.cdc

_25
import "CapabilityFilter"
_25
_25
transaction(identifiers: [String]) {
_25
prepare(acct: AuthAccount) {
_25
// Setup the AllowlistFilter
_25
if acct.borrow<&CapabilityFilter.AllowlistFilter>(from: CapabilityFilter.StoragePath) == nil {
_25
acct.save(<-CapabilityFilter.create(Type<@CapabilityFilter.AllowlistFilter>()), to: CapabilityFilter.StoragePath)
_25
}
_25
_25
// Ensure the AllowlistFilter is linked to the expected PublicPath
_25
acct.unlink(CapabilityFilter.PublicPath)
_25
acct.link<&CapabilityFilter.AllowlistFilter{CapabilityFilter.Filter}>(CapabilityFilter.PublicPath, target: CapabilityFilter.StoragePath)
_25
_25
// Get a reference to the filter
_25
let filter = acct.borrow<&CapabilityFilter.AllowlistFilter>(from: CapabilityFilter.StoragePath)
_25
?? panic("filter does not exist")
_25
_25
// Add the given type identifiers to the AllowlistFilter
_25
// **Note:** the whole transaction fails if any of the given identifiers are malformed
_25
for identifier in identifiers {
_25
let c = CompositeType(identifier)!
_25
filter.addType(c)
_25
}
_25
}
_25
}

And the following transaction configures a CapabilityFactory.Manager, adding NFT-related Factory objects:

info

Note that the Manager configured here enables retrieval of castable Capabilities. It's recommended that you implement Factory resource definitions to support any NFT Collections related with the use of your application so that users can retrieve Typed Capabilities from accounts linked from your app.

setup_factory.cdc

_35
import "CapabilityFactory"
_35
import "NFTCollectionPublicFactory"
_35
import "NFTProviderAndCollectionFactory"
_35
import "NFTProviderFactory"
_35
_35
import "NonFungibleToken"
_35
_35
transaction {
_35
_35
prepare(acct: AuthAccount) {
_35
// Check for a stored Manager, saving if not found
_35
if acct.borrow<&AnyResource>(from: CapabilityFactory.StoragePath) == nil {
_35
let f <- CapabilityFactory.createFactoryManager()
_35
acct.save(<-f, to: CapabilityFactory.StoragePath)
_35
}
_35
// Check for Capabilities where expected, linking if not found
_35
if !acct.getCapability<&CapabilityFactory.Manager{CapabilityFactory.Getter}>(CapabilityFactory.PrivatePath).check() {
_35
acct.unlink(CapabilityFactory.PublicPath)
_35
acct.link<&CapabilityFactory.Manager{CapabilityFactory.Getter}>(CapabilityFactory.PublicPath, target: CapabilityFactory.StoragePath)
_35
}
_35
_35
assert(
_35
acct.getCapability<&CapabilityFactory.Manager{CapabilityFactory.Getter}>(CapabilityFactory.PublicPath).check(),
_35
message: "CapabilityFactory is not setup properly"
_35
)
_35
_35
let manager = acct.borrow<&CapabilityFactory.Manager>(from: CapabilityFactory.StoragePath)
_35
?? panic("manager not found")
_35
_35
/// Add generic NFT-related Factory implementations to enable castable Capabilities from this Manager
_35
manager.addFactory(Type<&{NonFungibleToken.CollectionPublic}>(), NFTCollectionPublicFactory.Factory())
_35
manager.addFactory(Type<&{NonFungibleToken.Provider, NonFungibleToken.CollectionPublic}>(), NFTProviderAndCollectionFactory.Factory())
_35
manager.addFactory(Type<&{NonFungibleToken.Provider}>(), NFTProviderFactory.Factory())
_35
}
_35
}

resources/hybrid_custody_high_level

In this scenario, a user custodies a key for their main account which maintains access to a wrapped AuthAccount Capability, providing the user restricted access on the app account. The dApp maintains custodial access to the account and regulates the access restrictions to delegatee "parent" accounts.

Linking accounts can be done in one of two ways. Put simply, the child account needs to get the parent account an AuthAccount Capability, and the parent needs to save that Capability so they can retain access in a manner that also represents each side of the link and safeguards the integrity of any access restrictions an application puts in place on delegated access.

We can achieve issuance from the child account and claim from the parent account pattern in either:

  1. We can leverage Cadence’s AuthAccount.Inbox to publish the Capability from the child account & have the parent claim the Capability in a separate transaction.
  2. Multi-party signed transaction, signed by both the the accounts on either side of the link

Let’s take a look at both.

info

You'll want to consider whether you would like the parent account to be configured with some app-specific resources or Capabilities and compose you multisig or claim transactions to include such configurations.

For example, if your dApp deals with specific NFTs, you may want to configure the parent account with Collections for those NFTs so the user can easily transfer them between their linked accounts.

Publish & Claim

Publish

Here, the account delegating access to itself links its AuthAccount Capability, and publishes it to be claimed by the account it will be linked to.

publish_to_parent.cdc

_19
import "HybridCustody"
_19
import "CapabilityFactory"
_19
import "CapabilityFilter"
_19
import "CapabilityDelegator"
_19
_19
transaction(parent: Address, factoryAddress: Address, filterAddress: Address) {
_19
prepare(acct: AuthAccount) {
_19
let owned = acct.borrow<&HybridCustody.OwnedAccount>(from: HybridCustody.OwnedAccountStoragePath)
_19
?? panic("owned account not found")
_19
_19
let factory = getAccount(factoryAddress).getCapability<&CapabilityFactory.Manager{CapabilityFactory.Getter}>(CapabilityFactory.PublicPath)
_19
assert(factory.check(), message: "factory address is not configured properly")
_19
_19
let filter = getAccount(filterAddress).getCapability<&{CapabilityFilter.Filter}>(CapabilityFilter.PublicPath)
_19
assert(filter.check(), message: "capability filter is not configured properly")
_19
_19
owned.publishToParent(parentAddress: parent, factory: factory, filter: filter)
_19
}
_19
}

Claim

On the other side, the receiving account claims the published ChildAccount Capability, adding it to the signer's HybridCustody.Manager.childAccounts indexed on the child account's Address.

redeem_account.cdc

_41
import "MetadataViews"
_41
_41
import "HybridCustody"
_41
import "CapabilityFilter"
_41
_41
transaction(childAddress: Address, filterAddress: Address?, filterPath: PublicPath?) {
_41
prepare(acct: AuthAccount) {
_41
var filter: Capability<&{CapabilityFilter.Filter}>? = nil
_41
if filterAddress != nil && filterPath != nil {
_41
filter = getAccount(filterAddress!).getCapability<&{CapabilityFilter.Filter}>(filterPath!)
_41
}
_41
_41
if acct.borrow<&HybridCustody.Manager>(from: HybridCustody.ManagerStoragePath) == nil {
_41
let m <- HybridCustody.createManager(filter: filter)
_41
acct.save(<- m, to: HybridCustody.ManagerStoragePath)
_41
_41
acct.unlink(HybridCustody.ManagerPublicPath)
_41
acct.unlink(HybridCustody.ManagerPrivatePath)
_41
_41
acct.link<&HybridCustody.Manager{HybridCustody.ManagerPrivate, HybridCustody.ManagerPublic}>(
_41
HybridCustody.ManagerPrivatePath,
_41
target: HybridCustody.ManagerStoragePath
_41
)
_41
acct.link<&HybridCustody.Manager{HybridCustody.ManagerPublic}>(
_41
HybridCustody.ManagerPublicPath,
_41
target: HybridCustody.ManagerStoragePath
_41
)
_41
}
_41
_41
let inboxName = HybridCustody.getChildAccountIdentifier(acct.address)
_41
let cap = acct.inbox.claim<&HybridCustody.ChildAccount{HybridCustody.AccountPrivate, HybridCustody.AccountPublic, MetadataViews.Resolver}>(
_41
inboxName,
_41
provider: childAddress
_41
) ?? panic("child account cap not found")
_41
_41
let manager = acct.borrow<&HybridCustody.Manager>(from: HybridCustody.ManagerStoragePath)
_41
?? panic("manager no found")
_41
_41
manager.addAccount(cap: cap)
_41
}
_41
}

Multi-Signed Transaction

We can combine the two transactions in Publish and Claim into a single multi-signed transaction to achieve Hybrid Custody in a single step.

info

Note that while the following code links both accounts in a single transaction, in practicality you may find it easier to execute publish and claim transactions separately depending on your custodial infrastructure.

setup_multi_sig.cdc

_87
#allowAccountLinking
_87
_87
import "HybridCustody"
_87
_87
import "CapabilityFactory"
_87
import "CapabilityDelegator"
_87
import "CapabilityFilter"
_87
_87
import "MetadataViews"
_87
_87
transaction(parentFilterAddress: Address?, childAccountFactoryAddress: Address, childAccountFilterAddress: Address) {
_87
prepare(childAcct: AuthAccount, parentAcct: AuthAccount) {
_87
// --------------------- Begin setup of child account ---------------------
_87
var acctCap = childAcct.getCapability<&AuthAccount>(HybridCustody.LinkedAccountPrivatePath)
_87
if !acctCap.check() {
_87
acctCap = childAcct.linkAccount(HybridCustody.LinkedAccountPrivatePath)!
_87
}
_87
_87
if childAcct.borrow<&HybridCustody.OwnedAccount>(from: HybridCustody.OwnedAccountStoragePath) == nil {
_87
let ownedAccount <- HybridCustody.createOwnedAccount(acct: acctCap)
_87
childAcct.save(<-ownedAccount, to: HybridCustody.OwnedAccountStoragePath)
_87
}
_87
_87
// check that paths are all configured properly
_87
childAcct.unlink(HybridCustody.OwnedAccountPrivatePath)
_87
childAcct.link<&HybridCustody.OwnedAccount{HybridCustody.BorrowableAccount, HybridCustody.OwnedAccountPublic, MetadataViews.Resolver}>(
_87
HybridCustody.OwnedAccountPrivatePath,
_87
target: HybridCustody.OwnedAccountStoragePath
_87
)
_87
_87
childAcct.unlink(HybridCustody.OwnedAccountPublicPath)
_87
childAcct.link<&HybridCustody.OwnedAccount{HybridCustody.OwnedAccountPublic, MetadataViews.Resolver}>(
_87
HybridCustody.OwnedAccountPublicPath,
_87
target: HybridCustody.OwnedAccountStoragePath
_87
)
_87
// --------------------- End setup of child account ---------------------
_87
_87
// --------------------- Begin setup of parent account ---------------------
_87
var filter: Capability<&{CapabilityFilter.Filter}>? = nil
_87
if parentFilterAddress != nil {
_87
filter = getAccount(parentFilterAddress!).getCapability<&{CapabilityFilter.Filter}>(CapabilityFilter.PublicPath)
_87
}
_87
_87
if parentAcct.borrow<&HybridCustody.Manager>(from: HybridCustody.ManagerStoragePath) == nil {
_87
let m <- HybridCustody.createManager(filter: filter)
_87
parentAcct.save(<- m, to: HybridCustody.ManagerStoragePath)
_87
}
_87
_87
parentAcct.unlink(HybridCustody.ManagerPublicPath)
_87
parentAcct.unlink(HybridCustody.ManagerPrivatePath)
_87
_87
parentAcct.link<&HybridCustody.Manager{HybridCustody.ManagerPrivate, HybridCustody.ManagerPublic}>(
_87
HybridCustody.OwnedAccountPrivatePath,
_87
target: HybridCustody.ManagerStoragePath
_87
)
_87
parentAcct.link<&HybridCustody.Manager{HybridCustody.ManagerPublic}>(
_87
HybridCustody.OwnedAccountPublicPath,
_87
target: HybridCustody.ManagerStoragePath
_87
)
_87
// --------------------- End setup of parent account ---------------------
_87
_87
// Publish account to parent
_87
let owned = childAcct.borrow<&HybridCustody.OwnedAccount>(from: HybridCustody.OwnedAccountStoragePath)
_87
?? panic("owned account not found")
_87
_87
let factory = getAccount(childAccountFactoryAddress)
_87
.getCapability<&CapabilityFactory.Manager{CapabilityFactory.Getter}>(CapabilityFactory.PublicPath)
_87
assert(factory.check(), message: "factory address is not configured properly")
_87
_87
let filterForChild = getAccount(childAccountFilterAddress).getCapability<&{CapabilityFilter.Filter}>(CapabilityFilter.PublicPath)
_87
assert(filterForChild.check(), message: "capability filter is not configured properly")
_87
_87
owned.publishToParent(parentAddress: parentAcct.address, factory: factory, filter: filterForChild)
_87
_87
// claim the account on the parent
_87
let inboxName = HybridCustody.getChildAccountIdentifier(parentAcct.address)
_87
let cap = parentAcct.inbox.claim<&HybridCustody.ChildAccount{HybridCustody.AccountPrivate, HybridCustody.AccountPublic, MetadataViews.Resolver}>(
_87
inboxName,
_87
provider: childAcct.address
_87
) ?? panic("child account cap not found")
_87
_87
let manager = parentAcct.borrow<&HybridCustody.Manager>(from: HybridCustody.ManagerStoragePath)
_87
?? panic("manager no found")
_87
_87
manager.addAccount(cap: cap)
_87
}
_87
}

Onboarding Flows

Given the ability to establish an account and later delegate access to a user, dApps are freed from the constraints of dichotomous custodial & self-custodial paradigms. A developer can choose to onboard a user via traditional Web2 identity and later delegate access to the user’s wallet account. Alternatively, a dApp can enable wallet authentication at the outset, creating a dApp-specific account & linking with the user’s wallet account. As specified above, these two flows are known as walletless and blockchain-native onboarding respectively. Developers can choose to implement one for simplicity or both for maximum flexibility.

Walletless Onboarding

Account Creation

The following transaction creates an account, funding creation via the signer and adding the provided public key. You'll notice this transaction is pretty much your standard account creation. The magic for you will be how you custody the key for this account (locally, KMS, wallet service, etc.) in a manner that allows your dapp to mediate on-chain interactions on behalf of your user.

walletless_onboarding

_52
import "FungibleToken"
_52
import "FlowToken"
_52
_52
transaction(pubKey: String, initialFundingAmt: UFix64) {
_52
_52
prepare(signer: AuthAccount) {
_52
_52
/* --- Account Creation --- */
_52
// **NOTE:** your dApp may choose to separate creation depending on your custodial model)
_52
//
_52
// Create the child account, funding via the signer
_52
let newAccount = AuthAccount(payer: signer)
_52
// Create a public key for the new account from string value in the provided arg
_52
// **NOTE:** You may want to specify a different signature algo for your use case
_52
let key = PublicKey(
_52
publicKey: pubKey.decodeHex(),
_52
signatureAlgorithm: SignatureAlgorithm.ECDSA_P256
_52
)
_52
// Add the key to the new account
_52
// **NOTE:** You may want to specify a different hash algo & weight best for your use case
_52
newAccount.keys.add(
_52
publicKey: key,
_52
hashAlgorithm: HashAlgorithm.SHA3_256,
_52
weight: 1000.0
_52
)
_52
_52
/* --- (Optional) Additional Account Funding --- */
_52
//
_52
// Fund the new account if specified
_52
if initialFundingAmt > 0.0 {
_52
// Get a vault to fund the new account
_52
let fundingProvider = signer.borrow<&FlowToken.Vault{FungibleToken.Provider}>(
_52
from: /storage/flowTokenVault
_52
)!
_52
// Fund the new account with the initialFundingAmount specified
_52
newAccount.getCapability<&FlowToken.Vault{FungibleToken.Receiver}>(
_52
/public/flowTokenReceiver
_52
).borrow()!
_52
.deposit(
_52
from: <-fundingProvider.withdraw(
_52
amount: initialFundingAmt
_52
)
_52
)
_52
}
_52
_52
/* --- Continue with use case specific setup --- */
_52
//
_52
// At this point, the newAccount can further be configured as suitable for
_52
// use in your dapp (e.g. Setup a Collection, Mint NFT, Configure Vault, etc.)
_52
// ...
_52
}
_52
}

Blockchain-Native Onboarding

This onboarding flow is really a single-transaction composition of the steps covered above. This is a testament to the power of the complex transactions you can compose on Flow with Cadence!

info

Recall the pre-requisites needed to be satisfied before linking an account:

  1. CapabilityFilter Filter saved and linked
  2. CapabilityFactory Manager saved and linked as well as Factory implementations supporting the Capability Types you'll want accessible from linked child accounts as Typed Capabilities.

Account Creation & Linking

Compared to walletless onboarding where a user does not have a Flow account, blockchain-native onboarding assumes a user already has a wallet configured and immediately links it with a newly created dApp account. This enables the dApp to sign transactions on the user's behalf via the new child account while immediately delegating control of that account to the onboarding user's main account.

After this transaction, both the custodial party (presumably the client/dApp) and the signing parent account will have access to the newly created account - the custodial party via key access and the parent account via their HybridCustody.Manager maintaining the new account's ChildAccount Capability.

blockchain_native_onboarding.cdc

_132
#allowAccountLinking
_132
_132
import "FungibleToken"
_132
import "FlowToken"
_132
import "MetadataViews"
_132
_132
import "HybridCustody"
_132
import "CapabilityFactory"
_132
import "CapabilityFilter"
_132
import "CapabilityDelegator"
_132
_132
transaction(
_132
pubKey: String,
_132
initialFundingAmt: UFix64,
_132
factoryAddress: Address,
_132
filterAddress: Address
_132
) {
_132
_132
prepare(parent: AuthAccount, app: AuthAccount) {
_132
/* --- Account Creation --- */
_132
//
_132
// Create the child account, funding via the signing app account
_132
let newAccount = AuthAccount(payer: app)
_132
// Create a public key for the child account from string value in the provided arg
_132
// **NOTE:** You may want to specify a different signature algo for your use case
_132
let key = PublicKey(
_132
publicKey: pubKey.decodeHex(),
_132
signatureAlgorithm: SignatureAlgorithm.ECDSA_P256
_132
)
_132
// Add the key to the new account
_132
// **NOTE:** You may want to specify a different hash algo & weight best for your use case
_132
newAccount.keys.add(
_132
publicKey: key,
_132
hashAlgorithm: HashAlgorithm.SHA3_256,
_132
weight: 1000.0
_132
)
_132
_132
/* --- (Optional) Additional Account Funding --- */
_132
//
_132
// Fund the new account if specified
_132
if initialFundingAmt > 0.0 {
_132
// Get a vault to fund the new account
_132
let fundingProvider = app.borrow<&FlowToken.Vault{FungibleToken.Provider}>(
_132
from: /storage/flowTokenVault
_132
)!
_132
// Fund the new account with the initialFundingAmount specified
_132
newAccount.getCapability<&FlowToken.Vault{FungibleToken.Receiver}>(/public/flowTokenReceiver)
_132
.borrow()!
_132
.deposit(
_132
from: <-fundingProvider.withdraw(
_132
amount: initialFundingAmt
_132
)
_132
)
_132
}
_132
_132
/* Continue with use case specific setup */
_132
//
_132
// At this point, the newAccount can further be configured as suitable for
_132
// use in your dapp (e.g. Setup a Collection, Mint NFT, Configure Vault, etc.)
_132
// ...
_132
_132
/* --- Link the AuthAccount Capability --- */
_132
//
_132
var acctCap = newAccount.linkAccount(HybridCustody.LinkedAccountPrivatePath)
_132
?? panic("problem linking account Capability for new account")
_132
_132
// Create a OwnedAccount & link Capabilities
_132
let ownedAccount <- HybridCustody.createOwnedAccount(acct: acctCap)
_132
newAccount.save(<-ownedAccount, to: HybridCustody.OwnedAccountStoragePath)
_132
newAccount
_132
.link<&HybridCustody.OwnedAccount{HybridCustody.BorrowableAccount, HybridCustody.OwnedAccountPublic, MetadataViews.Resolver}>(
_132
HybridCustody.OwnedAccountPrivatePath,
_132
target: HybridCustody.OwnedAccountStoragePath
_132
)
_132
newAccount
_132
.link<&HybridCustody.OwnedAccount{HybridCustody.OwnedAccountPublic}>(
_132
HybridCustody.OwnedAccountPublicPath,
_132
target: HybridCustody.OwnedAccountStoragePath
_132
)
_132
_132
// Get a reference to the OwnedAccount resource
_132
let owned = newAccount.borrow<&HybridCustody.OwnedAccount>(from: HybridCustody.OwnedAccountStoragePath)!
_132
_132
// Get the CapabilityFactory.Manager Capability
_132
let factory = getAccount(factoryAddress)
_132
.getCapability<&CapabilityFactory.Manager{CapabilityFactory.Getter}>(
_132
CapabilityFactory.PublicPath
_132
)
_132
assert(factory.check(), message: "factory address is not configured properly")
_132
_132
// Get the CapabilityFilter.Filter Capability
_132
let filter = getAccount(filterAddress).getCapability<&{CapabilityFilter.Filter}>(CapabilityFilter.PublicPath)
_132
assert(filter.check(), message: "capability filter is not configured properly")
_132
_132
// Configure access for the delegatee parent account
_132
owned.publishToParent(parentAddress: parent.address, factory: factory, filter: filter)
_132
_132
/* --- Add delegation to parent account --- */
_132
//
_132
// Configure HybridCustody.Manager if needed
_132
if parent.borrow<&HybridCustody.Manager>(from: HybridCustody.ManagerStoragePath) == nil {
_132
let m <- HybridCustody.createManager(filter: filter)
_132
parent.save(<- m, to: HybridCustody.ManagerStoragePath)
_132
}
_132
_132
// Link Capabilities
_132
parent.unlink(HybridCustody.ManagerPublicPath)
_132
parent.unlink(HybridCustody.ManagerPrivatePath)
_132
parent.link<&HybridCustody.Manager{HybridCustody.ManagerPrivate, HybridCustody.ManagerPublic}>(
_132
HybridCustody.ManagerPrivatePath,
_132
target: HybridCustody.ManagerStoragePath
_132
)
_132
parent.link<&HybridCustody.Manager{HybridCustody.ManagerPublic}>(
_132
HybridCustody.ManagerPublicPath,
_132
target: HybridCustody.ManagerStoragePath
_132
)
_132
_132
// Claim the ChildAccount Capability
_132
let inboxName = HybridCustody.getChildAccountIdentifier(parent.address)
_132
let cap = parent
_132
.inbox
_132
.claim<&HybridCustody.ChildAccount{HybridCustody.AccountPrivate, HybridCustody.AccountPublic, MetadataViews.Resolver}>(
_132
inboxName,
_132
provider: newAccount.address
_132
) ?? panic("child account cap not found")
_132
_132
// Get a reference to the Manager and add the account
_132
let managerRef = parent.borrow<&HybridCustody.Manager>(from: HybridCustody.ManagerStoragePath)
_132
?? panic("manager no found")
_132
managerRef.addAccount(cap: cap)
_132
}
_132
}

Funding & Custody Patterns

Aside from implementing onboarding flows & account linking, you'll want to also consider the account funding & custodial pattern appropriate for the dApp you're building. The only pattern compatible with walletless onboarding (and therefore the only one showcased above) is one in which the dApp custodies the child account's key and funds account creation.

In general, the funding pattern for account creation will determine to some extent the backend infrastructure needed to support your dApp and the onboarding flow your dApp can support. For example, if you want to to create a service-less client (a totally local dApp without backend infrastructure), you could forego walletless onboarding in favor of a user-funded blockchain-native onboarding to achieve a hybrid custody model. Your dApp maintains the keys to the dApp account locally to sign on behalf of the user, and the user funds the creation of the the account, linking to their main account on account creation. This would be a user-funded, dApp custodied pattern.

Again, custody may deserve some regulatory insight depending on your jurisdiction. If building for production, you'll likely want to consider these non-technical implications in your technical decision-making. Such is the nature of building in crypto.

Here are the patterns you might consider:

DApp-Funded, DApp-Custodied

If you want to implement walletless onboarding, you can stop here as this is the only compatible pattern. In this scenario, a backend dApp account funds the creation of a new account and the dApp custodies the key for said account either on the user's device or some backend KMS.

DApp-Funded, User-Custodied

In this case, the backend dApp account funds account creation, but adds a key to the account which the user custodies. In order for the dApp to act on the user's behalf, it has to be delegated access via AuthAccount Capability which the backend dApp account would maintain in a HybridCustody.Manager. This means that the new account would have two parent accounts - the user's and the dApp. While this pattern provides the user maximum ownership and authority over the child account, this pattern may present unique considerations and edge cases for you as a builder depending on access to the child account. Also note that this and the following patterns are incompatible with walletless onboarding in that the user must have a wallet.

User-Funded, DApp-Custodied

As mentioned above, this pattern unlocks totally service-less architectures - just a local client & smart contracts. An authenticated user signs a transaction creating an account, adding the key provided by the client, and linking the account as a child account. At the end of the transaction, hybrid custody is achieved and the dApp can sign with the custodied key on the user's behalf using the newly created account.

User-Funded, User-Custodied

While perhaps not useful for most dApps, this pattern may be desirable for advanced users who wish to create a shared access account themselves. The user funds account creation, adding keys they custody, and delegates secondary access to some other account.