A connector for the wagmi library. The source code is available in the wagmi/references
repo
yarn add wagmi
npm i wagmi
- Import
SafeConnector
and include it in the wagmi client configuration options
import { SafeConnector } from 'wagmi/connectors/safe';
const chains = [];
const config = createConfig({
connectors: [
new SafeConnector({
chains,
options: {
allowedDomains: [/^app\.safe\.global$/],
debug: false,
},
}),
],
});
autoConnect
property or set it to false. Wagmi library automatically connects to the last used provider, but instead we want to automatically connect to the Safe if the app is loaded in the Safe Context. Autoconnect logic may be implemented via a separate hook.
- Create an autoconnect hook
Safe Apps are loaded inside an iframe in the Safe Wallet application and it is expected that the app automatically connects to the Safe wallet.
import { useConnect } from 'wagmi';
import { useEffect } from 'react';
const AUTOCONNECTED_CONNECTOR_IDS = ['safe'];
function useAutoConnect() {
const { connect, connectors } = useConnect();
useEffect(() => {
AUTOCONNECTED_CONNECTOR_IDS.forEach((connector) => {
const connectorInstance = connectors.find((c) => c.id === connector && c.ready);
if (connectorInstance) {
connect({ connector: connectorInstance });
}
});
}, [connect, connectors]);
}
export { useAutoConnect };
This hook attempts to connect to the Safe wallet automatically on the app load. The hook can be extended with other connectors that use a similar iframe approach (e.g., Ledger Live). It can also be extended with fallback logic such as the last used wallet if the connection to the Safe doesn't succeed.
An example application can be found here
For the SDK overview documentation, please refer to the safe-apps-sdk documentation