|
| 1 | +import { WalletProvider } from "./walletProvider"; |
| 2 | +import { Network } from "../network"; |
| 3 | +import { |
| 4 | + Account, |
| 5 | + Chain, |
| 6 | + createPublicClient, |
| 7 | + http, |
| 8 | + parseEther, |
| 9 | + ReadContractParameters, |
| 10 | + ReadContractReturnType, |
| 11 | +} from "viem"; |
| 12 | +import { privateKeyToAccount } from "viem/accounts"; |
| 13 | +import { CHAIN_ID_TO_NETWORK_ID, NETWORK_ID_TO_VIEM_CHAIN } from "../network/network"; |
| 14 | +import { PublicClient } from "viem"; |
| 15 | + |
| 16 | +// Safe SDK imports |
| 17 | +import Safe from "@safe-global/protocol-kit"; |
| 18 | +import SafeApiKit from "@safe-global/api-kit"; |
| 19 | + |
| 20 | +/** |
| 21 | + * Configuration options for the SafeWalletProvider. |
| 22 | + */ |
| 23 | +export interface SafeWalletProviderConfig { |
| 24 | + /** |
| 25 | + * Private key of the signer that controls (or co-controls) the Safe. |
| 26 | + */ |
| 27 | + privateKey: string; |
| 28 | + |
| 29 | + /** |
| 30 | + * Network ID, for example "base-sepolia" or "ethereum-mainnet". |
| 31 | + */ |
| 32 | + networkId: string; |
| 33 | + |
| 34 | + /** |
| 35 | + * Optional existing Safe address. If provided, will connect to that Safe; |
| 36 | + * otherwise, this provider will deploy a new Safe. |
| 37 | + */ |
| 38 | + safeAddress?: string; |
| 39 | +} |
| 40 | + |
| 41 | +/** |
| 42 | + * SafeWalletProvider is a wallet provider implementation that uses Safe multi-signature accounts. |
| 43 | + * When instantiated, this provider can either connect to an existing Safe or deploy a new one. |
| 44 | + */ |
| 45 | +export class SafeWalletProvider extends WalletProvider { |
| 46 | + #privateKey: string; |
| 47 | + #account: Account; |
| 48 | + #chain: Chain; |
| 49 | + #safeAddress: string | null = null; |
| 50 | + #isInitialized: boolean = false; |
| 51 | + #publicClient: PublicClient; |
| 52 | + #safeClient: Safe | null = null; |
| 53 | + #apiKit: SafeApiKit; |
| 54 | + |
| 55 | + /** |
| 56 | + * Creates a new SafeWalletProvider instance. |
| 57 | + * |
| 58 | + * @param config - The configuration options for the SafeWalletProvider. |
| 59 | + */ |
| 60 | + constructor(config: SafeWalletProviderConfig) { |
| 61 | + super(); |
| 62 | + |
| 63 | + // Get chain ID from network ID |
| 64 | + this.#chain = NETWORK_ID_TO_VIEM_CHAIN[config.networkId || "base-sepolia"]; |
| 65 | + if (!this.#chain) throw new Error(`Unsupported network: ${config.networkId}`); |
| 66 | + |
| 67 | + // Create default public viem client |
| 68 | + this.#publicClient = createPublicClient({ |
| 69 | + chain: this.#chain, |
| 70 | + transport: http(), |
| 71 | + }); |
| 72 | + |
| 73 | + // Initialize apiKit with chain ID from Viem chain |
| 74 | + this.#apiKit = new SafeApiKit({ |
| 75 | + chainId: BigInt(this.#chain.id), |
| 76 | + }); |
| 77 | + |
| 78 | + // Connect to an existing Safe or deploy a new one with account of private key as single owner |
| 79 | + this.#privateKey = config.privateKey; |
| 80 | + this.#account = privateKeyToAccount(this.#privateKey as `0x${string}`); |
| 81 | + |
| 82 | + this.initializeSafe(config.safeAddress).then( |
| 83 | + address => { |
| 84 | + this.#safeAddress = address; |
| 85 | + this.#isInitialized = true; |
| 86 | + this.trackInitialization(); |
| 87 | + }, |
| 88 | + error => { |
| 89 | + console.error("Error initializing Safe wallet:", error); |
| 90 | + }, |
| 91 | + ); |
| 92 | + } |
| 93 | + |
| 94 | + /** |
| 95 | + * Returns the Safe address once it is initialized. |
| 96 | + * If the Safe isn't yet deployed or connected, throws an error. |
| 97 | + * |
| 98 | + * @returns The Safe's address. |
| 99 | + * @throws Error if Safe is not initialized. |
| 100 | + */ |
| 101 | + getAddress(): string { |
| 102 | + if (!this.#safeAddress) { |
| 103 | + throw new Error("Safe not yet initialized."); |
| 104 | + } |
| 105 | + return this.#safeAddress; |
| 106 | + } |
| 107 | + |
| 108 | + /** |
| 109 | + * Returns the Network object for this Safe. |
| 110 | + * |
| 111 | + * @returns Network configuration for this Safe. |
| 112 | + */ |
| 113 | + getNetwork(): Network { |
| 114 | + return { |
| 115 | + protocolFamily: "evm", |
| 116 | + networkId: CHAIN_ID_TO_NETWORK_ID[this.#chain.id], |
| 117 | + chainId: this.#chain.id.toString(), |
| 118 | + }; |
| 119 | + } |
| 120 | + |
| 121 | + /** |
| 122 | + * Returns the name of this wallet provider. |
| 123 | + * |
| 124 | + * @returns The string "safe_wallet_provider". |
| 125 | + */ |
| 126 | + getName(): string { |
| 127 | + return "safe_wallet_provider"; |
| 128 | + } |
| 129 | + |
| 130 | + /** |
| 131 | + * Waits for a transaction receipt. |
| 132 | + * |
| 133 | + * @param txHash - The hash of the transaction to wait for. |
| 134 | + * @returns The transaction receipt from the network. |
| 135 | + */ |
| 136 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 137 | + async waitForTransactionReceipt(txHash: `0x${string}`): Promise<any> { |
| 138 | + return await this.#publicClient.waitForTransactionReceipt({ hash: txHash }); |
| 139 | + } |
| 140 | + |
| 141 | + /** |
| 142 | + * Reads data from a contract. |
| 143 | + * |
| 144 | + * @param params - The parameters to read the contract. |
| 145 | + * @returns The response from the contract. |
| 146 | + */ |
| 147 | + async readContract(params: ReadContractParameters): Promise<ReadContractReturnType> { |
| 148 | + return this.#publicClient.readContract(params); |
| 149 | + } |
| 150 | + |
| 151 | + /** |
| 152 | + * Queries the current Safe balance. |
| 153 | + * |
| 154 | + * @returns The balance in wei. |
| 155 | + * @throws Error if Safe address is not set. |
| 156 | + */ |
| 157 | + async getBalance(): Promise<bigint> { |
| 158 | + if (!this.#safeAddress) throw new Error("Safe address is not set."); |
| 159 | + const balance = await this.#publicClient.getBalance({ |
| 160 | + address: this.#safeAddress as `0x${string}`, |
| 161 | + }); |
| 162 | + return balance; |
| 163 | + } |
| 164 | + |
| 165 | + /** |
| 166 | + * Transfers native tokens from the Safe to the specified address. |
| 167 | + * If single-owner, executes immediately. |
| 168 | + * If multi-sig, proposes the transaction. |
| 169 | + * |
| 170 | + * @param to - The destination address |
| 171 | + * @param value - The amount in decimal form (e.g. "0.5" for 0.5 ETH) |
| 172 | + * @returns Transaction hash if executed or Safe transaction hash if proposed |
| 173 | + */ |
| 174 | + async nativeTransfer(to: string, value: string): Promise<string> { |
| 175 | + if (!this.#safeClient) throw new Error("Safe client is not set."); |
| 176 | + |
| 177 | + try { |
| 178 | + // Convert decimal ETH to wei |
| 179 | + const ethAmountInWei = parseEther(value); |
| 180 | + |
| 181 | + // Create the transaction |
| 182 | + const safeTx = await this.#safeClient.createTransaction({ |
| 183 | + transactions: [ |
| 184 | + { |
| 185 | + to: to as `0x${string}`, |
| 186 | + data: "0x", |
| 187 | + value: ethAmountInWei.toString(), |
| 188 | + }, |
| 189 | + ], |
| 190 | + }); |
| 191 | + |
| 192 | + // Get current threshold |
| 193 | + const threshold = await this.#safeClient.getThreshold(); |
| 194 | + |
| 195 | + if (threshold > 1) { |
| 196 | + // Multi-sig flow: propose transaction |
| 197 | + const safeTxHash = await this.#safeClient.getTransactionHash(safeTx); |
| 198 | + const signature = await this.#safeClient.signHash(safeTxHash); |
| 199 | + |
| 200 | + // Propose the transaction |
| 201 | + await this.#apiKit.proposeTransaction({ |
| 202 | + safeAddress: this.getAddress(), |
| 203 | + safeTransactionData: safeTx.data, |
| 204 | + safeTxHash, |
| 205 | + senderSignature: signature.data, |
| 206 | + senderAddress: this.#account.address, |
| 207 | + }); |
| 208 | + |
| 209 | + return `Proposed transaction with Safe transaction hash: ${safeTxHash}. Other owners will need to confirm the transaction before it can be executed.`; |
| 210 | + } else { |
| 211 | + // Single-sig flow: execute immediately |
| 212 | + const response = await this.#safeClient.executeTransaction(safeTx); |
| 213 | + const receipt = await this.waitForTransactionReceipt(response.hash as `0x${string}`); |
| 214 | + return `Successfully transferred ${value} ETH to ${to}. Transaction hash: ${receipt.transactionHash}`; |
| 215 | + } |
| 216 | + } catch (error) { |
| 217 | + throw new Error( |
| 218 | + `Failed to transfer: ${error instanceof Error ? error.message : String(error)}`, |
| 219 | + ); |
| 220 | + } |
| 221 | + } |
| 222 | + |
| 223 | + /** |
| 224 | + * Gets the current owners of the Safe. |
| 225 | + * |
| 226 | + * @returns Array of owner addresses. |
| 227 | + * @throws Error if Safe client is not set. |
| 228 | + */ |
| 229 | + async getOwners(): Promise<string[]> { |
| 230 | + if (!this.#safeClient) throw new Error("Safe client is not set."); |
| 231 | + return await this.#safeClient.getOwners(); |
| 232 | + } |
| 233 | + |
| 234 | + /** |
| 235 | + * Gets the current threshold of the Safe. |
| 236 | + * |
| 237 | + * @returns Current threshold number. |
| 238 | + * @throws Error if Safe client is not set. |
| 239 | + */ |
| 240 | + async getThreshold(): Promise<number> { |
| 241 | + if (!this.#safeClient) throw new Error("Safe client is not set."); |
| 242 | + return await this.#safeClient.getThreshold(); |
| 243 | + } |
| 244 | + |
| 245 | + /** |
| 246 | + * Adds a new owner to the Safe. |
| 247 | + * |
| 248 | + * @param newSigner - The address of the new owner. |
| 249 | + * @param newThreshold - The threshold for the new owner. |
| 250 | + * @returns Transaction hash |
| 251 | + */ |
| 252 | + async addOwnerWithThreshold( |
| 253 | + newSigner: string, |
| 254 | + newThreshold: number | undefined, |
| 255 | + ): Promise<string> { |
| 256 | + if (!this.#safeClient) throw new Error("Safe client is not set."); |
| 257 | + |
| 258 | + // Get current Safe settings |
| 259 | + const currentOwners = await this.getOwners(); |
| 260 | + const currentThreshold = await this.getThreshold(); |
| 261 | + |
| 262 | + // Validate new signer isn't already an owner |
| 263 | + if (currentOwners.includes(newSigner.toLowerCase())) |
| 264 | + throw new Error("Address is already an owner of this Safe"); |
| 265 | + |
| 266 | + // Determine new threshold (keep current if not specified) |
| 267 | + newThreshold = newThreshold || currentThreshold; |
| 268 | + |
| 269 | + // Validate threshold |
| 270 | + const newOwnerCount = currentOwners.length + 1; |
| 271 | + if (newThreshold > newOwnerCount) |
| 272 | + throw new Error( |
| 273 | + `Invalid threshold: ${newThreshold} cannot be greater than number of owners (${newOwnerCount})`, |
| 274 | + ); |
| 275 | + if (newThreshold < 1) throw new Error("Threshold must be at least 1"); |
| 276 | + |
| 277 | + // Add new signer |
| 278 | + const safeTransaction = await this.#safeClient.createAddOwnerTx({ |
| 279 | + ownerAddress: newSigner, |
| 280 | + threshold: newThreshold, |
| 281 | + }); |
| 282 | + |
| 283 | + if (currentThreshold > 1) { |
| 284 | + // Multi-sig flow: propose transaction |
| 285 | + const safeTxHash = await this.#safeClient.getTransactionHash(safeTransaction); |
| 286 | + const signature = await this.#safeClient.signHash(safeTxHash); |
| 287 | + |
| 288 | + await this.#apiKit.proposeTransaction({ |
| 289 | + safeAddress: this.getAddress(), |
| 290 | + safeTransactionData: safeTransaction.data, |
| 291 | + safeTxHash, |
| 292 | + senderSignature: signature.data, |
| 293 | + senderAddress: this.#account.address, |
| 294 | + }); |
| 295 | + return `Successfully proposed adding signer ${newSigner} to Safe ${this.#safeAddress}. Safe transaction hash: ${safeTxHash}. The other signers will need to confirm the transaction before it can be executed.`; |
| 296 | + } else { |
| 297 | + // Single-sig flow: execute immediately |
| 298 | + const tx = await this.#safeClient.executeTransaction(safeTransaction); |
| 299 | + return `Successfully added signer ${newSigner} to Safe ${this.#safeAddress}. Threshold: ${newThreshold}. Transaction hash: ${tx.hash}.`; |
| 300 | + } |
| 301 | + } |
| 302 | + |
| 303 | + /** |
| 304 | + * Gets the public client instance. |
| 305 | + * |
| 306 | + * @returns The Viem PublicClient instance. |
| 307 | + */ |
| 308 | + getPublicClient(): PublicClient { |
| 309 | + return this.#publicClient; |
| 310 | + } |
| 311 | + |
| 312 | + /** |
| 313 | + * Override walletProvider's trackInitialization to prevent tracking before Safe is initialized. |
| 314 | + * Only tracks analytics after the Safe is fully set up. |
| 315 | + */ |
| 316 | + protected trackInitialization(): void { |
| 317 | + // Only track if fully initialized |
| 318 | + if (!this.#isInitialized) return; |
| 319 | + super.trackInitialization(); |
| 320 | + } |
| 321 | + |
| 322 | + /** |
| 323 | + * Creates or connects to a Safe, depending on whether safeAddr is defined. |
| 324 | + * |
| 325 | + * @param safeAddr - The existing Safe address (if not provided, a new Safe is deployed). |
| 326 | + * @returns The address of the Safe. |
| 327 | + */ |
| 328 | + private async initializeSafe(safeAddr?: string): Promise<string> { |
| 329 | + if (!safeAddr) { |
| 330 | + // Check if account has enough ETH for gas fees |
| 331 | + const balance = await this.#publicClient.getBalance({ address: this.#account.address }); |
| 332 | + if (balance === BigInt(0)) |
| 333 | + throw new Error( |
| 334 | + "Creating Safe account requires gaas fees. Please ensure you have enough ETH in your wallet.", |
| 335 | + ); |
| 336 | + |
| 337 | + // Deploy a new Safe |
| 338 | + const predictedSafe = { |
| 339 | + safeAccountConfig: { |
| 340 | + owners: [this.#account.address], |
| 341 | + threshold: 1, |
| 342 | + }, |
| 343 | + safeDeploymentConfig: { |
| 344 | + saltNonce: BigInt(Date.now()).toString(), |
| 345 | + }, |
| 346 | + }; |
| 347 | + |
| 348 | + const safeSdk = await Safe.init({ |
| 349 | + provider: this.#publicClient.transport, |
| 350 | + signer: this.#privateKey, |
| 351 | + predictedSafe, |
| 352 | + }); |
| 353 | + |
| 354 | + // Prepare and send deployment transaction |
| 355 | + const deploymentTx = await safeSdk.createSafeDeploymentTransaction(); |
| 356 | + const externalSigner = await safeSdk.getSafeProvider().getExternalSigner(); |
| 357 | + const hash = await externalSigner?.sendTransaction({ |
| 358 | + to: deploymentTx.to, |
| 359 | + value: BigInt(deploymentTx.value), |
| 360 | + data: deploymentTx.data as `0x${string}`, |
| 361 | + chain: this.#publicClient.chain, |
| 362 | + }); |
| 363 | + const receipt = await this.waitForTransactionReceipt(hash as `0x${string}`); |
| 364 | + |
| 365 | + // Reconnect to the deployed Safe |
| 366 | + const safeAddress = await safeSdk.getAddress(); |
| 367 | + const reconnected = await safeSdk.connect({ safeAddress }); |
| 368 | + this.#safeClient = reconnected; |
| 369 | + this.#safeAddress = safeAddress; |
| 370 | + |
| 371 | + console.log("Safe deployed at:", safeAddress, "Receipt:", receipt.transactionHash); |
| 372 | + |
| 373 | + return safeAddress; |
| 374 | + } else { |
| 375 | + // Connect to an existing Safe |
| 376 | + const safeSdk = await Safe.init({ |
| 377 | + provider: this.#publicClient.transport, |
| 378 | + signer: this.#privateKey, |
| 379 | + safeAddress: safeAddr, |
| 380 | + }); |
| 381 | + this.#safeClient = safeSdk; |
| 382 | + const existingAddress = await safeSdk.getAddress(); |
| 383 | + |
| 384 | + return existingAddress; |
| 385 | + } |
| 386 | + } |
| 387 | +} |
0 commit comments