### Run the Example Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/siwe/README.md Install dependencies, build the project, and start the Sign-In with Ethereum example. ```bash npm ci && npm run build && npm run start ``` -------------------------------- ### Run WaaS Example Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/waas-in-a-box/README.md Execute this command to start the WaaS in a box example. Navigate to http://localhost:3000 in your browser after it starts. ```bash npm start ``` -------------------------------- ### Run the Example Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/ethers/README.md Execute the example script using npm to initiate the transaction signing and sending process. Ensure all prerequisites and environment variables are correctly set before running. ```bash npm run start ``` -------------------------------- ### Build the SDK with npm Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Install dependencies and build the SDK using npm. Ensure you have Node.js and npm installed. ```bash npm ci npm run build ``` -------------------------------- ### Install CubeSigner SDK Packages Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Install the core SDK and the filesystem-backed session storage module using npm. ```bash npm install --save "@cubist-labs/cubesigner-sdk" npm install --save "@cubist-labs/cubesigner-sdk-fs-storage" ``` -------------------------------- ### Install CubeSigner SDK Azure Key Vault Storage Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/packages/az-keyvault-storage/README.md Install the package using npm. ```bash npm install @cubist-labs/cubesigner-sdk-az-keyvault-storage ``` -------------------------------- ### Run Cosmos Token Transfer Example Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/cosmos/README.md Execute the Cosmos token transfer example using npm. This command initiates the process of sending ATOM tokens on the Theta testnet. ```bash npm -C examples/cosmos start ``` -------------------------------- ### Run Sui Token Transfer Example Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/sui/README.md Execute the Sui token transfer example using npm. By default, it sends 2000 mists. Ensure you have sufficient SUI in your account. ```bash npm -C examples/sui start ``` -------------------------------- ### Build TypeScript Project Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/cardano/README.md Build the TypeScript project using npm. This command is a prerequisite for running the subsequent examples. ```bash npm run build ``` -------------------------------- ### Import Mnemonics for EVM and Bitcoin Keys Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/packages/key-import/README.md Demonstrates importing multiple mnemonics for both EVM and Bitcoin Segwit key types. Includes examples with and without BIP39 passwords. ```typescript import * as cs from "@cubist-labs/cubesigner-sdk"; import * as csFs from "@cubist-labs/cubesigner-sdk-fs-storage"; import { KeyImporter, type MnemonicToImport } from "@cubist-labs/cubesigner-sdk-key-import"; // create a CubeSigner client from credentials on-disk, which // you can create by running `cs login` from the CLI. const client = await cs.CubeSignerClient.create(csFs.defaultManagementSessionManager()); // create the key-importer instance const keyImporter = new KeyImporter(client.org()); // mnemonics to import directly as EVM keys const evmMnemonics: MnemonicToImport[] = [ { mnemonic: "car split like parrot uphold faint amount alert inch bean priority custom auction denial reason oyster food duck horn top battle video seed company", derivationPath: "m/44'/60'/0'/0/0", }, { mnemonic: "force focus walnut scale barrel faint hotel fabric source because heavy provide bridge intact they receive stairs matter fetch family color happy slender accident", derivationPath: "m/44'/60'/1'/0/0", password: "bip39 passwords are silly", }, ]; // mnemonic to import directly as Bitcoin Segwit keys const btcMnemonics: MnemonicToImport[] = [ { mnemonic: "style goddess hair mountain open when train mail fly engage fork walnut end toe mail price priority ocean uncover immune spray person slogan avoid", derivationPath: "m/84'/0'/0'/0/0", }, { mnemonic: "marine airport maze doll note assume deliver second bus include deal escape detail friend letter captain glide actual resemble nation shell search elephant busy", derivationPath: "m/84'/0'/9'/0/1", }, ]; // import the keys const evmKeys = await keyImporter.importMnemonics(cs.Secp256k1.Evm, evmMnemonics); const btcKeys = await keyImporter.importMnemonics(cs.Secp256k1.Btc, btcMnemonics); ``` -------------------------------- ### Create CubeSigner Token Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/siwe/README.md Create a CubeSigner token with necessary scopes for managing users and organizations. This token is required to run the example. ```bash export CUBE_SIGNER_TOKEN=$(cs token create --scope 'manage:readonly' --scope 'manage:org:addUser' --scope 'manage:org:deleteUser' --output base64) ``` -------------------------------- ### Required Environment Variables Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/evm-gasless/eip-3009/README.md Set these environment variables to configure the EIP-3009 meta-transaction example. Ensure addresses and contract details are correct for your network. ```bash export FROM_ADDRESS=... # The sender's key material id (i.e., EVM address) export TO_ADDRESS=... # The recipient key material id (i.e., EVM address) export FEE_PAYER_ADDRESS=... # The relayer key material id (i.e., EVM address) who pays the gas export RPC_PROVIDER=... # RPC provider for network export TOKEN_ADDRESS=... # Address of the ERC-20 token contract that supports EIP-3009 export AMOUNT=... # The token amount to transfer without decimal adjustment (e.g., 1.5) ``` -------------------------------- ### Instantiate CubeSignerClient with Default Management Session Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/MIGRATION.md Use `defaultManagementSessionManager()` to get a session manager and then `CubeSignerClient.create()` to instantiate the client. This replaces the older `loadManagementSession()` method. ```typescript const mgr = cs.defaultManagementSessionManager(); const client = await cs.CubeSignerClient.create(mgr); ``` -------------------------------- ### Initiate FIDO Key Registration Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/oidc-client-signing/README.md Starts the process of registering a new FIDO key. This returns a challenge that must be answered to complete the registration. ```typescript const addFidoResp = await cubesigner.addFidoStart("My Fido Key"); const challenge = addFidoResp.data(); ``` -------------------------------- ### Initiate FIDO MFA Approval Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/oidc-client-signing/README.md Starts the process of approving an MFA request using an existing FIDO key. This requires an MFA session manager and returns a challenge to be answered. ```typescript const mfaSession = resp.mfaSessionInfo(); const mfaSessionMgr = await cs.SignerSessionManager.createFromSessionInfo(env, orgId, mfaSession); const signerSession = new cs.SignerSession(mfaSessionMgr); const mfaId = resp.mfaId(); const challenge = await signerSession.fidoApproveStart(mfaId); ``` -------------------------------- ### Create CubeSigner Role and Token Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/cardano/README.md Create a CubeSigner role named 'minting_nfts', add derived keys to it with 'AllowRawBlobSigning' policy, and generate a session token for accessing these keys. This setup is necessary for minting NFTs. ```bash export ROLE_ID=minting_nfts cs role create --role-name $ROLE_ID cat mnemonic.keys.json | jq -r '.keys[].key_id' | xargs -I {} cs role add-keys --key-id "{}" --policy='"AllowRawBlobSigning"' export CUBE_SIGNER_TOKEN=$(cs token create --purpose "testing" --output base64) ``` -------------------------------- ### Run Avalanche Types Cargo Tests Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/packages/fs-storage/test/fixtures/README.md Execute these cargo tests to generate transaction fixtures. Ensure you are in the correct directory and have the necessary dependencies installed. ```bash cargo test --package avalanche-types --lib -- --exact --show-output platformvm::txs::add_permissionless_validator::test_add_permissionless_validator_tx_serialization_with_one_signer platformvm::txs::add_subnet_validator::test_add_subnet_validator_tx_serialization_with_one_signer platformvm::txs::add_validator::test_add_validator_tx_serialization_with_one_signer platformvm::txs::create_chain::test_create_chain_tx_serialization_with_one_signer platformvm::txs::create_subnet::test_create_subnet_tx_serialization_with_one_signer platformvm::txs::export::test_export_tx_serialization_with_one_signer platformvm::txs::import::test_import_tx_serialization_with_one_signer avm::txs::test_tx_serialization_with_two_signers avm::txs::export::test_export_tx_serialization_with_two_signers avm::txs::import::test_import_tx_serialization_with_two_signers ``` -------------------------------- ### Get User and Organization Information Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Retrieve information about the logged-in user and their organization. Assumes the user belongs to exactly one organization. ```typescript const me = await cubesigner.user(); console.log(me); assert(me.user_id); // each user has a globally unique ID assert(me.org_ids); // IDs of all organizations this user is a member of assert(me.org_ids.length === 1); // assume that the user is a member of exactly one org const org = await cubesigner.org(); assert(await org.enabled()); // assume that the org is enabled ``` -------------------------------- ### Send Other Tokens on Sui Mainnet Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/sui/README.md To send non-SUI tokens like NAVX, set the `SUI_NETWORK` to `mainnet`, specify the `COIN_TYPE`, and the desired `AMOUNT`. Then, run the example using `npm`. ```bash export SUI_NETWORK=mainnet export COIN_TYPE="0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX" export AMOUNT=99999 npm -C examples/sui start ``` -------------------------------- ### Create CubeSigner Session Token Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/walletconnect/README.md Creates a new CubeSigner session token with the 'sign:evm:*' scope for signing EVM transactions. Ensure you have the CubeSigner CLI installed and configured. ```bash cs token create --role-id --scope "sign:evm:*" --save ``` -------------------------------- ### Approve TOTP Reset with Existing MFA Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md If MFA is required during TOTP reset, this snippet shows how to approve the reset using an existing TOTP code. Ensure 'otplib' is installed. ```typescript import { authenticator } from "otplib"; // npm install otplib@12.0.1 let totpSecret = process.env["CS_USER_TOTP_SECRET"]!; if (totpResetResp.requiresMfa()) { console.log("Resetting TOTP requires MFA"); const code = authenticator.generate(totpSecret); totpResetResp = await totpResetResp.totpApprove(oidcClient, code); assert(!totpResetResp.requiresMfa()); console.log("MFA approved using existing TOTP"); } ``` -------------------------------- ### Simple Viem Usage with CubeSigner Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/packages/viem/README.md Demonstrates how to create a Viem wallet client using CubeSigner for transaction signing. Ensure the CubeSignerClient is created with appropriate permissions and the correct key/address is specified. The transaction must be prepared with a defined type and chainId. ```typescript import { type CustomSource, createWalletClient, http, publicActions } from "viem"; import { CubeSignerClient } from "@cubist-labs/cubesigner-sdk"; import { CubeSignerSource } from "@cubist-labs/cubesigner-sdk-viem"; import { sepolia } from "viem/chains"; import { toAccount } from "viem/accounts"; const client = await CubeSignerClient.create(...); // must have permissions to sign with `key` const key = ...; // A CubeSigner key object or a string of an address in your org const chain = sepolia; // use an object from "viem/chains" const account = toAccount(new CubeSignerSource(key, client) as CustomSource); // Create a WalletClient to perform actions const walletClient = createWalletClient({ account, chain, transport: http(), // uses Viem's default RPC provider }).extend(publicActions); // Sign transaction as usual: const tx = await walletClient.prepareTransactionRequest({ to: "0x96be1e4c198ecb1a55e769f653b1934950294f19", value: 0n, }); const signature = await walletClient.signTransaction(tx); ... ``` -------------------------------- ### Run SDK Tests with npm Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Execute the SDK tests using npm after logging into Cubesigner. This process creates temporary keys and roles, signs messages, and cleans up resources. ```bash npm test ``` -------------------------------- ### Log into CubeSigner CLI Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Log into your CubeSigner organization using the `cs` command-line tool. Replace '' with your environment. ```bash cs login owner@example.com --env '' ``` -------------------------------- ### Create Cardano Wallet Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/cardano/README.md Initiate the creation of a Cardano wallet using the `npm run create-wallet` command. The output includes the role ID, payment address, and staking address. ```bash npm run create-wallet ``` ```json { role: Role { id: 'Role#8cb36e31-85e9-4b44-bdc8-18ee27873909', name: undefined }, paymentAddress: 'addr_vk1deakjs837zt6xmuwztxxfl95dn5lg80kqg5xwvjcctu8v05lhnyspzfzgc', stakingAddress: 'addr_vk1dgw4kv02l2fv52k2wq73xvpsmk774scwas46nppw0lk7enz3ctksfhl3x6' } ``` -------------------------------- ### Instantiate CubeSignerClient with Default Session Manager Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Create an instance of CubeSignerClient by loading a session token from the default location on disk. ```typescript const cubesigner = await cs.CubeSignerClient.create(defaultUserSessionManager()); ``` -------------------------------- ### Set Recipient Address for Transfer Instruction Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/solana-policy/README.md Export the recipient address for the required 'transfer' instruction. This is necessary when running the example without the optional test. ```bash export TO_ADDRESS=... ``` -------------------------------- ### Create a Role and Add a Key Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Demonstrates creating a new role and adding an existing Secp256k1 key to it. This is the first step in setting up role-based access control for shared keys. ```typescript // Create a role, implicitly adding ourselves as a member const role = await org.createRole(); console.log("Adding key to role, then signing an Ethereum transaction"); await role.addKey(secpKey); // Members of the role can create sessions which can only access keys in the role const roleClient = await cs.CubeSignerClient.create( // Role sessions implicitly have the "sign:*" scope await role.createSession("readme") ); console.log(`Created client for role '${role.id}'`); ``` -------------------------------- ### Create Session for JavaScript Client using CLI Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Use the CubeSigner CLI to create a session explicitly for a JavaScript client. The output is directed to a JSON file. ```bash cs session create --role-id $ROLE_ID --scope sign-all --output json > session.json ``` -------------------------------- ### Create Azure Key Vault Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/packages/az-keyvault-storage/README.md Create an Azure Key Vault using the Azure CLI. ```bash az keyvault create --name my-vault --resource-group my-rg --location eastus ``` -------------------------------- ### Login with CubeSigner CLI Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/viem/README.md Log in to CubeSigner using the CLI, specifying the required scopes for signing EVM transactions and managing keys. Ensure you have funds in your account for the transaction. ```bash cs login --scope 'sign:evm:tx' --scope 'manage:key:get' ... ``` -------------------------------- ### Create a Cosmos Key with RawBlobSigning Policy Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/cosmos/README.md Use this command to create a new Cosmos key with a raw blob signing policy, essential for secure transaction signing. ```bash cs key create -t secp-cosmos --metadata='"cosmos-from"' --policy '"AllowRawBlobSigning" ``` -------------------------------- ### Instantiate CubeSignerClient from File Storage Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/MIGRATION.md Instantiate `JsonFileSessionManager` directly and use `CubeSignerClient.create()` for instantiation from file. This simplifies the previous process involving `JsonFileSessionStorage` and `SignerSessionManager.loadFromStorage`. ```typescript const fileStorage = new cs.JsonFileSessionManager("management-session.json"); const client = await cs.CubeSignerClient.create(fileStorage); ``` -------------------------------- ### Mint NFTs on Cardano Testnet Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/cardano/README.md Execute the NFT minting process using the `npm run mint-nft` command. This command utilizes the previously configured CubeSigner role, keys, and BlockFrost API to mint NFTs on the Cardano testnet. ```bash npm run mint-nft ``` ```json { "address": "addr_test1qqm0nfdrt9xenp3cgk22q26ktudqgn4t405pyqx50qae9dfklxj6xk2dnxrrs3v55q44vhc6q382h2lgzgqdg7pmj26s2gf2uh", "tx_hash": "a5d9e425b959c400ecd75db6e7b7a03faaa42480c9142b8fc8b0180c45f39d45", "tx_index": 1, "output_index": 1, "amount": [ { "unit": "lovelace", "quantity": "9995977531" } ], "block": "f9ab5302207b8a5ea0323f7821044f6afc96199889365c7601ad9e058ca60f15", "data_hash": null, "inline_datum": null, "reference_script_hash": null } POLICY_KEYHASH: 08d116c36ddeb0f468403712a33ead1d55fa9ff8efa282697d77de0a POLICY_TTL: 30262916 POLICY_ID: e237b3d0050b482956a27b1e83bedb86f1828fbe049d3503df54b1ab METADATA: { "e237b3d0050b482956a27b1e83bedb86f1828fbe049d3503df54b1ab": { "cu13157": { "name": "cu13157", "description": "some descr this is a new nft with same policy", "image": "ipfs://QmNhmDPJMgdsFRM9HyiQEJqrKkpsWFshqES8mPaiFRq9Zk", "mediaType": "image/jpeg" } } } TX_TTL: 30262916 TX_HASH: a9c8983a15a3a0a6fca9df9020ce4f5aad28b37c2f4d4f6690e76850ac053d61 SUBMIT_RESULT: "a9c8983a15a3a0a6fca9df9020ce4f5aad28b37c2f4d4f6690e76850ac053d61" ``` -------------------------------- ### Configure Optional Transfer Parameters Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/tempo/README.md Sets optional environment variables for the TIP-20 coin transfer, including the token address, the amount to send, and the RPC provider URL. Defaults are provided if these variables are not set. ```bash # the token to send; defaults to AlphaUSD export TOKEN="0x20c0000000000000000000000000000000000001" # the amount to send; defaults to 100 export AMOUNT="50" # the RPC node to use; defaults to https://rpc.moderato.tempo.xyz export RPC_PROVIDER="https://rpc-tempo-testnet.conduit.xyz" ``` -------------------------------- ### Configure Transaction Environment Variables Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/ethers/README.md Set environment variables for the source address (secp key material ID), recipient address, JSON-RPC provider URL, and the transaction amount. Ensure the source account has sufficient funds for the transaction and gas fees. ```bash export FROM_ADDRESS=0x... # this is your secp key material id export TO_ADDRESS=0x... # the recipient export RPC_PROVIDER=https://... # A JSON-RPC provider for the desired chain export AMOUNT="0.01" # amount in ETH ``` -------------------------------- ### Set up FIDO Key if MFA is not configured Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/oidc-client-signing/README.md Check if Multi-Factor Authentication (MFA) is configured for the user. If not, proceed to set up a FIDO key. ```typescript if ((identity.user_info?.configured_mfa ?? []).length === 0) { console.log("No MFA set up; adding FIDO now"); await setUpFido(oidcToken); } ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/evm-gasless/pimlico/README.md Set environment variables for optional and required configurations. `FROM_ADDRESS` specifies the sender's key, `TO_ADDRESS` the recipient, `PIMLICO_API_KEY` is for Pimlico authentication, and `RPC_PROVIDER` is the network endpoint. ```bash # Optional: the sender's key material id (i.e., EVM address). Creates a new key with CubeSigner if missing. export FROM_ADDRESS=... # Optional: the recipient key material id (i.e., EVM address). Defaults to zero address (0x000...) export TO_ADDRESS=... export PIMLICO_API_KEY=... # Required: your pimlico.io API key export RPC_PROVIDER=... # Required: RPC provider for network ``` -------------------------------- ### Create CubeSigner Session Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/solana/README.md Creates a CubeSigner user session with specified scopes for managing keys and signing Solana transactions. Output is base64 encoded. ```bash export CUBE_SIGNER_TOKEN=$(cs session create --scope "manage:key:get" --scope "sign:solana" --user --output base64) ``` -------------------------------- ### Export CubeSigner Token with Scopes Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/evm-gasless/eip-3009/README.md Use the `cs` CLI to log in and export a CubeSigner token with the necessary scopes for signing EIP-712 messages. ```bash export CUBE_SIGNER_TOKEN=$(cs login ... --scope 'sign:evm:eip712' --export --format base64) ``` -------------------------------- ### Set Source and Destination Addresses for Testing Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/solana-policy/README.md Set the source and destination addresses for testing the Solana policy. FROM_ADDRESS should be your Solana base58 key material ID, and TO_ADDRESS is the recipient for the 'transfer' instruction. ```bash export FROM_ADDRESS=... # this is your Solana base58 key material id export TO_ADDRESS=... # the recipient address for the required 'transfer' instruction ``` -------------------------------- ### Create Cardano Keys from Mnemonic Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/cardano/README.md Generate a new mnemonic, derive account and policy keys using specific derivation paths, and set them as environment variables. This process is essential for signing transactions and minting NFTs. ```bash # Create new mnemonic cs key create --key-type=mnemonic | tee mnemonic.json # Get the mnemonic id export MNEMONIC_ID=$(cat mnemonic.json| jq -r '.keys[0].material_id') # Derive an account and policy key from the original mnemonic cs key derive --key-type cardano-vk --mnemonic-id $MNEMONIC_ID --derivation-path "m/1852'/1815'/0'/0/0" --derivation-path "m/1852'/1815'/0'/0/1" | tee mnemonic.keys.json # Set the environment variables (needed for this example): export ACCOUNT_KEY=$(cat mnemonic.keys.json | jq -r '.keys[0].public_key') export POLICY_KEY=$(cat mnemonic.keys.json | jq -r '.keys[1].public_key') ``` -------------------------------- ### Create OIDC Session using CubeSignerClient Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/MIGRATION.md The `OidcClient` class has been removed. Use the static `CubeSignerClient.createOidcSession` method instead. This method takes environment, organization ID, token, and scopes as arguments. ```typescript const resp = await CubeSignerClient.createOidcSession(env, orgId, token, [ "manage:*", "sign:*", ]); ``` -------------------------------- ### Instantiate CubeSignerClient with Explicit Session Manager Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Create a CubeSignerClient instance by explicitly providing a session manager backed by a JSON file. ```typescript // Create a session manager backed by a JSON file const fileStorage = new JsonFileSessionManager( `${process.env.HOME}/.config/cubesigner/management-session.json`, ); await cs.CubeSignerClient.create(fileStorage); ``` -------------------------------- ### Create a CubeSigner Client with Signing Scopes Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/packages/sdk/README.md Creates a CubeSigner client with the 'sign:*' scope, enabling the session to sign transactions using any accessible keys. This requires explicitly defining scopes during session creation. ```typescript let signingClient = await cs.CubeSignerClient.create( // declare the "sign:*" scope which allows us to sign using any keys the // account has access to await cubesigner.org().createSession("readme signing demo", ["manage:key:get", "sign:* আনুষ্ঠানিক"])); const signingKey = new cs.Key(signingClient, secpKey.cached); let sig = await signingKey.signEvm(eth1Request); console.log(sig.data()); assert(sig.data().rlp_signed_tx); ``` -------------------------------- ### Sign Raw Blob with Ed25519 and Secp256k1 Keys Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Demonstrates creating a key, adding it to a role, attempting to sign a raw blob which should fail by default, then appending the 'AllowRawBlobSigning' policy and successfully signing the blob. This is applicable for both Ed25519 and Secp256k1 key types. ```typescript const edKey = await org.createKey(cs.Ed25519.Cardano); await role.addKey(edKey); console.log(`Created '${await edKey.type()}' key ${edKey.id} and added it to role ${role.id}`); // Sign raw blobs with our new ed key and the secp we created before for (const key of [edKey, secpKey]) { console.log(`Confirming that raw blob with ${await key.type()} is rejected by default`); const roleKey = new cs.Key(roleClient, key.cached); const blobReq: cs.BlobSignRequest = { message_base64: "L1kE9g59xD3fzYQQSR7340BwU9fGrP6EMfIFcyX/YBc=", }; try { await roleKey.signBlob(blobReq); assert(false, "Must be rejected by policy"); } catch (e) { assert(`${e}`.includes("Raw blob signing not allowed")); } console.log("Signing raw blob after adding 'AllowRawBlobSigning' policy"); await key.appendPolicy(["AllowRawBlobSigning"]); const blobSig = await roleKey.signBlob(blobReq); console.log(blobSig.data()); assert(blobSig.data().signature); } ``` -------------------------------- ### Load Session from JSON File Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Load a session from a JSON file created by the CubeSigner CLI. Includes error handling for file not found. ```typescript try { await cs.CubeSignerClient.create(new JsonFileSessionManager("./session.json")); } catch { console.error("Unable to find file") } ``` -------------------------------- ### Login to CubeSigner Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/cardano/README.md Log into your CubeSigner organization using the `cs` command-line tool. This command establishes a management session, typically stored in `~/.config/cubesigner` on Linux. ```bash cs login user@example.com --env '' ``` -------------------------------- ### Set Environment Variables for Transaction Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/viem/README.md Configure the necessary environment variables for the transaction, including the source account (key material ID), recipient address, and the JSON-RPC provider URL for the target network (e.g., Sepolia testnet). ```bash export FROM_ADDRESS=0x... # this is your secp key material id export TO_ADDRESS=0x... # the recipient export RPC_PROVIDER=https://... # A JSON-RPC provider for Sepolia ``` -------------------------------- ### Set Sui Addresses and Network Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/sui/README.md Define the source and destination Sui addresses, and optionally the network and coin type for the transaction. Ensure the `FROM_ADDRESS` corresponds to your Sui key material ID. ```bash export FROM_ADDRESS=... # this is your Sui key material id export TO_ADDRESS=... # the recipient ``` -------------------------------- ### Sign Raw Blob with Ed25519 and Secp256k1 Keys Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/packages/sdk/README.md Demonstrates creating an Ed25519 key, adding it to a role, and then signing raw blobs. It includes error handling for default policy rejections and successful signing after appending the 'AllowRawBlobSigning' policy. This snippet is useful for understanding the workflow of signing uninterpreted byte data. ```typescript const edKey = await org.createKey(cs.Ed25519.Cardano); await role.addKey(edKey); console.log(`Created '${await edKey.type()}' key ${edKey.id} and added it to role ${role.id}`); for (const key of [edKey, secpKey]) { console.log(`Confirming that raw blob with ${await key.type()} is rejected by default`); const roleKey = new cs.Key(roleClient, key.cached); const blobReq: cs.BlobSignRequest = { message_base64: "L1kE9g59xD3fzYQQSR7340BwU9fGrP6EMfIFcyX/YBc=", }; try { await roleKey.signBlob(blobReq); assert(false, "Must be rejected by policy"); } catch (e) { assert(`${e}`.includes("Raw blob signing not allowed")); } console.log("Signing raw blob after adding 'AllowRawBlobSigning' policy"); await key.appendPolicy(["AllowRawBlobSigning"]); const blobSig = await roleKey.signBlob(blobReq); console.log(blobSig.data()); assert(blobSig.data().signature); } ``` -------------------------------- ### Complete FIDO MFA Approval Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/oidc-client-signing/README.md Answers the challenge generated during FIDO MFA approval by creating a credential and sending the confirmation back to CubeSigner. This allows the signing operation to proceed. ```typescript const mfaInfo = await challenge.createCredentialAndAnswer(); console.log("MFA info", mfaInfo); assert(mfaInfo.receipt); resp = await resp.signWithMfaApproval({ mfaId, mfaOrgId: orgId, mfaConf: mfaInfo.receipt.confirmation, }); ``` -------------------------------- ### Basic Usage of AzureKeyVaultSessionManager Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/packages/az-keyvault-storage/README.md Instantiate and use AzureKeyVaultSessionManager to create a CubeSigner client. Ensure Azure authentication is configured. ```typescript import * as cs from "@cubist-labs/cubesigner-sdk"; import { AzureKeyVaultSessionManager } from "@cubist-labs/cubesigner-sdk-az-keyvault-storage"; // Create a session manager const vaultUrl = "https://my-vault.vault.azure.net"; const secretName = "cubesigner-session"; const sessionMgr = new AzureKeyVaultSessionManager(vaultUrl, secretName); // Use it to create a CubeSigner client const client = await cs.CubeSignerClient.create(sessionMgr); // Use the client as normal const user = await client.user(); console.log("User:", user.email); ``` -------------------------------- ### Import Bare Mnemonic and Derive Keys Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/packages/key-import/README.md Shows how to import a bare mnemonic and then use its material ID to derive multiple keys for different cryptocurrency standards. This is useful when deriving many keys from a single mnemonic. ```typescript // If you want to derive many keys from the same mnemonic, you should import // the bare mnemonic and use the `deriveKey` and/or `deriveKeys` methods to // create keys. const bareMnemonic: MnemonicToImport = { mnemonic: "divide impact town typical inhale uncover rifle pet multiply idea long before debate apart pulse type need produce among pony attend cat injury ring", }; // First, import the bare mnemonic const mnemonic = (await keyImporter.importMnemonics(cs.Mnemonic, [bareMnemonic]))[0]; // Then derive keys from it. const deriveResponse = await org.deriveKey(cs.Secp256k1.Taproot, "m/86'/0'/3'/1/0", mnemonic.materialId); const otherDeriveResponses = await org.deriveKeys( cs.Secp256k1.Ava, [ "m/1'/2'/3", "m/4'/5/6", "m/7/8'/9", ], mnemonic.materialId, ); ``` -------------------------------- ### Sign an EVM Transaction using Signer Session Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/oidc-client-signing/README.md Instantiate a `SignerSession` with the obtained session manager. Retrieve available keys and use the first key to sign a dummy EVM transaction. ```typescript const oidcSession = new cs.SignerSession(sessionMgr); const key = (await oidcSession.keys())[0]; const resp = await oidcSession.signEvm(key.material_id, { ... }); const sig = resp.data(); ``` -------------------------------- ### Obtain MFA Client from Response Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/MIGRATION.md The `mfaSessionInfo()` method on the response object has been replaced by `mfaClient()`. The new method directly returns a `CubeSignerClient` instance, simplifying MFA client retrieval. ```typescript const client = await resp.mfaClient(); ``` -------------------------------- ### Import CubeSigner SDK Modules Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Import necessary modules from the CubeSigner SDK and filesystem storage for use in your TypeScript project. ```typescript import * as cs from "@cubist-labs/cubesigner-sdk"; import { JsonFileSessionManager, defaultUserSessionManager } from "@cubist-labs/cubesigner-sdk-fs-storage"; import assert from "assert"; ``` -------------------------------- ### Set Avalanche Chain Addresses Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/avalanchejs/README.md Set the C-chain and P-chain addresses as environment variables. The C-chain address should be your secp key material ID, and the P-chain address should be your secp-ava(-test) key material ID prefixed with `P-`. ```bash export C_CHAIN_ADDRESS=0x... # this is your secp key material id ``` ```bash export P_CHAIN_ADDRESS=P-... # this is your secp-ava(-test) key material id prefixed with `P-` ``` -------------------------------- ### Initiate TOTP Reset Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Initiates the TOTP reset procedure for a user. This is the first step in setting up or resetting TOTP. ```typescript console.log(`Setting up TOTP for user ${me.email}`); let totpResetResp = await oidcClient.resetTotp(); ``` -------------------------------- ### Create OIDC User and Key with CubeSigner API Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/oidc-client-signing-simple-api-only/README.md This TypeScript code demonstrates creating a new OIDC user and their associated EVM key using the CubeSigner API. It requires a management session and utilizes `createOidcUser` and `createKey` functions. ```typescript const managementSession = defaultManagementSessionManager().getDefaultSession(); const identityProof = await getOidcProof(oidcToken); let user = await CubeSigner.getUser(identityProof.userId); if (!user) { user = await CubeSigner.createOidcUser(identityProof); } const key = await CubeSigner.createKey(user.id, { evm: {}, }); ``` -------------------------------- ### Configure Org Policy for SIWE Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/siwe/README.md Configure your CubeSigner organization policy to allow the specified OIDC issuer for SIWE authentication. Replace YOUR_ORG_ID with your actual organization ID. ```json { "OidcAuthSources": { "https://shim.oauth2.cubist.dev/siwe": ["YOUR_ORG_ID"] } } ``` -------------------------------- ### Enable Policy Testing Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/solana-policy/README.md Set the TEST_POLICY environment variable to 'true' to enable the testing of the defined Solana transaction policy. This ensures that transactions adhere to the policy before signing. ```bash export TEST_POLICY=true ``` -------------------------------- ### Create CubeSigner Token Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/evm-gasless/pimlico/README.md Generate a CubeSigner token using the `cs` CLI with necessary scopes for creating and deleting keys, and signing EVM EIP-191 messages. This token is used for authentication. ```bash export CUBE_SIGNER_TOKEN=$(cs login ... --scope 'sign:evm:eip191' --scope 'manage:key:create' --scope 'manage:key:delete' --export --format base64) ``` -------------------------------- ### Complete FIDO Key Registration Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/oidc-client-signing/README.md Answers the challenge generated during FIDO key registration by creating a new credential and sending it back to CubeSigner. ```typescript await challenge.createCredentialAndAnswer(); ``` -------------------------------- ### Custom FIDO Key Registration with Manual Credential Handling Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/oidc-client-signing/README.md Allows for manual creation of a FIDO credential using the browser's WebAuthn API before answering the challenge. This provides more control over the credential creation process. ```typescript const cred = await navigator.credentials.create({ publicKey: challenge.options }); await challenge.answer(cred); ``` -------------------------------- ### Create CubeSigner Key with EIP-191 Signing Policy Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/walletconnect/README.md Creates a new CubeSigner key of type secp with the 'AllowEip191Signing' policy, which is required for testing the personal_sign RPC. The key ID is exported to CUBESIGNER_KEY_ID. ```bash export CUBESIGNER_KEY_ID=$(cs key create --key-type secp --policy '"AllowEip191Signing"' | jq -r '.keys[0].key_id') ``` -------------------------------- ### Create and Use ethers.js v6 CubeSigner Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/packages/ethers-v6/README.md Instantiate the CubeSigner Signer with a key address and CubeSigner session. Use the signer to sign transactions as you normally would with ethers.js. ```typescript import * as cs from "@cubist-labs/cubesigner-sdk"; import { Signer } from "@cubist-labs/cubesigner-sdk-ethers-v6"; import { ethers } from "ethers"; ... // Create new Signer given a key/account address and CubeSigner session object // (with permissions to sign with this key): const signer = new Signer(keyAddress, cubeSignerSession); // Sign transaction as usual: await signer.signTransaction({ to: "0xff50ed3d0ec03ac01d4c79aad74928bff48a7b2b", value: ethers.parseEther("0.0000001"), }); ... ``` -------------------------------- ### Set Source and Destination Addresses Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/tempo/README.md Sets the environment variables for the source (sender's key material ID) and destination (recipient's address) for the TIP-20 coin transfer. The source address must correspond to a key accessible by your CubeSigner session with the AllowRawBlobSigning policy. ```bash export FROM_ADDRESS="0x..." # this is your secp key material id export TO_ADDRESS="0x..." # the recipient ``` -------------------------------- ### Instantiate AzureKeyVaultSessionManager Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/packages/az-keyvault-storage/README.md Use this constructor to create a session manager that reads CubeSigner session tokens from Azure Key Vault. Provide the Key Vault URL and the name of the secret storing the session data. Optional configurations include custom credentials and cache lifetime settings. ```typescript new AzureKeyVaultSessionManager( vaultUrl: string, secretName: string, opts?: AzureKeyVaultSessionManagerOpts ) ``` -------------------------------- ### Instantiate AzureKeyVaultManager Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/packages/az-keyvault-storage/README.md Use this constructor to create a manager for updating and refreshing CubeSigner sessions stored in Azure Key Vault. Requires the Key Vault URL, secret name, and optionally a token credential and client options. ```typescript new AzureKeyVaultManager( vaultUrl: string, secretName: string, credential?: TokenCredential, clientOptions?: SecretClientOptions ) ``` -------------------------------- ### AzureKeyVaultManager Constructor Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/packages/az-keyvault-storage/README.md Initializes a new instance of the AzureKeyVaultManager for updating and refreshing CubeSigner sessions in Azure Key Vault. ```APIDOC ## `AzureKeyVaultManager` Constructor ### Description Initializes a new instance of the `AzureKeyVaultManager` for updating and refreshing CubeSigner sessions in Azure Key Vault. ### Constructor Signature ```typescript new AzureKeyVaultManager( vaultUrl: string, secretName: string, credential?: TokenCredential, clientOptions?: SecretClientOptions ) ``` ### Parameters #### Path Parameters - **vaultUrl** (string) - Required - Azure Key Vault URL (e.g., "https://my-vault.vault.azure.net") - **secretName** (string) - Required - Name of the secret containing the session data #### Optional Parameters - **credential** (TokenCredential) - Optional - Custom Azure credential. - **clientOptions** (SecretClientOptions) - Optional - Options passed to Azure `SecretClient`. ``` -------------------------------- ### Set CubeSigner Key Policy Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/evm-gasless/pimlico/README.md Use the `cs` CLI to set the `AllowEip191Signing` policy on a CubeSigner key. This policy is required for signing UserOperations. ```bash cs key set-policy --key-id="Key#0x..." --policy='"AllowEip191Signing"' ``` -------------------------------- ### Log in with OIDC and obtain a Signer Session Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/oidc-client-signing/README.md Log in using an OIDC token and request a signer session scoped to specific permissions (e.g., `"sign:*"`). This process may require MFA. ```typescript const sessionMgr = await oidcLogin(oidcToken, ["sign:*"]); ``` -------------------------------- ### Set Sender and Receiver Addresses Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/bitcoinjs/README.md Set the environment variables for the sender's Bitcoin address (FROM_ADDRESS) and the recipient's address (TO_ADDRESS). Ensure the FROM_ADDRESS corresponds to a key material ID managed by CubeSigner. ```bash export FROM_ADDRESS=tb1... # this is your btc key material id export TO_ADDRESS=tb1... # the recipient ``` -------------------------------- ### Set Cosmos Transaction Addresses Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/cosmos/README.md Set the source and destination addresses for your Cosmos transaction. FROM_ADDRESS should be your Cosmos key material ID, and TO_ADDRESS is the recipient's address. ```bash export FROM_ADDRESS=... export TO_ADDRESS=... ``` -------------------------------- ### Check Key Vault Access Policies Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/packages/az-keyvault-storage/README.md Use the Azure CLI to view the access policies configured for your Key Vault. This helps in diagnosing permission errors. ```bash az keyvault show --name my-vault --query properties.accessPolicies ``` -------------------------------- ### Create CubeSigner Session with Specific Lifetimes Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/examples/rotation-lambda/README.md Creates a CubeSigner session with specified authentication and refresh lifetimes, and limited scopes. This is crucial for meeting AWS Secrets Manager rotation period requirements. ```bash # DO NOT use the default 'manage:*' scope; choose only the scopes your service needs by providing one or more --scope arguments! cs login --export session.json --auth-lifetime 10h --refresh-lifetime 1d --scope "manage:session:get" ... ``` -------------------------------- ### Load Session from Memory (Directly) Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md A shorthand for loading a session directly from SessionData into a client. ```typescript // or, for short await cs.CubeSignerClient.create(sessionData) ``` -------------------------------- ### Load User Session from CLI Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Load an active user session managed by the CubeSigner CLI into the TypeScript SDK. ```typescript await cs.CubeSignerClient.create(defaultUserSessionManager()) ``` -------------------------------- ### Sign Ethereum Transaction with Correct Scopes Source: https://github.com/cubist-labs/cubesigner-typescript-sdk/blob/main/README.md Creates a CubeSigner client with the 'sign:*' scope and uses it to sign an Ethereum transaction. This requires prior creation of a session with appropriate permissions. ```typescript let signingClient = await cs.CubeSignerClient.create( // declare the "sign:*" scope which allows us to sign using any keys the // account has access to await cubesigner.org().createSession("readme signing demo", ["manage:key:get", "sign:*" ])); const signingKey = new cs.Key(signingClient, secpKey.cached); let sig = await signingKey.signEvm(eth1Request); console.log(sig.data()); assert(sig.data().rlp_signed_tx); ```