Initialize the signClient
Go to https : //cloud.walletconnect.com
import { SignClient } from " @walletconnect/sign-client " ;
let client : any ;
const projectId = "" ;
async function initSignClient ( url : string ) {
client = await SignClient . init ({
projectId ,
metadata : {
name : "" ,
description :
"" ,
url : "" ,
icons : [
"" ,
],
},
});
return client ;
}
Enter fullscreen mode
Exit fullscreen mode
Pairing with URL
const pairUrl = useCallback (
async ( url : string ) => {
if ( client ) {
await client . pair ({ uri : url });
}
},
[ client ],
);
Enter fullscreen mode
Exit fullscreen mode
Setup listeners
const setupListeners = useCallback (() => {
if ( client && selectedNetworkWalletInfo ?. walletAddress ) {
client . on ( " session_connect " , () => {
getSessions ();
});
client . on ( " session_delete " , () => {
getSessions ();
});
client . on ( " session_expire " , () => {
getSessions ();
});
client . on ( " session_ping " , () => {
getSessions ();
});
client . on ( " session_update " , () => {
getSessions ();
});
client . on ( " session_proposal " , async ( proposal ) => {
proposalRef . current = proposal ;
setShowProposalModal ( true );
});
client . on ( " session_request " , async ( event ) => {
try {
const {
params : {
request : { method , params },
},
} = event ;
if ( method === " eth_sendTransaction " && Array . isArray ( params )) {
const [ tx ] = params as EthereumTransaction [];
if ( tx ) {
const { to , value , data } = tx ;
let toAddress = to ;
let tokenAddress = undefined ;
let tokenAmount = " 0 " ;
const isERC20Transfer =
data ?. toUpperCase (). startsWith ( " 0xa9059cbb " . toUpperCase ()) &&
( ! value || value === " 0x0 " );
if ( isERC20Transfer && data ) {
// ERC20 detected
const iface = new ethers . utils . Interface ([
" function transfer(address to, uint256 amount) " ,
]);
const decoded = iface . decodeFunctionData ( " transfer " , data );
toAddress = decoded . to ; // Real recipient
tokenAddress = to ; // Token Contract address
tokenAmount = ethers . utils . formatUnits ( decoded . amount , 18 ); // Assume 18 decimals for now
} else {
// Native token transfer (ETH, MATIC, etc.)
tokenAddress = undefined ; // can not determine contract address from toAddress
tokenAmount = ethers . utils . formatEther ( value ?? " 0 " );
}
navigation . dispatch (
StackActions . push ( " SendCryptoScreen " , {
toAddress :
toAddress ?. toLowerCase () ===
selectedNetworkWalletInfo . walletAddress . toLowerCase ()
? undefined
: toAddress ,
tokenAddress ,
tokenAmount ,
onTransferSuccess : ( txHash ?: string ) =>
onTransferSuccess ( event , txHash ),
}),
);
return ;
}
}
} catch ( error : any ) {
LOG . error ( error );
}
});
}
}, [
client ,
getSessions ,
navigation ,
onTransferSuccess ,
selectedNetworkWalletInfo ?. walletAddress ,
]);
useEffect (() => {
setupListeners ();
}, [ setupListeners ]);
Enter fullscreen mode
Exit fullscreen mode
respond
const respond = useCallback (
async ( params : EngineTypes . RespondParams ) => {
if ( client ) {
await client . respond ( params );
}
},
[ client ],
);
Enter fullscreen mode
Exit fullscreen mode
On transfer Success
const onTransferSuccess = useCallback (
async (
event : SignClientTypes . EventArguments [ " session_request " ],
txHash ?: string ,
) => {
const { id , topic } = event ;
if ( txHash ) {
respond ({
topic ,
response : {
id ,
jsonrpc : " 2.0 " ,
result : txHash ,
},
});
} else {
respond ({
topic ,
response : {
id ,
jsonrpc : " 2.0 " ,
error : getSdkError ( " USER_REJECTED_METHODS " ),
},
});
}
},
[ respond ],
);
Enter fullscreen mode
Exit fullscreen mode
Get All sessions
const getSessions = useCallback (() => {
setSessions ( client ? client . session . getAll () : []);
}, [ client ]);
Enter fullscreen mode
Exit fullscreen mode
On cancel praposal
const onCancelProposal = useCallback (() => {
setShowProposalModal ( false );
showErrorModal ({
title : " Request Rejected " ,
subTitle : " Connection request has been rejected successfully " ,
buttonTitle : " Close " ,
customIcon : < Icons . Rejected width = { 35 } height = { 35 } /> ,
});
}, [ showErrorModal ]);
Enter fullscreen mode
Exit fullscreen mode
On approval praposal
const onApproveProposal = useCallback ( async () => {
if (
proposalRef . current &&
client &&
selectedNetworkWalletInfo ?. walletAddress
) {
const session = await client . approve ({
id : proposalRef . current . id ,
namespaces : getNameSpacesByNetwork (
selectedNetworkWalletInfo . walletAddress ,
),
});
if ( session . topic ) {
getSessions ();
setShowProposalModal ( false );
return showSuccessModal ({
title : " Wallet Connected " ,
subTitle : " Your wallet has been successfully connected. " ,
buttonTitle : " Close " ,
});
} else {
onCancelProposal ();
}
}
}, [
client ,
selectedNetworkWalletInfo ?. walletAddress ,
getSessions ,
showSuccessModal ,
onCancelProposal ,
]);
Enter fullscreen mode
Exit fullscreen mode
on delete session
const deleteSession = useCallback (
async ( topic : string , updateSessions = true ) => {
if ( client ) {
await client . disconnect ({
topic ,
reason : getSdkError ( " USER_DISCONNECTED " ),
});
if ( updateSessions ) {
getSessions ();
}
}
},
[ client , getSessions ],
);
Enter fullscreen mode
Exit fullscreen mode
delete All sessions
const deleteAllSessions = useCallback ( async () => {
await Promise . all (
sessions . map (( session ) => deleteSession ( session . topic , false )),
);
getSessions ();
}, [ deleteSession , getSessions , sessions ]);
Enter fullscreen mode
Exit fullscreen mode
Top comments (0)