@enclavemoney/enclavemoney-experimental
v1.0.20
Published
Enclave Money SDK
Readme
Enclave SDK
The Enclave SDK provides a set of tools to interact with the Enclave API, allowing you to manage smart accounts, build and submit transactions, calculate gas fees, and retrieve smart balances.
Table of Contents
- Installation
- Getting Started
- Types and Interfaces
- Create a Smart Account
- Passkey Account Management
- Fund Your Smart Account
- Get Smart Balance
- Compute Quote
- Build Transaction
- Submit Transaction
- Calculate Gas Fees
- Session Key Management
- Cross-Network USDC Transfer Example
Installation
To use the Enclave SDK, you need to have Node.js installed. You can install the SDK via npm:
npm install enclavemoneyGetting Started
To get started with the Enclave SDK, you need to initialize an instance of the Enclave class with your API key.
import { Enclave, SignMode, OrderType } from '@enclavemoney/enclavemoney-experimental';
const API_KEY = 'your-api-key-here';
const enclave = new Enclave(API_KEY);Types and Interfaces
The SDK exports several TypeScript interfaces and enums for type safety:
SignMode Enum
enum SignMode {
P256 = 0,
ECDSA = 1,
MultichainP256 = 2,
MultichainECDSA = 3,
SessionKey = 4,
SimpleSessionKey = 5,
}OrderType Enum
enum OrderType {
AMOUNT_OUT = "AMOUNT_OUT",
AMOUNT_IN = "AMOUNT_IN"
}Core Interfaces
TransactionDetails
interface TransactionDetails {
encodedData: string;
targetContractAddress: string;
value?: number | bigint;
}OrderData
interface OrderData {
amount: string | number;
limit?: string | number;
type: OrderType;
}CreateAccountResponse
interface CreateAccountResponse {
username: string;
verified: boolean;
authenticated: Boolean;
wallet: {
type?: string;
scw_address: string;
eoa_address?: string;
multi_scw?: any;
};
orgId: string;
addedOn?: number;
updatedOn?: number;
version?: number;
metadata: any;
}BuildUserOpResponse
interface BuildUserOpResponse {
userOp: UserOperationStruct;
messageToSign: string;
signMode: SignMode;
}SubmitTransactionResponse
interface SubmitTransactionResponse {
txnHash: string;
blockHash: string;
timestamp: number;
}ComputeQuoteResponse
interface ComputeQuoteResponse {
total_withdrawn: string;
total_fees: BigNumberish | null;
withdrawals: {
[k: string]: string | undefined;
} | null;
total_credit: BigNumberish;
userWithdrawal: BigNumberish;
}GetBalanceResponse
interface GetBalanceResponse {
grossBalance: string;
netBalance: string;
pendingClaims: string;
balanceByNetwork: {
network: number;
grossValue: string;
netValue: string;
pendingClaims: string;
}[];
}Create a Smart Account
To create a smart account using the Enclave SDK, you can use the createSmartAccount method. Here's an example:
// Assuming you have already initialized the Enclave instance as shown above
const privateKey = 'your-private-key-here'; // Replace with the user's private key
const wallet = new ethers.Wallet(privateKey);
const account: CreateAccountResponse = await enclave.createSmartAccount(wallet.address);
console.log('Smart Account created:', account.wallet.scw_address);Parameters:
eoaAddress(string): The Externally Owned Account address
Returns: Promise<CreateAccountResponse>
Passkey Account Management
The Enclave SDK supports creating and managing smart accounts using passkeys (WebAuthn). This provides a secure and convenient way to manage your smart account without needing to handle private keys.
Get Passkey Registration Options
const registrationOptions = await enclave.getPasskeyAccountRegistrationOptions("[email protected]");Parameters:
username(string): The username for the account
Returns: Promise<PublicKeyCredentialCreationOptionsJSON>
Submit Passkey Registration
const account = await enclave.submitPasskeyAccountRegistrationResponse({
username: "[email protected]",
attResp: response // RegistrationResponseJSON from passkey library
});
console.log('Passkey Smart Account created:', account.wallet.scw_address);Parameters:
interface SubmitPasskeyAccountRegistrationResponseParams {
username: string;
attResp: RegistrationResponseJSON;
}Get Passkey Transaction Options
const transactionOptions = await enclave.getPasskeyTransactionOptions({
username: "[email protected]",
transactionDetails: [{
encodedData: "0x...",
targetContractAddress: "0x...",
value: 0
}],
network: 10,
orderData: {
amount: "100",
type: OrderType.AMOUNT_OUT
},
paymasterData: "0x..." // optional
});Parameters:
interface GetPasskeyTransactionOptionsParams {
username: string;
transactionDetails: TransactionDetails[];
network: number;
orderData: OrderData;
paymasterData?: string;
}Returns: Promise<PublicKeyCredentialRequestOptionsJSON>
Submit Passkey Transaction
const result = await enclave.submitPasskeyTransactionResponse({
username: "[email protected]",
attResp: authResponse // AuthenticationResponseJSON from passkey library
});Parameters:
interface SubmitPasskeyTransactionResponseParams {
username: string;
attResp: AuthenticationResponseJSON;
}Fund Your Smart Account
To fund your smart account, you can deposit USDC to the wallet address on any supported network. Follow these steps:
Retrieve Your Wallet Address: Use the
createSmartAccountmethod to get your wallet address if you haven't already.Deposit USDC: Transfer USDC to your smart account's wallet address using any wallet or exchange that supports the network you are using.
Verify the Deposit: After the transfer, you can verify the deposit by checking the balance using the
getSmartBalancemethod.
Get Smart Balance
Get Simple Balance (string)
To retrieve the balance of a smart account as a string, use the getSmartBalance method:
const balance: string = await enclave.getSmartBalance(account.wallet.scw_address);
console.log('Smart Account Balance:', balance);Parameters:
walletAddress(string): The smart contract wallet address
Returns: Promise<string> - The net balance as a string
Get Detailed Balance Object
To retrieve detailed balance information, use the getSmartBalanceObject method:
const balanceDetails: GetBalanceResponse = await enclave.getSmartBalanceObject(account.wallet.scw_address);
console.log('Balance Details:', balanceDetails);Parameters:
walletAddress(string): The smart contract wallet address
Returns: Promise<GetBalanceResponse>
Compute Quote
To compute a quote using the Enclave SDK, you can use the computeQuote method:
const quote: ComputeQuoteResponse = await enclave.computeQuote({
walletAddress: account.wallet.scw_address,
outputNetwork: 10, // Optimism
amount: 100, // Amount to compute the quote for
type: 'AMOUNT_OUT',
limit: 102 // Limit for the quote
});
console.log('Quote computed:', quote);Parameters:
interface ComputeQuoteParams {
walletAddress: string;
outputNetwork: number;
amount: number;
type: string;
limit: number;
}Returns: Promise<ComputeQuoteResponse>
Order Types Explanation
- AMOUNT_OUT: This type indicates that the user needs a specific amount on the target network. The user will be charged the specified amount plus any applicable fees.
- AMOUNT_IN: This type indicates that the user is willing to spend a specific amount, and they will receive the specified amount minus any applicable fees on the target network.
Build Transaction
The buildTransaction method constructs a transaction for execution:
const builtTxn: BuildUserOpResponse = await enclave.buildTransaction({
transactionDetails: [{
encodedData: "0x...",
targetContractAddress: "0x...",
value: 0
}],
network: 10,
walletAddress: account.wallet.scw_address,
orderData: {
amount: "100",
type: OrderType.AMOUNT_OUT,
limit: "102"
},
paymasterData: "0x...", // optional
signMode: SignMode.ECDSA
});Parameters:
interface BuildTransactionParams {
transactionDetails: TransactionDetails[];
network: number;
walletAddress: string;
orderData?: OrderData;
paymasterData?: string;
signMode: SignMode;
}Returns: Promise<BuildUserOpResponse>
Submit Transaction
Submit a built and signed transaction:
const response: SubmitTransactionResponse = await enclave.submitTransaction({
signature: "0x...",
userOp: builtTxn.userOp,
network: 10,
walletAddress: account.wallet.scw_address,
signatureType: SignMode.ECDSA
});Parameters:
interface SubmitTransactionParams {
signature: string;
userOp: UserOperationStruct;
network: number;
walletAddress: string;
signatureType: SignMode;
}Returns: Promise<SubmitTransactionResponse>
Calculate Gas Fees
Calculate the gas fees for a transaction:
const gasFees: GasResponse = await enclave.calculateGasFees({
transactionDetails: [{
encodedData: "0x...",
targetContractAddress: "0x...",
value: 0
}],
network: 10,
walletAddress: account.wallet.scw_address,
orderData: {
amount: "100",
type: OrderType.AMOUNT_OUT
}
});Parameters:
interface CalculateGasFeesParams {
transactionDetails: TransactionDetails[];
network: number;
walletAddress: string;
orderData?: OrderData;
}Returns: Promise<GasResponse>
Session Key Management
The Enclave SDK provides functionality to enable and disable session keys for your smart account. Session keys allow for temporary delegation of transaction signing capabilities.
Enable Session Key
To enable a session key for your smart account, use the enableSessionKey method:
import { ethers, getBytes } from 'ethers';
const validAfter = Math.floor(Date.now() / 1000); // Unix timestamp when the session key becomes valid
const validUntil = validAfter + (24 * 60 * 60); // Valid for 24 hours
const network = 10; // Network ID (e.g., 10 for Optimism)
const builtTxn: BuildUserOpResponse = await enclave.enableSessionKey({
walletAddress: account.wallet.scw_address,
validAfter,
validUntil,
network
});
// Sign the message
const signature = await wallet.signMessage(getBytes(builtTxn.messageToSign));
// Submit the transaction
const response = await enclave.submitTransaction({
signature,
userOp: builtTxn.userOp,
network: 10,
walletAddress: account.wallet.scw_address,
signatureType: builtTxn.signMode
});
console.log('Transaction submitted successfully:', response);Parameters:
interface EnableSessionKeyParams {
walletAddress: string;
validAfter: number;
validUntil: number;
network: number;
}Returns: Promise<BuildUserOpResponse>
Disable Session Key
To disable a previously enabled session key, use the disableSessionKey method:
const builtTxn: BuildUserOpResponse = await enclave.disableSessionKey({
walletAddress: account.wallet.scw_address,
network: 10
});
// Sign the message
const signature = await wallet.signMessage(getBytes(builtTxn.messageToSign));
// Submit the transaction
const response = await enclave.submitTransaction({
signature,
userOp: builtTxn.userOp,
network: 10,
walletAddress: account.wallet.scw_address,
signatureType: builtTxn.signMode
});
console.log('Transaction submitted successfully:', response);Parameters:
interface DisableSessionKeyParams {
walletAddress: string;
network: number;
}Returns: Promise<BuildUserOpResponse>
Delegate Action
To execute delegated transactions through an account once session keys are enabled:
const response: SubmitTransactionResponse = await enclave.delegateAction({
transactionDetails: [{
encodedData: "0x...",
targetContractAddress: "0x...",
value: 0
}],
network: 10,
walletAddress: account.wallet.scw_address,
orderData: {
amount: "100",
type: OrderType.AMOUNT_OUT
},
paymasterData: "0x..." // optional
});
console.log('Transaction submitted successfully:', response);Parameters:
interface DelegateActionParams {
transactionDetails: TransactionDetails[];
network: number;
walletAddress: string;
orderData?: OrderData;
paymasterData?: string;
}Returns: Promise<SubmitTransactionResponse>
Cross-Network USDC Transfer Example
In this example, we'll demonstrate how to deposit USDC on Arbitrum and then transfer it to an address on Optimism using the Enclave SDK.
Step 1: Deposit USDC on Arbitrum
First, ensure you have deposited USDC into your smart account on the Arbitrum network. You can verify the deposit using the getSmartBalance method.
Step 2: Build transaction to transfer USDC to Optimism
To transfer USDC to a wallet on Optimism, you'll need to construct the calldata for the transfer and build the transaction. Here's how you can do it:
// Define the transaction details
// Define the USDC contract address on Optimism
const usdcContractAddress = '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85';
// Define the recipient address and amount to transfer
const recipientAddress = '0x...'; // Replace with the recipient's address
const amount = ethers.utils.parseUnits('1', 6); // Amount of USDC to transfer (1 USDC)
// Create the call data for the ERC20 transfer
const erc20Interface = new ethers.utils.Interface([
'function transfer(address to, uint256 amount)'
]);
const encodedData = erc20Interface.encodeFunctionData('transfer', [recipientAddress, amount]);
const transactionDetails: TransactionDetails[] = [{
encodedData,
targetContractAddress: usdcContractAddress,
value: 0 // Assuming no ETH is being transferred, only USDC
}];
// Define the order data - Describes how much the user wants to spend from their chain-abstracted balances
const orderData: OrderData = {
amount: amount.toString(), // Amount of USDC required for the transfer
type: OrderType.AMOUNT_OUT
// Understanding order type
// AMOUNT_OUT: User needs 100 USDC on the target network. The user will be charged 100 + fees.
// AMOUNT_IN : User is charged 100 USDC and receives (100 - fees) on target network
};
// Build the transaction
const builtTxn: BuildUserOpResponse = await enclave.buildTransaction({
transactionDetails,
network: 10, // Target network (Optimism)
walletAddress: account.wallet.scw_address, // User's smart account address
orderData,
signMode: SignMode.ECDSA // Sign mode (Pass SignMode.SimpleSessionKey for sessionKey transaction)
});
console.log('Transaction built successfully:', builtTxn);Explanation
- Transaction Details: This includes the encoded data for the USDC transfer and the target contract address on Optimism.
- Order Data: Specifies the amount of USDC to transfer and the type of operation.
- Build Transaction: The
buildTransactionmethod constructs the transaction for the specified network (Optimism in this case).
Step 3: Sign and submit the transaction
After building the transaction, you need to sign the messageToSign with the user's EOA (Externally Owned Account) and then submit the transaction using the Enclave SDK.
To sign the transaction, you can use the ethers library to sign the messageToSign with the user's private key.
import { ethers, getBytes } from 'ethers';
// Sign the message
const signature = await wallet.signMessage(getBytes(builtTxn.messageToSign));
// Submit the transaction
const response: SubmitTransactionResponse = await enclave.submitTransaction({
signature,
userOp: builtTxn.userOp,
network: 10, // Target network
walletAddress: account.wallet.scw_address,
signatureType: SignMode.ECDSA // Signature type (Pass SignMode.SimpleSessionKey if the signature is being generated from a sessionKey instead of the user's default EOA)
});
console.log('Transaction submitted successfully:', response);Explanation
- Sign the Message: Use the
etherslibrary to sign themessageToSignwith the user's private key. - Submit the Transaction: Call the
submitTransactionmethod on the Enclave SDK object, passing the signature and other required parameters.
