|
| 1 | +import { |
| 2 | + type PublicClient, |
| 3 | + type WalletClient, |
| 4 | + type Chain, |
| 5 | + type Transport, |
| 6 | + type Account, |
| 7 | + keccak256, |
| 8 | + concatHex, |
| 9 | + pad, |
| 10 | + toBytes, |
| 11 | +} from 'viem'; |
| 12 | +import { AzethFactoryAbi } from '@azeth/common/abis'; |
| 13 | +import { |
| 14 | + AzethError, |
| 15 | + AZETH_FACTORY_DOMAIN, |
| 16 | + CREATE_ACCOUNT_TYPES, |
| 17 | + type AzethContractAddresses, |
| 18 | +} from '@azeth/common'; |
| 19 | +import { requireAddress } from '../utils/addresses.js'; |
| 20 | +import { withRetry } from '../utils/retry.js'; |
| 21 | +import type { CreateAccountParams, CreateAccountResult } from './create.js'; |
| 22 | + |
| 23 | +/** Result from the relay endpoint */ |
| 24 | +interface RelayResponse { |
| 25 | + data: { |
| 26 | + account: `0x${string}`; |
| 27 | + tokenId: string; |
| 28 | + txHash: `0x${string}`; |
| 29 | + }; |
| 30 | + error?: { code: string; message: string }; |
| 31 | +} |
| 32 | + |
| 33 | +/** Hash an address array the same way the contract does: keccak256(abi.encodePacked(addresses)). |
| 34 | + * Solidity's abi.encodePacked on address[] pads each element to 32 bytes (not 20). */ |
| 35 | +function hashAddressArray(addresses: `0x${string}`[]): `0x${string}` { |
| 36 | + if (addresses.length === 0) return keccak256(new Uint8Array(0)); |
| 37 | + return keccak256(concatHex(addresses.map((a) => pad(a, { size: 32 })))); |
| 38 | +} |
| 39 | + |
| 40 | +/** Sign CreateAccount params with EIP-712 for gasless relay submission */ |
| 41 | +export async function signCreateAccount( |
| 42 | + walletClient: WalletClient<Transport, Chain, Account>, |
| 43 | + publicClient: PublicClient<Transport, Chain>, |
| 44 | + addresses: AzethContractAddresses, |
| 45 | + params: CreateAccountParams, |
| 46 | + agentURI: string, |
| 47 | + salt: `0x${string}`, |
| 48 | +): Promise<{ signature: `0x${string}`; nonce: bigint }> { |
| 49 | + const factoryAddress = requireAddress(addresses, 'factory'); |
| 50 | + const chainId = publicClient.chain?.id; |
| 51 | + if (!chainId) throw new AzethError('Chain ID not available', 'NETWORK_ERROR'); |
| 52 | + |
| 53 | + // Read current nonce from factory |
| 54 | + const nonce = await withRetry(() => publicClient.readContract({ |
| 55 | + address: factoryAddress, |
| 56 | + abi: AzethFactoryAbi, |
| 57 | + functionName: 'nonces', |
| 58 | + args: [params.owner], |
| 59 | + })) as bigint; |
| 60 | + |
| 61 | + // Pre-hash dynamic fields (must match contract's keccak256(abi.encodePacked(...))) |
| 62 | + const protocolsHash = hashAddressArray(params.protocols ?? []); |
| 63 | + const tokensHash = hashAddressArray(params.tokens ?? []); |
| 64 | + const agentURIHash = keccak256(toBytes(agentURI)); |
| 65 | + |
| 66 | + const signature = await walletClient.signTypedData({ |
| 67 | + domain: { |
| 68 | + ...AZETH_FACTORY_DOMAIN, |
| 69 | + chainId: BigInt(chainId), |
| 70 | + verifyingContract: factoryAddress, |
| 71 | + }, |
| 72 | + types: CREATE_ACCOUNT_TYPES, |
| 73 | + primaryType: 'CreateAccount', |
| 74 | + message: { |
| 75 | + owner: params.owner, |
| 76 | + salt, |
| 77 | + guardrails: { |
| 78 | + maxTxAmountUSD: params.guardrails.maxTxAmountUSD, |
| 79 | + dailySpendLimitUSD: params.guardrails.dailySpendLimitUSD, |
| 80 | + guardianMaxTxAmountUSD: params.guardrails.guardianMaxTxAmountUSD, |
| 81 | + guardianDailySpendLimitUSD: params.guardrails.guardianDailySpendLimitUSD, |
| 82 | + guardian: params.guardrails.guardian, |
| 83 | + emergencyWithdrawTo: params.guardrails.emergencyWithdrawTo, |
| 84 | + }, |
| 85 | + protocolsHash, |
| 86 | + tokensHash, |
| 87 | + agentURIHash, |
| 88 | + nonce, |
| 89 | + }, |
| 90 | + }); |
| 91 | + |
| 92 | + return { signature, nonce }; |
| 93 | +} |
| 94 | + |
| 95 | +/** Submit a signed CreateAccount to the relay endpoint. |
| 96 | + * Returns null for 429 (rate-limited) or 503 (relay unavailable). */ |
| 97 | +export async function submitToRelay( |
| 98 | + serverUrl: string, |
| 99 | + params: CreateAccountParams, |
| 100 | + salt: `0x${string}`, |
| 101 | + agentURI: string, |
| 102 | + signature: `0x${string}`, |
| 103 | + chain: string, |
| 104 | +): Promise<CreateAccountResult | null> { |
| 105 | + const response = await fetch(`${serverUrl}/api/v1/relay/create-account`, { |
| 106 | + method: 'POST', |
| 107 | + headers: { 'Content-Type': 'application/json' }, |
| 108 | + body: JSON.stringify({ |
| 109 | + owner: params.owner, |
| 110 | + salt, |
| 111 | + guardrails: { |
| 112 | + maxTxAmountUSD: params.guardrails.maxTxAmountUSD.toString(), |
| 113 | + dailySpendLimitUSD: params.guardrails.dailySpendLimitUSD.toString(), |
| 114 | + guardianMaxTxAmountUSD: params.guardrails.guardianMaxTxAmountUSD.toString(), |
| 115 | + guardianDailySpendLimitUSD: params.guardrails.guardianDailySpendLimitUSD.toString(), |
| 116 | + guardian: params.guardrails.guardian, |
| 117 | + emergencyWithdrawTo: params.guardrails.emergencyWithdrawTo, |
| 118 | + }, |
| 119 | + protocols: params.protocols ?? [], |
| 120 | + tokens: params.tokens ?? [], |
| 121 | + agentURI, |
| 122 | + signature, |
| 123 | + chain, |
| 124 | + }), |
| 125 | + signal: AbortSignal.timeout(120_000), |
| 126 | + }); |
| 127 | + |
| 128 | + if (!response.ok) { |
| 129 | + // 429 = rate limited, 503 = relay unavailable — caller should fall back |
| 130 | + if (response.status === 429 || response.status === 503) { |
| 131 | + return null; |
| 132 | + } |
| 133 | + const body = await response.json().catch(() => null) as RelayResponse | null; |
| 134 | + throw new AzethError( |
| 135 | + body?.error?.message ?? `Relay error: HTTP ${response.status}`, |
| 136 | + 'NETWORK_ERROR', |
| 137 | + ); |
| 138 | + } |
| 139 | + |
| 140 | + const body = await response.json() as RelayResponse; |
| 141 | + return { |
| 142 | + account: body.data.account, |
| 143 | + tokenId: BigInt(body.data.tokenId), |
| 144 | + txHash: body.data.txHash, |
| 145 | + }; |
| 146 | +} |
| 147 | + |
| 148 | +/** Try gasless creation via relay, return null if relay unavailable or rate-limited. |
| 149 | + * Falls back gracefully when the factory doesn't support createAccountWithSignature |
| 150 | + * (nonces() call fails), relay is down, or relay returns 429/503. */ |
| 151 | +export async function createAccountGasless( |
| 152 | + publicClient: PublicClient<Transport, Chain>, |
| 153 | + walletClient: WalletClient<Transport, Chain, Account>, |
| 154 | + addresses: AzethContractAddresses, |
| 155 | + params: CreateAccountParams, |
| 156 | + serverUrl: string, |
| 157 | + chain: string, |
| 158 | + salt: `0x${string}`, |
| 159 | + agentURI: string, |
| 160 | +): Promise<CreateAccountResult | null> { |
| 161 | + try { |
| 162 | + const { signature } = await signCreateAccount( |
| 163 | + walletClient, publicClient, addresses, params, agentURI, salt, |
| 164 | + ); |
| 165 | + return await submitToRelay(serverUrl, params, salt, agentURI, signature, chain); |
| 166 | + } catch { |
| 167 | + // Factory doesn't support gasless (nonces() reverts), relay down, timeout, |
| 168 | + // rate limited — fall back to direct on-chain tx |
| 169 | + return null; |
| 170 | + } |
| 171 | +} |
0 commit comments