chore: improve SWIF

This commit is contained in:
Andrei O 2024-10-14 05:34:31 +03:00
parent 4c0f13840f
commit beb0d6bbd2
No known key found for this signature in database
GPG Key ID: B961E5B68389457E
5 changed files with 49 additions and 15 deletions

View File

@ -137,7 +137,7 @@ class MetaMaskAPI {
_eventsCount = 2 _eventsCount = 2
_jsonRpcConnection = {} _jsonRpcConnection = {}
_log = {} _log = {}
_maxListeners= 100 _maxListeners = 10
_metamask = new Proxy({ _metamask = new Proxy({
isUnlocked: () => { isUnlocked: () => {
return Promise.resolve(true) return Promise.resolve(true)
@ -153,7 +153,6 @@ class MetaMaskAPI {
return false return false
} }
// for maximum compatibility since is cloning the same API // for maximum compatibility since is cloning the same API
enable() { enable() {
return sendMessage({ method: 'eth_requestAccounts', params: Array(0)}) return sendMessage({ method: 'eth_requestAccounts', params: Array(0)})
} }
@ -314,7 +313,7 @@ class MetaMaskAPI {
} }
getMaxListeners() { getMaxListeners() {
return 100 return 10
} }
_getExperimentalApi () { _getExperimentalApi () {
return this._metamask return this._metamask
@ -380,6 +379,7 @@ const listner = function(event: any) {
(<any>eth).selectedAddress = eventDataData?.address?.[0] ?? null; (<any>eth).selectedAddress = eventDataData?.address?.[0] ?? null;
(<any>eth).accounts = eventDataData.address?.[0] ? [eventDataData.address?.[0]] : []; (<any>eth).accounts = eventDataData.address?.[0] ? [eventDataData.address?.[0]] : [];
(<any>eth)._state.accounts = (<any>eth).accounts; (<any>eth)._state.accounts = (<any>eth).accounts;
(<any>eth)._state.isConnected = true;
(<any>eth).isConnected = () => true; (<any>eth).isConnected = () => true;
loadEIP1193Provider(eth) loadEIP1193Provider(eth)
} else if( listnerName === 'chainChanged' ) { } else if( listnerName === 'chainChanged' ) {

View File

@ -1,9 +1,11 @@
import { signMsg, getSelectedAddress, getOptimismProvider } from './wallet' import { signMsg, getSelectedAddress, getOptimismProvider } from './wallet'
import { FARCASTER_PARTIAL_KEY_ABI } from './abis' import { FARCASTER_PARTIAL_KEY_ABI } from './abis'
import { ethers } from 'ethers' import { ethers } from 'ethers'
import { getUrl } from './platform' import { getUrl, setCachedFcAuthToken, getCachedFcAuthToken } from './platform'
import { generateApiToken } from './warpcast-auth' import { generateApiToken} from './warpcast-auth'
import { getQRCode } from './QR' import { getQRCode } from './QR'
import { wait } from './misc'
export interface TChannelTokenStatusResponse { export interface TChannelTokenStatusResponse {
state: string; state: string;
nonce: string; nonce: string;
@ -114,7 +116,8 @@ export const constructWarpcastSWIEMsg = ({
return `${domain} wants you to sign in with your Ethereum account:\n${custodyAddress}\n\nFarcaster Auth\n\nURI: ${siweUri}\nVersion: 1\nChain ID: 10\nNonce: ${nonce}${notBefore ? `\nIssued At: ${notBefore}` : `\nIssued At: ${new Date(Date.now() - 1000).toISOString()}`}${expirationTime ? `\nExpiration Time: ${expirationTime}` : ''}${notBefore ? `\nNot Before: ${notBefore}` : ''}\nResources:\n- farcaster://fid/${fid}` return `${domain} wants you to sign in with your Ethereum account:\n${custodyAddress}\n\nFarcaster Auth\n\nURI: ${siweUri}\nVersion: 1\nChain ID: 10\nNonce: ${nonce}${notBefore ? `\nIssued At: ${notBefore}` : `\nIssued At: ${new Date(Date.now() - 1000).toISOString()}`}${expirationTime ? `\nExpiration Time: ${expirationTime}` : ''}${notBefore ? `\nNot Before: ${notBefore}` : ''}\nResources:\n- farcaster://fid/${fid}`
} }
// WC API has become slow authtoken is many times not considered valid until a few retries
// we use cached older token first
export const signInWithFarcaster = async ({ export const signInWithFarcaster = async ({
channelToken, channelToken,
message, message,
@ -126,11 +129,20 @@ export const signInWithFarcaster = async ({
signature: string, signature: string,
authToken: string authToken: string
}) => { }) => {
const response = await fetch(`${EP_SIGNIN}`, { const maxRetries = 4
let retries = 1
let response: Response
const newToken = authToken
const cachedToken = await getCachedFcAuthToken()
let token = cachedToken || newToken
const isCachedToken = token === cachedToken
do {
await wait(200 * retries)
response = await fetch(`${EP_SIGNIN}`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}` 'Authorization': `Bearer ${token}`
}, },
body: JSON.stringify({ body: JSON.stringify({
channelToken, channelToken,
@ -138,6 +150,15 @@ export const signInWithFarcaster = async ({
signature, signature,
}) })
}); });
if (response.ok) {
setCachedFcAuthToken(token)
return response.json();
}
if (isCachedToken) {
token = newToken
}
retries++
} while (retries < maxRetries)
return response.json(); return response.json();
} }

View File

@ -161,7 +161,6 @@ export const removeAllAbis = async (): Promise<void> => {
await storageSave('abis', defaultAbis) await storageSave('abis', defaultAbis)
} }
export const readCAGetAll = async (): Promise<ContractActions> => { export const readCAGetAll = async (): Promise<ContractActions> => {
return ((await storageGet('read-actions'))?.['read-actions'] ?? {}) as ContractActions return ((await storageGet('read-actions'))?.['read-actions'] ?? {}) as ContractActions
} }
@ -208,6 +207,15 @@ export const writeCAWipe = async (): Promise<void> => {
await storageSave('write-actions', {}) await storageSave('write-actions', {})
} }
export const setCachedFcAuthToken = async (token: string): Promise<void> => {
await storageSave('fcAuthToken', token)
}
export const getCachedFcAuthToken = async (): Promise<string> => {
return (await storageGet('fcAuthToken'))?.fcAuthToken ?? ''
}
export const blockLockout = async (): Promise<Settings> => { export const blockLockout = async (): Promise<Settings> => {
const settings = await getSettings() const settings = await getSettings()
settings.lockOutBlocked = true settings.lockOutBlocked = true

View File

@ -131,7 +131,8 @@
<ion-label <ion-label
><h2>Try to scan QR</h2> ><h2>Try to scan QR</h2>
<p style="font-size: 0.8rem"> <p style="font-size: 0.8rem">
(must be visible on current page) (must be visible on current page, might fail if QR is small or too
complex)
</p></ion-label </p></ion-label
> >
</ion-item> </ion-item>
@ -143,16 +144,20 @@
<ion-item> <ion-item>
<ion-label <ion-label
><h2>Alternative: paste link from QR</h2> ><h2>Alternative: paste link from QR</h2>
<p style="font-size: 0.8rem; opacity: 0.9"> <p style="font-size: 0.7rem; opacity: 0.9">
similar to: https://warpcast.com/~/siwf?channelToken=AXLUD4S4 Privy has copy link, if you see `I am on mobile` you can also right click
to copy. Link is similar to:
https://warpcast.com/~/siwf?channelToken=AXXXXXXX
</p></ion-label </p></ion-label
> >
</ion-item> </ion-item>
<ion-item> <ion-item>
<ion-label> <ion-label>
<p>Account needs to own a fid</p> <p style="font-size: 0.7rem; opacity: 0.9">
<p>QR needs to be visible on the website you click authorize</p> Account needs to own a fid, WC API has become slow you might need to try
multiple, times if you don't get signed in
</p>
</ion-label> </ion-label>
</ion-item> </ion-item>
<ion-item> <ion-item>

View File

@ -44,7 +44,7 @@
:clear-on-edit="false" :clear-on-edit="false"
:spellcheck="false" :spellcheck="false"
:tabindex="0" :tabindex="0"
@ionInput="mpPass = $event.target.value" @ionInput="(e: any) => (mpPass = String(e.target.value))"
id="pass-input" id="pass-input"
> >
<div slot="label"><ion-text color="danger">(Password)</ion-text></div> <div slot="label"><ion-text color="danger">(Password)</ion-text></div>