├── .solhintignore ├── .npmignore ├── .eslintignore ├── .prettierignore ├── .gitignore ├── metadata └── 0 ├── .solhint.json ├── tsconfig.json ├── .eslintrc.js ├── deploy └── 001_deploy_token.ts ├── LICENSE ├── scripts ├── transferOwnershipFromGnosis.ts ├── transferOwnershipToGnosis.ts ├── utils.ts └── gnosis.ts ├── README.md ├── test └── index.ts ├── package.json ├── contracts └── CryptoArt.sol └── hardhat.config.ts /.solhintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | hardhat.config.ts 2 | scripts 3 | test 4 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | artifacts 3 | cache 4 | coverage 5 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | artifacts 3 | cache 4 | coverage* 5 | gasReporterOutput.json 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .env 3 | coverage 4 | coverage.json 5 | typechain 6 | 7 | #Hardhat files 8 | cache 9 | artifacts 10 | 11 | # Other 12 | config.json 13 | -------------------------------------------------------------------------------- /metadata/0: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Crypto Art #0", 3 | "description": "Crypto Art is a collection of 1 PNG file, which I took from some Medium article", 4 | "image": "ipfs://" 5 | } -------------------------------------------------------------------------------- /.solhint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "solhint:recommended", 3 | "rules": { 4 | "compiler-version": ["error", "^0.8.0"], 5 | "func-visibility": ["warn", { "ignoreConstructors": true }] 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2018", 4 | "module": "commonjs", 5 | "strict": true, 6 | "esModuleInterop": true, 7 | "outDir": "dist", 8 | "declaration": true 9 | }, 10 | "include": ["./scripts", "./test", "./typechain"], 11 | "files": ["./hardhat.config.ts"] 12 | } 13 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | browser: false, 4 | es2021: true, 5 | mocha: true, 6 | node: true, 7 | }, 8 | plugins: ["@typescript-eslint"], 9 | extends: [ 10 | "standard", 11 | "plugin:prettier/recommended", 12 | "plugin:node/recommended", 13 | ], 14 | parser: "@typescript-eslint/parser", 15 | parserOptions: { 16 | ecmaVersion: 12, 17 | }, 18 | rules: { 19 | "node/no-unsupported-features/es-syntax": [ 20 | "error", 21 | { ignores: ["modules"] }, 22 | ], 23 | }, 24 | }; 25 | -------------------------------------------------------------------------------- /deploy/001_deploy_token.ts: -------------------------------------------------------------------------------- 1 | import { HardhatRuntimeEnvironment } from "hardhat/types"; 2 | import { DeployFunction } from "hardhat-deploy/types"; 3 | 4 | const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) { 5 | const { deployments, getNamedAccounts } = hre; 6 | const { deploy } = deployments; 7 | const { deployer } = await getNamedAccounts(); 8 | console.log("Deployer: ", deployer); 9 | await deploy("CryptoArt", { 10 | from: deployer, 11 | args: [], 12 | log: true, 13 | }); 14 | }; 15 | 16 | export default func; 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Barefoot-Dev 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /scripts/transferOwnershipFromGnosis.ts: -------------------------------------------------------------------------------- 1 | import { proposeTransaction } from "./gnosis"; 2 | import { getContract } from "./utils"; 3 | const hre = require("hardhat"); 4 | const config = require("../config.json"); 5 | 6 | async function main() { 7 | // get the contract 8 | const chainId = await hre.getChainId(); 9 | const { contract, networkName } = await getContract(chainId); 10 | 11 | // get the original deployer's address 12 | const { getNamedAccounts } = hre; 13 | const { deployer } = await getNamedAccounts(); 14 | 15 | // change the owner and store the transaction receipt 16 | // get the hex code of the desired txn 17 | const methodSignature = await contract.interface.encodeFunctionData( 18 | "transferOwnership", 19 | [deployer] 20 | ); 21 | 22 | // propose the txn 23 | const result = await proposeTransaction( 24 | chainId, 25 | config.gnosisSafeAddress[networkName], 26 | contract.address, 27 | methodSignature 28 | ); 29 | console.log("got result", result); 30 | } 31 | 32 | main() 33 | .then(() => process.exit(0)) 34 | .catch((error) => { 35 | console.error(error); 36 | process.exit(1); 37 | }); 38 | -------------------------------------------------------------------------------- /scripts/transferOwnershipToGnosis.ts: -------------------------------------------------------------------------------- 1 | import { getContract } from "./utils"; 2 | const hre = require("hardhat"); 3 | const config = require("../config.json"); 4 | 5 | async function main() { 6 | console.log("transfering contract ownership"); 7 | // get the contract 8 | const chainId = await hre.getChainId(); 9 | let { contract, provider, networkName } = await getContract(chainId); 10 | 11 | // check the initial owner 12 | const initOwner = await contract.owner(); 13 | console.log("from", initOwner); 14 | 15 | const gnosisSafeAddress = config.gnosisSafeAddress[networkName]; 16 | console.log("to", gnosisSafeAddress); 17 | 18 | // estimate the gas required 19 | const methodSignature = await contract.interface.encodeFunctionData( 20 | "transferOwnership", 21 | [gnosisSafeAddress] 22 | ); 23 | const tx = { 24 | to: contract.address, 25 | value: 0, 26 | data: methodSignature, 27 | from: initOwner, 28 | }; 29 | const gasEstimate = await provider.estimateGas(tx); 30 | 31 | // send the transaction to transfer ownership 32 | const txnReceipt = await contract.transferOwnership(gnosisSafeAddress, { 33 | from: initOwner, 34 | value: 0, 35 | gasLimit: gasEstimate, 36 | }); 37 | 38 | console.log("txn hash", txnReceipt["hash"]); 39 | } 40 | 41 | main() 42 | .then(() => process.exit(0)) 43 | .catch((error) => { 44 | console.error(error); 45 | process.exit(1); 46 | }); 47 | -------------------------------------------------------------------------------- /scripts/utils.ts: -------------------------------------------------------------------------------- 1 | const deployment = require("../deployments.json"); 2 | const hre = require("hardhat"); 3 | import { config as dotenvConfig } from "dotenv"; 4 | import { resolve } from "path"; 5 | dotenvConfig({ path: resolve(__dirname, "../.env") }); 6 | 7 | const alchemyKey: string | undefined = process.env.ALCHEMY_KEY; 8 | if (!alchemyKey) { 9 | throw new Error("Please set your ALCHEMY_KEY in a .env file"); 10 | } 11 | 12 | export async function getContract(chainId: string) { 13 | // find the contract address created at the last run of hardhat deploy 14 | const deploymentInfo = deployment[chainId]; 15 | if (!deploymentInfo) 16 | // did you run hardhat deploy with the export-all flag? 17 | throw `Error: no network found in deployments.json for chainId ${chainId}`; 18 | 19 | const networkName = Object.keys(deploymentInfo)[0]; // get the first key 20 | const address = deploymentInfo[networkName].contracts.CryptoArt.address; 21 | 22 | // load the contract via ethers.js 23 | const Contract = await hre.ethers.getContractFactory("CryptoArt"); 24 | if (!Contract) { 25 | throw new Error("Error: could not load contract factory"); // check the name ^ 26 | } 27 | const contract = await Contract.attach(address); 28 | console.log("got deployed contract", contract.address); 29 | 30 | // get a provider for estimating gas 31 | const provider = new hre.ethers.providers.AlchemyProvider( 32 | networkName, 33 | alchemyKey 34 | ); 35 | 36 | return { contract, provider, networkName }; 37 | } 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Solidity NFT Boilerplate 2 | A smart contract development and deployment boilerplate using Hardhat & Ethers.js 3 | 4 | *Note that this boilerplate does not yet incorporate recent gas optimisations discovered by the Web3 community, such as ERC-721a smart contracts* 5 | 6 | # Tutorial 7 | Find a detailed and guided tutorial to this repo in the associated [Medium Article](https://medium.com/coinmonks/deploying-a-smart-contract-and-selling-nfts-d6215b1da69) 8 | # Install and usage 9 | 10 | Add the required keys to a `.env` file (details [here](https://medium.com/coinmonks/deploying-a-smart-contract-and-selling-nfts-d6215b1da69)): 11 | - ALCHEMY_KEY 12 | - PRIVATE_KEY 13 | - MNEMONIC 14 | - ETHERSCAN_API_KEY 15 | 16 | 17 | Setup 18 | ``` 19 | npm install 20 | ``` 21 | 22 | Run contract tests 23 | ``` 24 | npx hardhat test 25 | ``` 26 | 27 | Check test coverage 28 | ``` 29 | npx hardhat coverage 30 | ``` 31 | 32 | Deploy to the Rinkeby test network 33 | ``` 34 | npx hardhat deploy --network rinkeby --export-all deployments.json 35 | ``` 36 | 37 | Verify on Etherscan 38 | ``` 39 | npx hardhat verify --network rinkeby 40 | ``` 41 | 42 | # About 43 | This repository is the core framework used by [Spectra.Art](https://spectra.art) to develop, test and deploy smart contracts. 44 | 45 | It has been used so far to successfully launch 4 NFT collections: 46 | 1. [Eternal Fragments](https://eternal-fragments.spectra.art) 47 | 2. [Living Fragments](https://opensea.io/collection/living-fragments) 48 | 3. [Vortex](https://vortex.spectra.art) 49 | 4. [Chromospheres](https://chromospheres.spectra.art) 50 | -------------------------------------------------------------------------------- /test/index.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { ethers } from "hardhat"; 3 | 4 | describe("Minting", function () { 5 | it("Mints a token", async function () { 6 | // deploy a contract to the local Hardhat Network 7 | const CryptoArt = await ethers.getContractFactory("CryptoArt"); 8 | const cryptoart = await CryptoArt.deploy(); 9 | await cryptoart.deployed(); 10 | 11 | // get the mint price 12 | const mintPrice = await cryptoart.mintPrice(); 13 | 14 | // mint one token and send the required value (mintPrice) 15 | await cryptoart.mint(1, { value: mintPrice }); 16 | 17 | // get the numer of tokens minted to this newly deployed contract 18 | const supply = await cryptoart.totalSupply(); 19 | 20 | // ensure that the supply is exactly 1 21 | await expect(supply).to.equal(1); 22 | }); 23 | }); 24 | 25 | describe("Utilities", function () { 26 | it("Sets a base URI", async function () { 27 | // deploy a contract to the local Hardhat Network 28 | const CryptoArt = await ethers.getContractFactory("CryptoArt"); 29 | const cryptoart = await CryptoArt.deploy(); 30 | await cryptoart.deployed(); 31 | 32 | // make a fake URI 33 | const URI = "ipfs://testCID/"; 34 | 35 | // set the base URI 36 | await cryptoart.setBaseURI(URI); 37 | 38 | // mint a token 39 | const mintPrice = await cryptoart.mintPrice(); 40 | await cryptoart.mint(1, { value: mintPrice }); 41 | 42 | // get the newly minted token's tokenURI 43 | const tokenURI = await cryptoart.tokenURI(0); 44 | 45 | // check the value 46 | await expect(tokenURI).to.equal(URI + "0"); 47 | }); 48 | }); 49 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hardhat-project", 3 | "devDependencies": { 4 | "@nomiclabs/hardhat-ethers": "^2.0.5", 5 | "@nomiclabs/hardhat-etherscan": "^2.1.8", 6 | "@nomiclabs/hardhat-waffle": "^2.0.1", 7 | "@nomiclabs/hardhat-web3": "^2.0.0", 8 | "@openzeppelin/hardhat-upgrades": "^1.14.0", 9 | "@typechain/ethers-v5": "^7.2.0", 10 | "@typechain/hardhat": "^2.3.1", 11 | "@types/chai": "^4.3.0", 12 | "@types/mocha": "^9.1.0", 13 | "@types/node": "^16.11.24", 14 | "@typescript-eslint/eslint-plugin": "^4.33.0", 15 | "@typescript-eslint/parser": "^4.33.0", 16 | "chai": "^4.3.6", 17 | "dotenv": "^10.0.0", 18 | "eslint": "^7.32.0", 19 | "eslint-config-prettier": "^8.3.0", 20 | "eslint-config-standard": "^16.0.3", 21 | "eslint-plugin-import": "^2.25.4", 22 | "eslint-plugin-node": "^11.1.0", 23 | "eslint-plugin-prettier": "^3.4.1", 24 | "eslint-plugin-promise": "^5.2.0", 25 | "ethereum-waffle": "^3.4.0", 26 | "ethers": "^5.5.4", 27 | "hardhat": "^2.8.4", 28 | "hardhat-contract-sizer": "^2.4.0", 29 | "hardhat-deploy": "^0.9.29", 30 | "hardhat-exposed": "github:Barefoot-Dev/hardhat-exposed#feature/externalLibraryFunction", 31 | "hardhat-gas-reporter": "^1.0.7", 32 | "prettier": "^2.5.1", 33 | "prettier-plugin-solidity": "^1.0.0-beta.19", 34 | "solhint": "^3.3.7", 35 | "solhint-plugin-prettier": "0.0.5", 36 | "solidity-coverage": "^0.7.19", 37 | "ts-node": "^10.5.0", 38 | "typechain": "^5.2.0", 39 | "typescript": "^4.5.5", 40 | "web3": "^1.7.0" 41 | }, 42 | "dependencies": { 43 | "@gnosis.pm/safe-core-sdk": "^2.0.0", 44 | "@gnosis.pm/safe-ethers-lib": "^1.0.0", 45 | "@gnosis.pm/safe-service-client": "^1.1.1", 46 | "@openzeppelin/contracts": "^4.5.0", 47 | "aws-sdk": "^2.1073.0", 48 | "base-64": "^1.0.0", 49 | "base64-img": "^1.0.4", 50 | "data-uri-to-buffer": "^4.0.0", 51 | "open": "^8.4.0", 52 | "prb-math": "^2.4.3" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /contracts/CryptoArt.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | import "@openzeppelin/contracts/access/Ownable.sol"; 5 | import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; 6 | 7 | contract CryptoArt is ERC721Enumerable, Ownable { 8 | uint256 public constant maxSupply = 1024; 9 | uint256 public constant mintPrice = 0.1 ether; 10 | string private currentBaseURI; 11 | 12 | constructor() ERC721("CryptoArt", "ART") {} 13 | 14 | /** @dev Mints NFTs 15 | * @param quantity The quantity of tokens to mint 16 | */ 17 | function mint(uint256 quantity) public payable { 18 | /// block transactions that would exceed the maxSupply 19 | require(totalSupply() + quantity <= maxSupply, "Supply is exhausted"); 20 | 21 | // block transactions that don't provide enough ether 22 | require( 23 | msg.value >= mintPrice * quantity, 24 | "Insufficient value for presale mint" 25 | ); 26 | 27 | /// mint the requested quantity 28 | for (uint256 i = 0; i < quantity; i++) { 29 | uint256 tokenId = totalSupply(); 30 | _safeMint(msg.sender, tokenId); 31 | } 32 | } 33 | 34 | /** @dev Get the current base URI 35 | * @return currentBaseURI 36 | */ 37 | function _baseURI() internal view virtual override returns (string memory) { 38 | return currentBaseURI; 39 | } 40 | 41 | /** @dev Update the base URI 42 | * @param baseURI_ New value of the base URI 43 | */ 44 | function setBaseURI(string memory baseURI_) public onlyOwner { 45 | currentBaseURI = baseURI_; 46 | } 47 | 48 | /** 49 | * @dev Withdraw ether to owner's wallet 50 | */ 51 | function withdrawEth() public onlyOwner { 52 | uint256 balance = address(this).balance; 53 | (bool success, ) = payable(msg.sender).call{value: balance}(""); 54 | require(success, "Withdraw failed"); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /hardhat.config.ts: -------------------------------------------------------------------------------- 1 | import "hardhat-deploy"; // adds the deploy task 2 | import "@nomiclabs/hardhat-ethers"; 3 | import "@nomiclabs/hardhat-etherscan"; 4 | import "@nomiclabs/hardhat-waffle"; 5 | import "hardhat-gas-reporter"; 6 | import "solidity-coverage"; 7 | import { HardhatUserConfig } from "hardhat/config"; 8 | import { NetworkUserConfig } from "hardhat/types"; 9 | 10 | import { resolve } from "path"; 11 | import { config as dotenvConfig } from "dotenv"; 12 | 13 | dotenvConfig({ path: resolve(__dirname, "./.env") }); 14 | 15 | const chainIds = { 16 | hardhat: 31337, 17 | mainnet: 1, 18 | rinkeby: 4, 19 | }; 20 | 21 | // Ensure that we have all the environment variables we need. 22 | const mnemonic: string | undefined = process.env.MNEMONIC; 23 | if (!mnemonic) { 24 | throw new Error("Please set your MNEMONIC in a .env file"); 25 | } 26 | const alchemyKey: string | undefined = process.env.ALCHEMY_KEY; 27 | if (!alchemyKey) { 28 | throw new Error("Please set your ALCHEMY_KEY in a .env file"); 29 | } 30 | 31 | function getChainConfig(network: keyof typeof chainIds): NetworkUserConfig { 32 | const url: string = 33 | "https://eth-" + network + ".alchemyapi.io/v2/" + alchemyKey; 34 | return { 35 | accounts: { mnemonic }, 36 | chainId: chainIds[network], 37 | url: url, 38 | }; 39 | } 40 | 41 | const config: HardhatUserConfig = { 42 | networks: { 43 | hardhat: { 44 | accounts: { mnemonic }, 45 | }, 46 | rinkeby: { 47 | ...getChainConfig("rinkeby"), 48 | }, 49 | }, 50 | gasReporter: { 51 | enabled: true, 52 | currency: "USD", 53 | }, 54 | namedAccounts: { 55 | deployer: 0, 56 | }, 57 | etherscan: { 58 | apiKey: process.env.ETHERSCAN_API_KEY, 59 | }, 60 | solidity: { 61 | version: "0.8.9", 62 | settings: { 63 | // Disable the optimizer when debugging 64 | // https://hardhat.org/hardhat-network/#solidity-optimizer-support 65 | optimizer: { 66 | enabled: true, 67 | runs: 200, 68 | }, 69 | }, 70 | }, 71 | }; 72 | 73 | export default config; 74 | -------------------------------------------------------------------------------- /scripts/gnosis.ts: -------------------------------------------------------------------------------- 1 | import EthersAdapter from "@gnosis.pm/safe-ethers-lib"; 2 | import Safe from "@gnosis.pm/safe-core-sdk"; 3 | import { ethers } from "ethers"; 4 | import { 5 | SafeTransactionData, 6 | SafeTransaction, 7 | } from "@gnosis.pm/safe-core-sdk-types"; 8 | import SafeServiceClient from "@gnosis.pm/safe-service-client"; 9 | import { 10 | SafeMultisigTransactionEstimate, 11 | SafeMultisigTransactionEstimateResponse, 12 | } from "@gnosis.pm/safe-service-client"; 13 | import { resolve } from "path"; 14 | import { config as dotenvConfig } from "dotenv"; 15 | 16 | // API 17 | // https://safe-transaction.rinkeby.gnosis.io/ 18 | 19 | dotenvConfig({ path: resolve(__dirname, "./.env") }); 20 | const sk: string | undefined = process.env.PRIVATE_KEY; 21 | if (!sk) { 22 | throw "Please set your PRIVATE_KEY in a .env file"; 23 | } 24 | 25 | const alchemyKey: string | undefined = process.env.ALCHEMY_KEY; 26 | if (!alchemyKey) { 27 | throw new Error("Please set your ALCHEMY_KEY in a .env file"); 28 | } 29 | 30 | // as per example https://github.com/scaffold-eth/scaffold-eth/blob/gnosis-starter-kit/packages/react-app/src/views/EthSignSignature.jsx 31 | // we need to mock a SafeSignature to manually run addSignature method 32 | // to get the UI-sourced signature onto the transaction prior to executeTransaction 33 | const Signature = class CustomSignature { 34 | signer: string; 35 | data: string; 36 | constructor(signer: string, data: string) { 37 | this.signer = signer; 38 | this.data = data; 39 | } 40 | staticPart() { 41 | return this.data; 42 | } 43 | dynamicPart() { 44 | return ""; 45 | } 46 | }; 47 | 48 | export async function getProvider(chainId: string) { 49 | let provider; 50 | if (chainId === "1") { 51 | provider = new ethers.providers.AlchemyProvider(1, alchemyKey); 52 | } else if (chainId === "4") { 53 | provider = new ethers.providers.AlchemyProvider(4, alchemyKey); 54 | } else { 55 | throw "Unsupported chainId"; 56 | } 57 | return provider; 58 | } 59 | 60 | export async function proposeTransaction( 61 | chainId: string, // e.g. '4' for rinkeby 62 | gnosisSafeAddress: string, // address 63 | contractAddress: string, // address 64 | methodSignature: string // hex 65 | ) { 66 | console.log("Getting provider"); 67 | const provider = await getProvider(chainId); 68 | 69 | console.log("Getting signer"); 70 | // @ts-ignore 71 | const signer = new ethers.Wallet(sk, provider); 72 | 73 | const ethAdapterOwner = new EthersAdapter({ 74 | ethers, 75 | signer: signer, 76 | }); 77 | 78 | // get an instance of the safe-service-client 79 | let safeService; 80 | if (chainId === "1") { 81 | safeService = new SafeServiceClient({ 82 | txServiceUrl: "https://safe-transaction.gnosis.io/", 83 | ethAdapter: ethAdapterOwner, 84 | }); 85 | } else if (chainId === "4") { 86 | safeService = new SafeServiceClient({ 87 | txServiceUrl: "https://safe-transaction.rinkeby.gnosis.io/", 88 | ethAdapter: ethAdapterOwner, 89 | }); 90 | } else { 91 | throw "Unsupported chainId"; 92 | } 93 | 94 | console.log("Getting safe sdk", ethAdapterOwner, gnosisSafeAddress); 95 | const safeSdk: Safe = await Safe.create({ 96 | ethAdapter: ethAdapterOwner, 97 | safeAddress: gnosisSafeAddress, 98 | }); 99 | 100 | // get variables requires as inputs to the transaction 101 | 102 | // nonce 103 | const nonce = await safeSdk.getNonce(); 104 | console.log(`Nonce ${nonce}`); 105 | 106 | // estimate of gas to call this method 107 | const safeTransactionEstimate: SafeMultisigTransactionEstimate = { 108 | to: contractAddress, 109 | value: "0", // in Wei 110 | operation: 0, // 0 = CALL 111 | data: methodSignature, // "0x" for nothing 112 | }; 113 | console.log("Estimating gas", safeTransactionEstimate); 114 | const gasEstimate: SafeMultisigTransactionEstimateResponse = 115 | await safeService.estimateSafeTransaction( 116 | gnosisSafeAddress, 117 | safeTransactionEstimate 118 | ); 119 | console.log("Got gas estimate", gasEstimate); 120 | const safeTxGas: number = parseInt(gasEstimate.safeTxGas); 121 | 122 | // docs https://docs.gnosis.io/safe/docs/contracts_tx_execution/ 123 | const safeTransactionData: SafeTransactionData = { 124 | to: contractAddress, 125 | value: "0", // in Wei 126 | data: methodSignature, // "0x" for nothing 127 | safeTxGas: safeTxGas, 128 | operation: 0, // 0 = CALL 129 | gasToken: ethers.constants.AddressZero, // ether 130 | gasPrice: 0, // Gas price used for the refund calculation 131 | baseGas: 21000, 132 | refundReceiver: gnosisSafeAddress, 133 | nonce: nonce, // nonce of the safe 134 | }; 135 | 136 | // prepare & sign the transaction 137 | const safeTransaction: SafeTransaction = await safeSdk.createTransaction( 138 | safeTransactionData 139 | ); 140 | const txHash = await safeSdk.getTransactionHash(safeTransaction); 141 | console.log(`Safe tx hash = ${txHash}`); 142 | 143 | const signature = await safeSdk.signTransactionHash(txHash); 144 | safeTransaction.addSignature(signature); 145 | 146 | // send the transaction to the UI to collect the other signatures off chain 147 | console.log(`Proposing transaction`); 148 | await safeService.proposeTransaction({ 149 | safeAddress: gnosisSafeAddress, 150 | senderAddress: signer.address, 151 | safeTransaction: safeTransaction, 152 | safeTxHash: txHash, 153 | }); 154 | 155 | const threshold = await safeSdk.getThreshold(); 156 | console.log("Safe threshold:", threshold); 157 | console.log(`Awaiting ${threshold} confirmation(s)`); 158 | let confirmed = false; 159 | while (!confirmed) { 160 | let confirmations = await safeService.getTransactionConfirmations(txHash); 161 | console.log(`Current num confirmations ${confirmations.count}`); 162 | if (confirmations.count === threshold) { 163 | console.log("Received all required confirmations!"); 164 | console.log(confirmations); 165 | confirmed = true; 166 | // the 0th confirmation is the one already provided above in code 167 | // the 1st is the newly acquired confirmation from the UI 168 | // get that and add it to the transaction object 169 | // (the signature of the first signer (the sdk) is added inside executeTransaction) 170 | for (let i = 1; i < confirmations.results.length; i++) { 171 | const signature = confirmations.results[i]; 172 | await safeTransaction.addSignature( 173 | new Signature(signature.owner, signature.signature) 174 | ); 175 | } 176 | // const confirmation = confirmations.results[1]; 177 | // console.log("adding signature2 from UI confirmation", confirmation); 178 | // const signature2 = new Signature( 179 | // confirmation.owner, 180 | // confirmation.signature 181 | // ); 182 | // await safeTransaction.addSignature(signature2); 183 | } else { 184 | await new Promise((resolve) => setTimeout(resolve, 10000)); 185 | } 186 | } 187 | 188 | const approvers = await safeSdk.getOwnersWhoApprovedTx(txHash); 189 | console.log("approvers", approvers); 190 | console.log("signatures", safeTransaction.signatures); 191 | 192 | // use ethers.js to guess the gas price to use 193 | const gasPriceBN = await provider.getGasPrice(); 194 | let gasPrice = gasPriceBN.toNumber(); 195 | console.log("got gasPrice", gasPrice); 196 | // option to increase the gas price via the config 197 | console.log(`Executing with gasPrice = ${gasPrice}`); 198 | 199 | // ensure the gas price was returned and is not nan 200 | if (gasPrice && !isNaN(gasPrice)) { 201 | const executeTxResponse = await safeSdk.executeTransaction( 202 | safeTransaction, 203 | { 204 | gasPrice: gasPrice, 205 | } 206 | ); 207 | 208 | let executed = false; 209 | while (!executed) { 210 | console.log("awaiting tx execution"); 211 | const tx = await safeService.getTransaction(txHash); 212 | if (tx.isExecuted) { 213 | console.log(`Tx executed!`); 214 | // hash is null until executin 215 | console.log(`Hash: ${tx.transactionHash}`); 216 | console.log(tx); 217 | executed = true; 218 | } else { 219 | await new Promise((resolve) => setTimeout(resolve, 10000)); 220 | } 221 | } 222 | await executeTxResponse.transactionResponse?.wait(); 223 | console.log( 224 | `Executed tx hash: ${executeTxResponse.transactionResponse?.hash}` 225 | ); 226 | } else { 227 | console.log(`Could not execute transaction with gasPrice ${gasPrice}`); 228 | } 229 | } 230 | --------------------------------------------------------------------------------