Protocol Kit
The Protocol Kit (opens in a new tab) enables developers to interact with the Safe contracts (opens in a new tab) using a TypeScript interface. This Kit can be used to create new Safe accounts, update the configuration of existing Safes, propose and execute transactions, among other features.
Quickstart
In this quickstart guide, you will create a 2 of 3 multi-sig Safe and propose and execute a transaction to send some ETH out of this Safe.
For a more detailed guide, including how to integrate with web3.js
and more Safe transaction configuration options, see Guide: Integrating the Protocol Kit and API Kit (opens in a new tab) and Protocol Kit Reference (opens in a new tab).
Prerequisites
- Node.js and npm (opens in a new tab)
- Three externally-owned accounts with Testnet ETH in at least one account
Install dependencies
First, we need to install some dependencies from safe-core-sdk
and the ethers
library.
To interact with Ethereum and other EVM blockchains in Node, we can either use: web3.js or ethers.js. In this tutorial, we will use the ethers.js library. To use web3js
, see Instantiate an EthAdapter section in Guide: Integrating the Safe Core SDK (opens in a new tab).
The Protocol Kit is compatible only with ethers.js v6. Make sure you specify this version when installing the SDK.
You can store your environment variables such as private keys in a .env
file. To read easily from .env
files, use the dotenv
library.
_10yarn add ethers @safe-global/protocol-kit \_10 @safe-global/api-kit \_10 @safe-global/safe-core-sdk-types \_10 dotenv
Create the .env
file:
_10touch .env
Put your signing account private keys into the .env
file you just created.
_10export OWNER_1_PRIVATE_KEY='<PRIVATE_KEY>'_10export OWNER_2_PRIVATE_KEY='<PRIVATE_KEY>'_10export OWNER_3_PRIVATE_KEY='<PRIVATE_KEY>'
Create an index.ts
file that you will use to run the following code snippets.
_10touch index.ts
Tip: Use ts-node (opens in a new tab) to run a Typescript file in Node.js.
_10npx ts-node examples/protocol-kit/index.ts
Initialize Signers, Providers, and EthAdapter
The signers trigger transactions to the Ethereum blockchain or off-chain transactions. The provider connects to the Ethereum blockchain.
You can get a public RPC URL from Chainlist (opens in a new tab), however, public RPC URLs can be unreliable so you can also try a dedicated provider like Infura or Alchemy.
For this tutorial, we will be creating a Safe on the Sepolia Testnet.
_19import { ethers } from 'ethers'_19import { EthersAdapter } from '@safe-global/protocol-kit'_19import dotenv from 'dotenv'_19_19dotenv.config()_19_19// https://chainlist.org/?search=sepolia&testnets=true_19const RPC_URL='https://eth-sepolia.public.blastapi.io'_19const provider = new ethers.JsonRpcProvider(RPC_URL)_19_19// Initialize signers_19const owner1Signer = new ethers.Wallet(process.env.OWNER_1_PRIVATE_KEY!, provider)_19const owner2Signer = new ethers.Wallet(process.env.OWNER_2_PRIVATE_KEY!, provider)_19const owner3Signer = new ethers.Wallet(process.env.OWNER_3_PRIVATE_KEY!, provider)_19_19const ethAdapterOwner1 = new EthersAdapter({_19 ethers,_19 signerOrProvider: owner1Signer_19})
Initialize the API Kit
The API Kit (opens in a new tab) consumes the Safe Transaction Service API (opens in a new tab). To use this library, create a new instance of the SafeApiKit
class, imported from @safe-global/api-kit
. In chains where Safe provides a Transaction Service, it's enough to specify the chainId.
You can specify your own service using the optional txServiceUrl
parameter.
You will be using Sepolia for this tutorial, however, you can also get service URLs for different networks.
_12import SafeApiKit from '@safe-global/api-kit'_12_12const apiKit = new SafeApiKit({_12 chainId: 1n_12})_12_12_12// or using a custom service_12const apiKit = new SafeApiKit({_12 chainId: 1n, // set the correct chainId_12 txServiceUrl: 'https://url-to-your-custom-service'_12})
Initialize the Protocol Kit
Sepolia is a supported network so you don't need to specify the contract addresses, however, to see how to create a safe on a local or unsupported network, see Instantiate an EthAdapter (opens in a new tab).
Safe Factory is used to create Safes. While Safe class represents an instance of a specific Safe account.
_10import { SafeFactory } from '@safe-global/protocol-kit'_10_10const safeFactory = await SafeFactory.create({ ethAdapter: ethAdapterOwner1 })
Deploy a Safe
Calling the deploySafe
method will deploy the desired Safe and return a Protocol Kit initialized instance ready to be used. Check the API Reference (opens in a new tab) for more details on additional configuration parameters and callbacks.
_21import { SafeAccountConfig } from '@safe-global/protocol-kit'_21_21const safeAccountConfig: SafeAccountConfig = {_21 owners: [_21 await owner1Signer.getAddress(),_21 await owner2Signer.getAddress(),_21 await owner3Signer.getAddress()_21 ],_21 threshold: 2,_21 // ... (Optional params)_21}_21_21/* This Safe is tied to owner 1 because the factory was initialized with_21an adapter that had owner 1 as the signer. */_21const protocolKitOwner1 = await safeFactory.deploySafe({ safeAccountConfig })_21_21const safeAddress = await protocolKitOwner1.getAddress()_21_21console.log('Your Safe has been deployed:')_21console.log(`https://sepolia.etherscan.io/address/${safeAddress}`)_21console.log(`https://app.safe.global/sep:${safeAddress}`)
Send ETH to the Safe
You will send some ETH to this Safe.
_13const safeAddress = protocolKit.getAddress()_13_13const safeAmount = ethers.parseUnits('0.01', 'ether').toHexString()_13_13const transactionParameters = {_13 to: safeAddress,_13 value: safeAmount_13}_13_13const tx = await owner1Signer.sendTransaction(transactionParameters)_13_13console.log('Fundraising.')_13console.log(`Deposit Transaction: https://sepolia.etherscan.io/tx/${tx.hash}`)
Making a transaction from a Safe
The first signer will sign and propose a transaction to send 0.005 ETH out of the Safe. Then, the second signer will add their own proposal and execute the transaction since it meets the 2 of 3 thresholds.
At a high level, making a transaction from the Safe requires the following steps:
Overview
The high-level overview of a multi-sig transaction is PCE: Propose. Confirm. Execute.
- First signer proposes a transaction
- Create transaction: define the amount, destination, and any additional data
- Perform an off-chain signature of the transaction before proposing
- Submit the transaction and signature to the Safe Transaction Service
- Second signer confirms the transaction
- Get pending transactions from the Safe service
- Perform an off-chain signature of the transaction
- Submit the signature to the service
- Anyone executes the transaction
- In this example, the first signer executes the transaction
- Anyone can get the pending transaction from the Safe service
- Account executing the transaction pays the gas fee
Create a transaction
For more details on what to include in a transaction see Create a Transaction in the Safe Core SDK Guide (opens in a new tab).
_13import { MetaTransactionData } from '@safe-global/safe-core-sdk-types'_13_13// Any address can be used. In this example you will use vitalik.eth_13const destination = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'_13const amount = ethers.parseUnits('0.005', 'ether').toString()_13_13const safeTransactionData: MetaTransactionData = {_13 to: destination,_13 data: '0x',_13 value: amount_13}_13// Create a Safe transaction with the provided parameters_13const safeTransaction = await protocolKitOwner1.createTransaction({ transactions: [safeTransactionData] })
Propose the transaction
To propose a transaction to the Safe Transaction Service we need to call the proposeTransaction
method from the API Kit instance.
For a full list and description of the properties that proposeTransaction
accepts, see Propose the transaction to the service (opens in a new tab) in the Safe Core SDK guide.
_13// Deterministic hash based on transaction parameters_13const safeTxHash = await protocolKitOwner1.getTransactionHash(safeTransaction)_13_13// Sign transaction to verify that the transaction is coming from owner 1_13const senderSignature = await protocolKitOwner1.signHash(safeTxHash)_13_13await apiKit.proposeTransaction({_13 safeAddress,_13 safeTransactionData: safeTransaction.data,_13 safeTxHash,_13 senderAddress: await owner1Signer.getAddress(),_13 senderSignature: senderSignature.data,_13})
Get pending transactions
Recall that you created the apiKit
in Initialize the API Kit.
_10const pendingTransactions = await apiKit.getPendingTransactions(safeAddress).results
Confirm the transaction: Second confirmation
When owner 2 is connected to the application, the Protocol Kit should be initialized again with the existing Safe address the address of the owner 2 instead of the owner 1.
_16// Assumes that the first pending transaction is the transaction you want to confirm_16const transaction = pendingTransactions[0]_16const safeTxHash = transaction.safeTxHash_16_16const ethAdapterOwner2 = new EthersAdapter({_16 ethers,_16 signerOrProvider: owner2Signer_16})_16_16const protocolKitOwner2 = await Safe.create({_16 ethAdapter: ethAdapterOwner2,_16 safeAddress_16})_16_16const signature = await protocolKitOwner2.signHash(safeTxHash)_16const response = await apiKit.confirmTransaction(safeTxHash, signature.data)
Execute the transaction
Anyone can execute the Safe transaction once it has the required number of signatures. In this example, owner 1 will execute the transaction and pay for the gas fees.
_10const safeTransaction = await apiKit.getTransaction(safeTxHash)_10const executeTxResponse = await protocolKit.executeTransaction(safeTransaction)_10const receipt = await executeTxResponse.transactionResponse?.wait()_10_10console.log('Transaction executed:')_10console.log(`https://sepolia.etherscan.io/tx/${receipt.transactionHash}`)
Confirm that the transaction was executed
You know that the transaction was executed if the balance in your Safe changes.
_10const afterBalance = await protocolKit.getBalance()_10_10console.log(`The final balance of the Safe: ${ethers.formatUnits(afterBalance, 'ether')} ETH`)
_10$ node index.js_10_10Fundraising._10_10Initial balance of Safe: 0.01 ETH_10Buying a car._10The final balance of the Safe: 0.005 ETH
Conclusion
In this quickstart, you learned how to create and deploy a Safe and to propose and then execute a transaction for the Safe.