@seedprotocol/publish 0.7.4-next.793.g6dd83dd → 0.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chainConfig-BKuFZqOU.js → chainConfig-DM9RSIMT.js} +1391 -1394
- package/dist/chainConfig-DM9RSIMT.js.map +1 -0
- package/dist/{ensureAutomationSessionKey-DgpGcDDd.js → ensureAutomationSessionKey-DTO5lxXB.js} +3 -3
- package/dist/{ensureAutomationSessionKey-DgpGcDDd.js.map → ensureAutomationSessionKey-DTO5lxXB.js.map} +1 -1
- package/dist/{ensureModularPublishBootstrap-C-z64vF-.js → ensureModularPublishBootstrap-BYySx3sx.js} +3 -3
- package/dist/{ensureModularPublishBootstrap-C-z64vF-.js.map → ensureModularPublishBootstrap-BYySx3sx.js.map} +1 -1
- package/dist/{ensureSmartWalletThenPublish-YoUtjqRN.js → ensureSmartWalletThenPublish-DiH5CKLY.js} +2 -2
- package/dist/{ensureSmartWalletThenPublish-YoUtjqRN.js.map → ensureSmartWalletThenPublish-DiH5CKLY.js.map} +1 -1
- package/dist/index.js +2 -2
- package/dist/{managedAccountAdmin-C2sRBf9X.js → managedAccountAdmin-rhHtJC4y.js} +2 -2
- package/dist/{managedAccountAdmin-C2sRBf9X.js.map → managedAccountAdmin-rhHtJC4y.js.map} +1 -1
- package/dist/{publishAuthorization-Dprnd1G4.js → publishAuthorization-Dx-4adsz.js} +2 -2
- package/dist/{publishAuthorization-Dprnd1G4.js.map → publishAuthorization-Dx-4adsz.js.map} +1 -1
- package/dist/{resolveRevokeAccount-BQWdziaJ.js → resolveRevokeAccount-CC9X1H9x.js} +2 -2
- package/dist/{resolveRevokeAccount-BQWdziaJ.js.map → resolveRevokeAccount-CC9X1H9x.js.map} +1 -1
- package/dist/services/publish/helpers/ensureEasSchemas.d.ts.map +1 -1
- package/dist/thirdweb.js +5 -5
- package/dist/{undeployedSmartAccount-96Jwrrl6.js → undeployedSmartAccount-uDk6iZjl.js} +2 -2
- package/dist/{undeployedSmartAccount-96Jwrrl6.js.map → undeployedSmartAccount-uDk6iZjl.js.map} +1 -1
- package/dist/{worker-CcBaiQEh.js → worker-Bv_xadel.js} +2 -2
- package/dist/{worker-CcBaiQEh.js.map → worker-Bv_xadel.js.map} +1 -1
- package/package.json +5 -5
- package/dist/chainConfig-BKuFZqOU.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chainConfig-DM9RSIMT.js","names":["_client","_clientKey","pollSmartWalletDeployed","ZERO_ADDRESS","ZERO_BYTES32","ZERO_ADDRESS","ZERO_BYTES32","seedClient","optimismSepolia","defineChain","ZERO_BYTES32","waitForItem","waitForItem","waitForItem","getPublishUploadData","sdkGetPublishUploadData","logger","waitForItem","getPublishUploadData","waitForItem","getPublishUploadData","logger","importDynamic","ZERO_BYTES32","isZero","ZERO_BYTES32","logger","ZERO_BYTES32","BYTES32_LEN","toHex32","toBytesHex","ZERO_BYTES32","logger","toHex32","ZERO_BYTES32","logger","pollDeployed","MSG_EAS_MISMATCH","ZERO_ADDRESS","logger","waitForItem","toHex32","ZERO_BYTES32","logger","ZERO_BYTES32","BYTES32_LEN","toHex32","logger","ZERO_BYTES32","TTL_MS","cache","inflight","ev","logger","getStateValue","coerceDataItemSigner","ev","ev","logger","logger","logger","__exportAll","defineChain$1","optimismSepolia$1","Arweave","debug","EAS_SCHEMA_NAME_ATTESTATION_UID","MANAGED_ACCOUNT_FACTORY_ADDRESSES","MULTI_PUBLISH_ABI_REFERENCE_ADDRESS_OP_SEPOLIA","SEED_PROTOCOL_CONTRACT_ADDRESS_OP_SEPOLIA","PublishMachineStates","LONG_RUNNING_PUBLISH_STATES","PERIODIC_SAVE_INTERVAL_MS","DEFAULT_PUBLISH_CHAIN","optimismSepolia","DEFAULT_TURBO_UPLOAD_URL","DEFAULT_TURBO_PAYMENT_URL","PublishPaymentConfigError","message","resolvePublishSender","config","resolveSponsorGas","explicit","resolvePublishPayment","sender","gas","userStorage","resolveUseArweaveBundler","assertPublishPaymentConfig","payment","EAS_ERRORS_ABI","attestationRequestData","easAbi","multiPublishAbi","publisherReadWriteAbi","publisherEventsAbi","managedAccountFactoryAbi","executorEventsAbi","executorModuleAbi","seedExecutorRouterAbi","MODULE_TYPE_EXECUTOR","schemaRegistryAbi","AttestationVerificationError","seedLocalId","expectedSchemas","foundSchemas","code","stringifyUnderlyingCause","u","nested","maxLen","o","parts","ManagedAccountPublishError","extra","underlyingCause","managedAddress","PublishTransactionRevertedError","transactionHash","receipt","isManagedAccountPublishError","Eip7702ModularAccountPublishError","modularAddress","eip7702ModularCodes","isEip7702ModularAccountPublishError","isRouterNonModularCoreAccountError","msg","cause","_client$1","_clientKey$1","publishRpcFetchOptions","secret","getPublishConfig","createPublishPublicClient","chain","getPublishViemChain","rpcUrl","getPublishRpcUrl","fetchOptions","createPublicClient","http","getPublishPublicClient","key","waitForPublishReceipt","readUntil","value","read","i","attempts","accept","resolve","intervalMs","isContractDeployed","getBlockTimestampMs","block","DEFAULT_DEPLOY_POLL_ATTEMPTS","DEFAULT_DEPLOY_POLL_INTERVAL_MS","pollSmartWalletDeployed$1","smartWalletAddress","publishIndexResolver","indexByLocalId","requests","r","pu","publishIndex","encodeMultiPublish","publishIndexes","encodeFunctionData","encodeExecutorMultiPublish","to","readExecutorModuleIsInitialized","moduleAddress","account","readExecutorModuleEas","readSeedExecutorRouter","executor","eas","readFactorySeedExecutor","requireManagedAccountFactoryAddress","client","extension","factory","toFunctionSelector","getAbiItem","zeroAddress","readSeedExecutorInstalled","encodeInstallSeedExecutor","encodeSetEas","readGetEas","readIsActiveSigner","signer","readIsAdmin","readFactoryGetAddress","adminSigner","data","encodeCreateAccount","admin","ZERO_ADDRESS$3","encodeEasAttest","easContractAddress","params","encodeEasMultiAttest","encodeEasMultiRevoke","d","ZERO_BYTES32$5","readSchemaRecord","result","uid","encodeRegisterSchema","ZERO_ADDRESS$2","ZERO_BYTES32$4","prepareEasAttest","prepareEasMultiAttest","encodeBytes32","encodeAbiParameters","getAttestationUidFromReceipt","getAttestedUidsFromReceipt","want","logs","l","parsed","parseEventLogs","out","ev","schemaUid","prepareEasMultiRevoke","publishErrorsAbi","findRevertData","err","BaseError","isRevert","NO_DATA_REASON","describeRevert","noDataReason","decoded","decodeErrorResult","args","describeFailedUserOp","revertData","txHash","userOpFailureError","reverted","errorChain","cur","selectorNames","errorNameForSelector","item","selector","explainUserOpError","e","failed","signature","name","session","waitUntilSeedInitialized","setPublishWallet","next","owned","a","claimAs","getPublishWallet","clearPublishWallet","isNonceTooLowError","retryNonceTooLow","attempt","send","delayMs","SEED_SIGNER_BRAND","SEED_TX_SENDER_BRAND","brandSigner","brandTxSender","isSeedSigner","isSeedTxSender","isPublishWallet","fromEthersWallet","address","wallet","raw","bytes","ethers","tx","asSeedSigner","asSeedTxSender","asPublishWallet","cached","getPublishThirdwebChain","ref","source","getConfigRef","viemChain","LOCAL_CHAIN_IDS","isLocalThirdwebChain","host","logGas","printable","k","v","stage","gasFields","pad","op","thirdwebAccount_exports","asSeedSignerFromThirdweb","asThirdwebPublishWallet","fromThirdwebAccount","explicitClient","options","publishThirdwebClient_exports","transaction","prepareTransaction","sendTransaction","error","accountOrWallet","PublishChainConfigError","chainId","problems","verified","configKey","cfg","runChecks","rpcChainId","redactRpcUrl","contracts","results","label","fix","url","verifyPublishChain","isLegacyModularExecutorAttester","attester","additionalGetter","getGetAdditionalSyncAddresses","additional","attesterLower","isAutomationRevoke","signerAddress","n","isAutomationSessionActive","ALREADY_REVOKED_SELECTOR","ACCESS_DENIED_SELECTOR","sameAddress","b","revertMatches","resolveRevokeWallet","registered","thirdweb_exports","getConnectedAccount","revokeAccount","resolveRevokeAccount","findRevokedUids","revoked","uids","revokeBatch","req","txSender","revokeAttestations","assertLocalDbChain","getAttesterForSeed","versionRows","metadataRows","getVersionsForSeedUid","seedUid","getMetadataAttestationUidsForSeedUid","versionUids","isValidEasAttestationUid","metadataBySchema","list","VERSION_SCHEMA_UID","seedSchemaUid","revokedAt","updateSeedRevokedAt","assignRestoreFromDb","assign","event","incomingProcesses","incomingSubscriptions","getArweave","BaseArweaveClient","ArweaveModule","ZERO_BYTES32$3","waitForItem$1","Item","interval","found","deserializeChunks","serialized","s","c","p","serializeChunks","chunks","createArweaveTransactions","fromPromise","context","publishOpts","def","publishUploads","signArweaveTransactions","arweaveJwk","uploads","arweave","jwk","upload","json","serializedChunks","rest","attrs","createArweaveTransactionsPhase2","preparingHtmlEmbedded","policy","prepareHtmlEmbeddedImagesForPublish","toUploadedPairs","txs","ups","t","id","rewritingHtmlEmbedded","pairs","rewriteHtmlEmbeddedImagesOnDisk","getPublishUploadData$1","getPublishUploadData","SIG_TYPE_ETHEREUM","PLACEHOLDER_MESSAGE","ANCHOR_LENGTH","UINT64_MASK","buildPublishAnchorBytes","hash","timestampMs","walletAddress","uniqueness","encodeTargetOrAnchorSection","isEthersWallet","writeZigZagVInt","m","pos","offset","byte","serializeTags","tags","encoder","temp","appendLong","len","tag","nameBytes","valueBytes","totalLength","sum","chunk","writeUint64LE","buf","view","sha384","concat","deepHash","enc","acc","chunkHash","getSignatureData","ownerBytes","rawTarget","rawAnchor","rawTags","rawData","buildMessageBytes","serializedTags","numTagsBytes","numTagBytesBytes","messageparts","messageLength","part","assembleDataItemAndId","sigTypeBytes","fullLength","hashBuffer","base64url","createSignedDataItem","pubKeyHex","signatureData","createSignedDataItemWithAccount","placeholderHex","placeholderSig","digest","signatureDataHex","sigHex","getTagsStartOffset","targetFlag","targetPresent","anchorFlag","anchorPresent","sliceTargetAndAnchor","tagsStart","anchorStart","verifyDataItem","minLength","numTagBytes","tagsEnd","recoveredPubKey","recoveredBytes","binary","logger$12","signBundlerUploadDataList","arweaveTransactions","signedDataItems","signDataItems","uploadDataList","dataItemSigner","items","randomUniq","dataItem","seedSigner","createArweaveDataItems","uploadDataOpts","executeCreateArweaveDataItemsPhase2","createArweaveDataItemsPhase2","PUBLISH_AUTHORIZATION_HEADER","PublishNotAuthorizedError","reason","runAuthorizePublish","hook","answer","request","publishAuthorizationHeaders","authorization","BASE64_CHUNK_SIZE","arrayBufferToBase64","buffer","formDataToSerializableParts","formData","entry","base64","file","uploadServerErrorMessage","status","body","transactionKeys","uploadNetworkErrorMessage","technicalMessage","postUploadArweaveStart","api","headers","res","sendReimbursementRequest","reimbursementTransactionId","transactions","dataBlob","chunksBlob","jsonBlob","serverMessage","uploadApiBaseUrl","technicalMsg","errMsg","pollForConfirmation","requestResponse","response","logger$11","ensureUint8Array","uploadData","fromCallback","ctx","input","resumeState","startIndex","total","rawTransaction","uploader","uploaderState","dataBytes","sendBack","InsufficientStorageCreditsError","amounts","getJson","text","getTurboBalanceWinc","endpoints","getTurboPriceWinc","getTurboFreeUploadLimitBytes","uploadDataItemToTurbo","getTurboDataItemStatus","assertTurboCanPay","freeLimit","paid","itemSizes","size","required","balance","ethereumSignerOfDataItem","owner","computeAddress","importDynamic$1","readNodeFile","readFile","filename","rawBytesOf","resolved","uploadToTurbo","raws","turbo","BATCH_UPLOAD_TIMEOUT_MS","importDynamic","nodeFsPromisesCache","getNodeFsPromises","mod","uploadViaBundler","storage","useArweaveBundler","bundlerUrl","itemCount","getRawCache","rawByteLength","nodeFsPromises","totalSize","lengths","payload","controller","uploadTimeoutId","succeeded","attestationMsFromReceipt","bn","toHex32Normalized","listCreatedAttestationPairsFromReceipt","abi","useModularExecutor","su","isZero$1","sameSchema","expandPropertySlots","att","count","propertyName","seedPublishedEvents","contractAddress","decodeAbiParameters","attributeMultiPublishReceipt","created","createdUids","seedVersionSchemas","attested","published","contractAddressForEvents","slotsByRequest","seedVersionCount","propertyCount","propertiesInCreated","createdAt","attestedAt","publishedAt","takeCreated","slots","propertySource","legacySeed","legacyVersion","got","j","slot","logger$10","ZERO_BYTES32$2","PERSIST_SEED_UID_TIMEOUT_MS","persistSeedUidFromPublishResult","match","normalizedRequests","persistSeedUidSafely","persist","timeout","reject","attestationCreatedAtMs","BYTES32_LEN$2","toHex32$2","arr","toBytesHex$1","hex","hasCrossPayloadUnresolved","localIds","reqs","filterPropertiesToUpdateForBatch","propertiesToUpdate","batchLocalIds","placeholderData","ZERO_ADDRESS","normalizePublishRequest","listOfAttestations","dataArr","applyPropertiesToUpdatePlaceholders","targetId","targetReq","byLocalId","logger$9","isZero","nonZero","recordMultiPublishReceipt","attributed","attMs","versionUid","updateVersionUid","publisherAddress","propertyPairs","applyPropertyAttestationUidsFromPublish","rootSeedLocalId","recordRelatedSeedUid","related","getClient","_client","_clientKey","thirdwebClientId","thirdwebSecretKey","createThirdwebClient","CALL_GAS_HEADROOM_BPS","paymasterAndDataOf","seedPaymaster","userOp","thirdwebClient","first","getPaymasterAndData","est","estimateUserOpGas","raised","signed","ExternalWalletsForDeploy","appMetadata","deployManagedAccountViaFactory","deploySmartWalletContract","getConnectedManagedAccountAddress","getConnectedModularAccount","getManagedAccountWallet","getModularAccountWallet","getSharedPublishInAppWalletStorage","getSmartWalletAddressForAdmin","getWalletsForConnectButton","isSmartWalletDeployed","pollSmartWalletDeployed","resolveSmartWalletForPublish","syncPublishInAppAuthToken","useActiveSmartWalletContract","useLocalWalletAccount","wallets","logger$8","SEED_IN_APP_SESSION_PREFIX","_publishInAppWalletStorage","bareKey","prefixedKey","bare","prefixed","syncedBareToPrefixed","syncedPrefixedToBare","connectManagedAccountWallet","managedAccountWallet","createWallet","localWalletAccount","setLocalWalletAccount","useState","useRef","useEffect","useActiveAccount","contract","setContract","getContract","adminAddress","accountContract","localAccount","deploySmartAccount","managedAccount","managedAccountFactoryFor","IN_APP_AUTH_OPTIONS","_managedInAppWallet","factoryAddress","resolveThirdwebWalletOptions","sponsorGas","inAppWallet","_modularInAppWallet","modularWalletMode","MSG_LEGACY_ROUTER","MSG_NOT_INITIALIZED","MSG_EAS_MISMATCH$1","MSG_READ_FAILED","requireModuleAddress","module","lacksExecutorRouterExtension","assertExecutorModuleReadyForAccount","initialized","moduleEas","expected","isInsufficientFunds","simulateCallFromAccount","call","withBalance","parseEther","requireSimulation","action","MODULE_INSTALL_MSG","getPublishChainName","ensureExecutorModuleInstalled","modularAccountModuleContract","router","installViaRouterExtension","pinnedExecutor","configuredModule","getManagedAccountAdmin","installedEasFromReceipt","simulateInstallSeedExecutor","isAddressEqual","log","MSG_UNAVAILABLE","MSG_NOT_DEPLOYED","MSG_NOT_DEPLOYED_AFTER_ATTEMPT","MSG_FAILED_DEPLOY","ensureManagedAccountReady","getManagedAccountSigningAccount","managedWallet","DEPLOY_TIMEOUT_MS","deploySmartWalletWithTimeout","timeoutId","tryDeployManagedAccount","deployParams","modularAccount","modularWallet","runModularExecutorPublishPrep","state","signingAccount","resolvePublishWallet","getSchemaRecord","registerSchema","ZERO_ADDRESS$1","prepareNameSchemaAttestation","encodedData","SchemaEncoder","NO_EXPIRATION","ZERO_BYTES32","RESOLVER_ADDRESS","REVOCABLE","NAME_SCHEMA_DEF","VERSION_SCHEMA_DEF","chainsWithBaseSchemas","getModelNamesForItem","getSegmentedItemProperties","modelNames","prop","itemRelationProperties","itemImageProperties","dataType","normalizeDataType","ModelPropertyDataTypes","itemListProperties","sendAndWait","easTypeForDataType","INTERNAL_DATA_TYPES","throwIfAutomationCannotRegister","blockSchemaRegistration","schemaDef","assertBaseSchemas","versionSchemaUid","SchemaRegistry","missing","resolveBlockSchemaRegistration","ensureEasSchemasForItem","ensureEasSchemasForItemResolved","allProperties","itemBasicProperties","registeredSchemaUids","registeredModelSchemaUids","modelName","easName","setSchemaUidForModel","storageSchemaDef","storageSchemaUid","setSchemaUidForSchemaDefinition","property","easDataTypeRaw","listRelationName","listRelationEasPropertyName","propertyNameSnakeCase","easPropertyNameForPublish","easDataTypeForLookup","schema","getEasSchemaForItemProperty","onChainRecord","relatedItems","getRelatedItemsForPublish","relatedItem","verifyArweaveTransactionsExist","txIds","getUploadPipelineTransactionStatus","arweaveUploadVerificationBaseUrl","txId","detail","PHASE_PENDING","enqueueArweaveL1FinalizeJobsFromPublishContext","db","BaseDb","now","ar","up","dataItemId","arweaveL1FinalizeJobs","MSG_SET_EAS","MSG_EAS_MISMATCH","MSG_FIXED_EAS_MISMATCH","current","normAddr","expectedEasFromConfig","readCurrentEas","assertManagedAccountEasMatchesConfig","ensureManagedAccountEasConfigured","logger$7","isExecutorModuleAddress","resolvePublishRouting","routeToExecutorModule","createAttestations","routing","activeWallet","uploadDataWithTxIds","arweaveTransaction","requestData","sessionKeyAddress","automationActive","prep","ensureModularPublishBootstrap","sendPublishTx","needsSequential","effectiveRequests","lastAttestationReceipt","batchExtraUids","workingPayload","resolvedUids","resolvedVersionUids","resolvePublishPayloadValues","rawReq","normalizedOne","byLocalIdSingle","pair","recorded","seedUidFromTx","payloadForContract","itemWithPersist","rootSeedUid","clearHtmlEmbeddedImageCoPublishRows","rootForBatch","collectPublishedBatch","logger$6","ZERO_BYTES32$1","BYTES32_LEN$1","toHex32$1","VERIFY_DELAY_MS","VERIFY_MAX_ATTEMPTS","verifyAttestations","easProperties","lastError","getItemPropertiesFromEas","foundSet","logger$5","BYTES32_LEN","toHex32","toBytesHex","waitForItem","isListAttestation","hasUnresolvedRef","applyResolvedRefs","rawAtts","outData","target","createAttestationsDirectToEas","publishWallet","lastAttestationMs","createdSeeds","persistCreatedSeed","attestationMs","newSeedUid","newVersionUid","attestTx","seedUidFromReceipt","versionUidFromReceipt","multiRequests","multiTx","sameLen","rootRequest","rootReq","resolveItem","itemNeedsArweaveUpload","itemHasPublishUploadCandidates","activePublishProcesses","resolveAttestationStrategy","refuseUndeployedSmartAccount","problem","undeployedPublisherProblem","checking","isItemOwned","unpublishedRelatedItems","getUnpublishedRelatedItems","publishMode","RelatedItemUnpublishedError","validation","validateItemForPublish","attestationStrategy","refusal","needsArweave","useBundler","PUBLISH_GAS_HEURISTICS","heuristicPublishGas","work","TTL_MS$1","cache$1","inflight$1","readConfigGetter","fetchCoinbaseSpot","symbol","fetchDefaultTokenPrices","ethUsd","arUsd","getCachedTokenPrices","getter","prices","resetTokenPriceCache","TTL_MS","ARWEAVE_PRICE_REF_BYTES","cache","inflight","fetchGasPriceWei","fetchWinstonPerByte","winston","getCachedMarketRates","gasPriceWei","winstonPerByte","resetMarketRateCache","WINSTON_PER_AR","WEI_PER_ETH","readPublishFlags","roundUsd","combinePublishCostEstimate","evmUserPays","flags","arweaveUserPays","arweavePath","evmWei","rates","evmEth","evmUsd","estimatePublishCost","summarizePublishWork","configAuthorizePublish","authorizing","authorizePublish","attestationUsesDirectEas","attestationUsesMultiPublish","getErrorFromEvent","publishMachine","setup","errors","FAILURE","SUCCESS","batch","onPublished","setPublishManagerRef","getPublishManagerRef","logger$4","getStateValue$1","snapshot","isLongRunningState","stateValue","subscribe","managerRef","periodicSaveIntervalId","clearPeriodicSave","startPeriodicSaveIfNeeded","live","publishProcess","subscription","type","resolvers","nextToken","registerCreatePublishResolver","token","settleCreatePublish","actor","coerceWallet","coerceDataItemSigner$1","createPublish","enqueueActions","enqueue","publishProcesses","createToken","publishRunId","publishCfg","arweaveUploadTags","spawn","settledPublishes","subscriptions","subscriptionProcess","retryAttestations","stopScopedOrStandaloneChild","child","self","logger$3","saveWriteTailBySeed","enqueueSaveWrite","write","isTerminalPublishRowStatus","statusFromSnapshot","MAX_ERROR_MESSAGE_LENGTH","MAX_ERROR_DETAILS_LENGTH","MAX_ERROR_CODE_LENGTH","jsonStringifyPersistedSnapshot","publishRunIdFromSnapshot","errorMessageOf","errorCodeOf","errorFieldsFromContext","errorMessage","errorStep","errorCode","errorDetails","markInProgressPublishInterrupted","existing","and","eq","desc","savePublish","persistedSnapshot","snapshotStr","errorFields","rec","incomingRunId","latest","schemaId","logger$2","getLockManager","held","publishLockName","tryHoldPublishLock","locks","lock","release","releasePublishLock","releaseAllPublishLocks","isHoldingPublishLock","stopPublish","newPublishProcesses","newSubscriptions","logger$1","stopAll","query","addSubscription","newSubscription","HEAVY_PUBLISH_CONTEXT_KEYS","SECRET_PUBLISH_CONTEXT_KEYS","STRIPPED_KEYS","isPlainObject","proto","stripPublishSnapshotFields","seen","getPersistableSnapshot","requestSavePublish","publishDone","finished","newSettled","removeSubscription","RESTORE_DB_WAIT_MS","RESTORE_DB_POLL_MS","envMs","fallback","waitForDb","deadline","maxWaitMs","pollMs","getStateValue","isRestorableSnapshot","isPersistedActorRef","patchPublishContextItemForRestore","record","restoreFromDb","_restoreFromDb","inProgress","bySeed","sorted","publishProcessRecords","publishProcessRecord","createActor","empty","queueCreatePublish","drainPendingCreates","pending","logger","publishManagerMachine","publishManager","publishManagerStarted","ensurePublishManagerStarted","PublishManager","sub","heldBefore","subscriptionActor","seedSignerToLocalAccount","assertBundlerSupportsEntryPoint08","supported","entryPoint08Address","createPermissionlessTxSender","publicClient","simpleAccount","to7702SimpleSmartAccount","pimlicoClient","createPimlicoClient","paymasterUrl","smartAccountClient","createSmartAccountClient","sponsored","userOpHash","assertUserOpSucceeded","coerceDataItemSigner","ensureWalletThenPublish","ensureSmartWalletThenPublish","w","RECOVERABLE_FAILURE_STATES","waitForPublishActor","settled","finish","check","step","publishItem","expectEasReadChain","configRef","setConfigRef","initPublish","easChain","resolvePublishEasChain","configureEasReadChain","setGetPublisherForNewSeeds","setPublishExecutor","setRevokeExecutor","whenLeaderTab","setAdditionalSyncAddresses","configurePublish","tw","arweaveGraphqlUrl","DEFAULT_ARWEAVE_GRAPHQL_URL","accountMode","resolveAutoDeployEip7702ModularAccount","resolveEasChainDeployment","thirdwebAccountFactoryAddress"],"sources":["../src/helpers/constants.ts","../src/helpers/defaultChain.ts","../src/payment.ts","../src/helpers/abi/eas.ts","../src/helpers/abi/publisher.ts","../src/helpers/abi/factory.ts","../src/helpers/abi/executor.ts","../src/helpers/abi/seedExecutorRouter.ts","../src/helpers/abi/schemaRegistry.ts","../src/errors.ts","../src/helpers/chainClient.ts","../src/helpers/contracts/index.ts","../src/helpers/easDirect.ts","../src/helpers/abi/seedErrors.ts","../src/helpers/describeRevert.ts","../src/helpers/publishWalletRegistry.ts","../src/helpers/retryNonceTooLow.ts","../src/helpers/seedSigner.ts","../src/helpers/thirdwebChain.ts","../src/helpers/gasLog.ts","../src/helpers/adapters/thirdwebAccount.ts","../src/helpers/verifyPublishChain.ts","../src/services/revoke/revokeAttestations.ts","../src/services/publishManager/actions/assignRestoreFromDb.ts","../src/helpers/blockchain.ts","../src/services/publish/actors/utils.ts","../src/services/publish/actors/createArweaveTransactions.ts","../src/services/publish/actors/createArweaveTransactionsPhase2.ts","../src/services/publish/actors/preparingHtmlEmbedded.ts","../src/services/publish/actors/rewritingHtmlEmbedded.ts","../src/services/publish/helpers/getPublishUploadData.ts","../src/helpers/arweave.ts","../src/services/publish/actors/createArweaveDataItems.ts","../src/services/publish/actors/createArweaveDataItemsPhase2.ts","../src/authorization.ts","../src/helpers/uploadApi.ts","../src/services/publish/actors/sendReimbursementRequest.ts","../src/services/publish/actors/pollForConfirmation.ts","../src/services/publish/actors/uploadData.ts","../src/helpers/turbo.ts","../src/services/publish/helpers/uploadToTurbo.ts","../src/services/publish/actors/uploadViaBundler.ts","../src/services/publish/helpers/receiptAttestationMs.ts","../src/services/publish/actors/seedUidHelpers.ts","../src/services/publish/actors/multiPublishReceipt.ts","../src/services/publish/actors/persistSeedUid.ts","../src/services/publish/actors/publishRequestNormalize.ts","../src/services/publish/actors/recordMultiPublishReceipt.ts","../src/helpers/publishThirdwebClient.ts","../src/helpers/seedPaymaster.ts","../src/helpers/thirdweb.ts","../src/helpers/executorModuleReadiness.ts","../src/helpers/ensureExecutorModule.ts","../src/helpers/ensureManagedAccountReady.ts","../src/helpers/resolvePublishWallet.ts","../src/helpers/schemaRegistry.ts","../src/helpers/nameSchemaAttestation.ts","../src/services/publish/helpers/ensureEasSchemas.ts","../src/services/publish/helpers/verifyArweaveTransactionsExist.ts","../src/services/arweaveL1Finalize/enqueue.ts","../src/helpers/ensureManagedAccountEasConfigured.ts","../src/services/publish/actors/createAttestations.ts","../src/services/publish/helpers/verifyAttestations.ts","../src/services/publish/actors/createAttestationsDirectToEas.ts","../src/services/publish/helpers/itemNeedsArweave.ts","../src/services/publish/actors/checking.ts","../src/services/publishCost/gasHeuristics.ts","../src/services/publishCost/tokenPrices.ts","../src/services/publishCost/marketRates.ts","../src/services/publishCost/estimatePublishCost.ts","../src/services/publish/actors/authorizing.ts","../src/services/publish/index.ts","../src/services/publishManager/publishManagerRef.ts","../src/services/publishManager/actors/subscribe.ts","../src/services/publishManager/createPublishResult.ts","../src/services/publishManager/actions/createPublish.ts","../src/services/publishManager/actions/retryAttestations.ts","../src/services/publishManager/actions/stopScopedOrStandaloneChild.ts","../src/services/publishManager/actors/savePublish.ts","../src/services/publishManager/publishLocks.ts","../src/services/publishManager/actions/stopPublish.ts","../src/services/publishManager/actions/stopAll.ts","../src/services/publishManager/actions/query.ts","../src/services/publishManager/actions/addSubscription.ts","../src/services/publishManager/actions/requestSavePublish.ts","../src/services/publishManager/actions/publishDone.ts","../src/services/publishManager/actions/removeSubscription.ts","../src/services/publishManager/actors/restoreFromDb.ts","../src/services/publishManager/actions/queueCreatePublish.ts","../src/services/publishManager/actions/drainPendingCreates.ts","../src/services/publishManager/index.ts","../src/helpers/adapters/permissionlessTxSender.ts","../src/helpers/ensureWalletThenPublish.ts","../src/helpers/publishItem.ts","../src/config.ts","../src/helpers/chainConfig.ts"],"sourcesContent":["/**\n * Constants for the publish package.\n */\n/**\n * @deprecated OP Stack predeploy; wrong on non-OP chains. Use `getPublishConfig().schemaRegistryAddress`.\n */\nexport const SCHEMA_REGISTRY_ADDRESS =\n '0x4200000000000000000000000000000000000020' as const\n\n/** Schema #1 (Name a Schema) - universal UID for naming attestations */\nexport const EAS_SCHEMA_NAME_ATTESTATION_UID =\n '0x44d562ac1d7cd77e232978687fea027ace48f719cf1d58c7888e509663bb87fc' as const\n\n/**\n * Thirdweb ManagedAccount factories Seed Protocol has deployed, keyed by chain id.\n * Chains not listed here need `PublishConfig.managedAccountFactoryAddress` for managed / modular flows.\n */\nexport const MANAGED_ACCOUNT_FACTORY_ADDRESSES: Readonly<Record<number, `0x${string}`>> = {\n 11155420: '0x76f47d88bfaf670f5208911181fcdc0e160cb16d',\n}\n\n/**\n * @deprecated Optimism Sepolia only. Use `getPublishConfig().thirdwebAccountFactoryAddress`.\n */\nexport const THIRDWEB_ACCOUNT_FACTORY_ADDRESS =\n '0x76f47d88bfaf670f5208911181fcdc0e160cb16d' as const\n\n/**\n * @deprecated OP Stack predeploy; wrong on non-OP chains. Use `getPublishConfig().easContractAddress`.\n */\nexport const EAS_CONTRACT_ADDRESS =\n '0x4200000000000000000000000000000000000021' as const\n\n/**\n * Optimism Sepolia address of the deployment the **`multiPublish` ABI** was generated from.\n *\n * **Do not use as the transaction `to` for user publishes.** Runtime `multiPublish` targets the\n * publisher’s deployed ManagedAccount (non-modular), `managedAddress` (modular), or is not used\n * when attesting via direct EAS (EOA path).\n */\nexport const MULTI_PUBLISH_ABI_REFERENCE_ADDRESS_OP_SEPOLIA =\n '0xcd8c945872df8e664e55cf8885c85ea3ea8f2148' as const\n\n/**\n * @deprecated Misleading name: this is the ABI reference deployment, not a shared on-chain router.\n * Use {@link MULTI_PUBLISH_ABI_REFERENCE_ADDRESS_OP_SEPOLIA}.\n */\nexport const SEED_PROTOCOL_CONTRACT_ADDRESS_OP_SEPOLIA =\n MULTI_PUBLISH_ABI_REFERENCE_ADDRESS_OP_SEPOLIA\n\nexport const PublishMachineStates = {\n SUCCESS: 'success',\n FAILURE: 'failure',\n} as const\n\n/** States that run for a long time without snapshot changes; need periodic saves. */\nexport const LONG_RUNNING_PUBLISH_STATES = [\n 'pollingForConfirmation',\n 'uploadingData',\n 'uploadingViaBundler',\n 'uploadingViaBundlerPhase2',\n] as const\n\nexport const PERIODIC_SAVE_INTERVAL_MS = 30_000\n","import type { Chain } from 'viem'\nimport { optimismSepolia } from 'viem/chains'\n\n/** Default chain when apps omit `PublishConfig.chain`. */\nexport const DEFAULT_PUBLISH_CHAIN: Chain = optimismSepolia\n","import type { PublishConfig } from './config'\n\n/**\n * Who pays a publish's EVM gas: `'sponsored'` (a Thirdweb or ERC-4337 paymaster) or `'user'`\n * (the publishing account's own ETH).\n */\nexport type PublishGasPayer = 'sponsored' | 'user'\n\n/**\n * Who pays for Arweave storage: `'operator'` (the upload API at `uploadApiBaseUrl` funds it) or\n * `'user'` (see {@link PublishUserStorageConfig}).\n */\nexport type PublishStoragePayer = 'operator' | 'user'\n\n/** Default Turbo endpoints (ArDrive). */\nexport const DEFAULT_TURBO_UPLOAD_URL = 'https://upload.ardrive.io'\nexport const DEFAULT_TURBO_PAYMENT_URL = 'https://payment.ardrive.io'\n\n/**\n * How users pay for storage when `payment.storage` is `'user'`. The only provider so far is\n * Turbo: data items, signed by the user's EVM key as on the bundler path, go straight to the\n * Turbo upload service, which charges that address's Turbo credits (topped up with a card or\n * crypto through Turbo). Items under Turbo's free-tier size are free.\n */\nexport interface PublishUserStorageConfig {\n provider?: 'turbo'\n /** Turbo upload service. Default {@link DEFAULT_TURBO_UPLOAD_URL}. */\n uploadUrl?: string\n /** Turbo payment service (balances, prices). Default {@link DEFAULT_TURBO_PAYMENT_URL}. */\n paymentUrl?: string\n /**\n * Addresses whose shared Turbo credits pay first (Turbo's `x-paid-by`), e.g. an app wallet that\n * approved credits for its users. The signer's own credits cover the rest.\n */\n paidBy?: string[]\n}\n\n/**\n * Who pays for a publish. Each field is optional: leave it out to keep what the lower-level\n * settings (`thirdweb.sponsorGas`, `paymasterUrl`, ...) give. When set, it fills in those\n * settings' defaults, and `initPublish` throws if a setting contradicts it.\n */\nexport interface PublishPaymentConfig {\n gas?: PublishGasPayer\n storage?: PublishStoragePayer\n /** With `storage: 'user'`: the provider users pay. Defaults to Turbo. */\n userStorage?: PublishUserStorageConfig\n}\n\n/**\n * Which account sends a publish's transactions:\n * - `'modular'`: the user's Thirdweb managed account (`useModularExecutor`)\n * - `'eip7702'`: the permissionless EIP-7702 sender (`accountMode: 'eip7702'` with `bundlerUrl`)\n * - `'wallet'`: the registered publish wallet as-is (EIP-1193, ethers or a Thirdweb account)\n */\nexport type PublishSenderKind = 'modular' | 'eip7702' | 'wallet'\n\nexport interface ResolvedPublishPayment {\n sender: PublishSenderKind\n gas: {\n payer: PublishGasPayer\n /** Who sponsors when `payer` is `'sponsored'`. */\n sponsor?: 'thirdweb' | 'paymaster'\n }\n storage: {\n payer: PublishStoragePayer\n path: 'l1' | 'bundler'\n /** Where uploads go: the upload API, or (user-paid) Turbo directly. */\n uploadTo: 'upload-api' | 'turbo'\n /** Set when `uploadTo` is `'turbo'`. */\n turbo?: { uploadUrl: string; paymentUrl: string; paidBy: string[] }\n }\n}\n\nexport class PublishPaymentConfigError extends Error {\n constructor(message: string) {\n super(`@seedprotocol/publish: ${message}`)\n this.name = 'PublishPaymentConfigError'\n }\n}\n\ntype PaymentInputs = Pick<\n PublishConfig,\n 'payment' | 'useModularExecutor' | 'accountMode' | 'bundlerUrl' | 'paymasterUrl' | 'thirdweb' | 'useArweaveBundler'\n>\n\n/** The sender ensureWalletThenPublish and useSeedWallet use for this config. */\nexport function resolvePublishSender(config: PaymentInputs): PublishSenderKind {\n if (config.useModularExecutor) return 'modular'\n const accountMode = config.accountMode ?? (config.bundlerUrl ? 'eip7702' : 'eoa')\n if (accountMode === 'eip7702' && config.bundlerUrl) return 'eip7702'\n return 'wallet'\n}\n\n/**\n * `thirdweb.sponsorGas` with `payment.gas` as its default. Thirdweb wallets read this, so a\n * `payment: { gas: 'user' }` config builds unsponsored wallets without setting sponsorGas too.\n */\nexport function resolveSponsorGas(config: Pick<PublishConfig, 'payment' | 'thirdweb'>): boolean {\n const explicit = config.thirdweb?.sponsorGas\n if (explicit !== undefined) return explicit\n return config.payment?.gas !== 'user'\n}\n\n/**\n * Who pays gas and storage for this config, from the sender it selects. The publish flow and\n * {@link estimatePublishCost} both use this, so a cost estimate reports what a publish does.\n *\n * - modular: Thirdweb sponsors when `thirdweb.sponsorGas` (default true)\n * - eip7702: a paymaster sponsors (`paymasterUrl`, else the bundler), unless `payment.gas` is\n * `'user'`, which sends without one\n * - wallet: the user pays\n *\n * Operator-paid storage goes through the upload API on both paths. On the bundler path the\n * user's key signs data items and the operator pays for them. On the L1 path the user's Arweave\n * key pays the fee and the upload API reimburses it before the upload; the second pass for\n * deferred Html is not reimbursed. User-paid storage uploads data items to Turbo, charged to the\n * signer's credits.\n */\nexport function resolvePublishPayment(config: PaymentInputs): ResolvedPublishPayment {\n const sender = resolvePublishSender(config)\n let gas: ResolvedPublishPayment['gas']\n if (sender === 'modular') {\n gas = resolveSponsorGas(config) ? { payer: 'sponsored', sponsor: 'thirdweb' } : { payer: 'user' }\n } else if (sender === 'eip7702') {\n gas = config.payment?.gas === 'user' ? { payer: 'user' } : { payer: 'sponsored', sponsor: 'paymaster' }\n } else {\n gas = { payer: 'user' }\n }\n const storagePayer = config.payment?.storage ?? 'operator'\n if (storagePayer === 'user') {\n const userStorage = config.payment?.userStorage ?? {}\n return {\n sender,\n gas,\n storage: {\n payer: 'user',\n path: 'bundler',\n uploadTo: 'turbo',\n turbo: {\n uploadUrl: (userStorage.uploadUrl ?? DEFAULT_TURBO_UPLOAD_URL).replace(/\\/$/, ''),\n paymentUrl: (userStorage.paymentUrl ?? DEFAULT_TURBO_PAYMENT_URL).replace(/\\/$/, ''),\n paidBy: userStorage.paidBy ?? [],\n },\n },\n }\n }\n return {\n sender,\n gas,\n storage: {\n payer: 'operator',\n path: config.useArweaveBundler ? 'bundler' : 'l1',\n uploadTo: 'upload-api',\n },\n }\n}\n\n/** `useArweaveBundler` with `payment.storage: 'user'` as its default (user-paid storage uploads data items). */\nexport function resolveUseArweaveBundler(config: Pick<PublishConfig, 'payment' | 'useArweaveBundler'>): boolean {\n return config.useArweaveBundler ?? config.payment?.storage === 'user'\n}\n\n/**\n * Throws {@link PublishPaymentConfigError} when `payment` asks for something the other settings\n * can't deliver. Called by `initPublish`.\n */\nexport function assertPublishPaymentConfig(config: PaymentInputs): void {\n const payment = config.payment\n if (!payment) return\n const sender = resolvePublishSender(config)\n\n if (payment.gas === 'sponsored') {\n if (sender === 'wallet') {\n throw new PublishPaymentConfigError(\n \"payment.gas is 'sponsored', but publishes are sent from the connected wallet, which pays its own gas. \" +\n 'Set useModularExecutor (Thirdweb sponsorship) or bundlerUrl (EIP-7702 with a paymaster).',\n )\n }\n if (sender === 'modular' && config.thirdweb?.sponsorGas === false) {\n throw new PublishPaymentConfigError(\"payment.gas is 'sponsored' but thirdweb.sponsorGas is false.\")\n }\n }\n\n if (payment.gas === 'user') {\n if (sender === 'modular' && config.thirdweb?.sponsorGas === true) {\n throw new PublishPaymentConfigError(\"payment.gas is 'user' but thirdweb.sponsorGas is true.\")\n }\n if (sender === 'eip7702' && config.paymasterUrl) {\n throw new PublishPaymentConfigError(\n \"payment.gas is 'user' but paymasterUrl is set; remove it so the EIP-7702 sender pays its own gas.\",\n )\n }\n }\n\n if (payment.storage === 'user' && config.useArweaveBundler === false) {\n throw new PublishPaymentConfigError(\n \"payment.storage is 'user', which uploads data items to Turbo, but useArweaveBundler is false.\",\n )\n }\n if (payment.userStorage && payment.storage !== 'user') {\n throw new PublishPaymentConfigError(\"payment.userStorage is set but payment.storage is not 'user'.\")\n }\n}\n","/**\n * EAS contract ABI fragments + custom errors for revert decoding.\n */\n\nexport const EAS_ERRORS_ABI = [\n { type: 'error' as const, name: 'AccessDenied', inputs: [] },\n { type: 'error' as const, name: 'AlreadyRevoked', inputs: [] },\n { type: 'error' as const, name: 'InvalidRevocation', inputs: [] },\n { type: 'error' as const, name: 'InvalidRevocations', inputs: [] },\n { type: 'error' as const, name: 'InvalidSchema', inputs: [] },\n { type: 'error' as const, name: 'Irrevocable', inputs: [] },\n { type: 'error' as const, name: 'NotFound', inputs: [] },\n { type: 'error' as const, name: 'NotPayable', inputs: [] },\n { type: 'error' as const, name: 'InsufficientValue', inputs: [] },\n { type: 'error' as const, name: 'InvalidLength', inputs: [] },\n] as const\n\nconst attestationRequestData = [\n { name: 'recipient', type: 'address' },\n { name: 'expirationTime', type: 'uint64' },\n { name: 'revocable', type: 'bool' },\n { name: 'refUID', type: 'bytes32' },\n { name: 'data', type: 'bytes' },\n { name: 'value', type: 'uint256' },\n] as const\n\nexport const easAbi = [\n {\n type: 'function',\n name: 'attest',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'request',\n type: 'tuple',\n components: [\n { name: 'schema', type: 'bytes32' },\n {\n name: 'data',\n type: 'tuple',\n components: attestationRequestData,\n },\n ],\n },\n ],\n outputs: [{ type: 'bytes32' }],\n },\n {\n type: 'function',\n name: 'multiAttest',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'requests',\n type: 'tuple[]',\n components: [\n { name: 'schema', type: 'bytes32' },\n {\n name: 'data',\n type: 'tuple[]',\n components: attestationRequestData,\n },\n ],\n },\n ],\n outputs: [{ type: 'bytes32[]' }],\n },\n {\n type: 'function',\n name: 'multiRevoke',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'multiRequests',\n type: 'tuple[]',\n components: [\n { name: 'schema', type: 'bytes32' },\n {\n name: 'data',\n type: 'tuple[]',\n components: [\n { name: 'uid', type: 'bytes32' },\n { name: 'value', type: 'uint256' },\n ],\n },\n ],\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'getAttestation',\n stateMutability: 'view',\n inputs: [{ name: 'uid', type: 'bytes32' }],\n outputs: [\n {\n type: 'tuple',\n components: [\n { name: 'uid', type: 'bytes32' },\n { name: 'schema', type: 'bytes32' },\n { name: 'time', type: 'uint64' },\n { name: 'expirationTime', type: 'uint64' },\n { name: 'revocationTime', type: 'uint64' },\n { name: 'refUID', type: 'bytes32' },\n { name: 'recipient', type: 'address' },\n { name: 'attester', type: 'address' },\n { name: 'revocable', type: 'bool' },\n { name: 'data', type: 'bytes' },\n ],\n },\n ],\n },\n {\n type: 'event',\n name: 'Attested',\n inputs: [\n { name: 'recipient', type: 'address', indexed: true },\n { name: 'attester', type: 'address', indexed: true },\n { name: 'uid', type: 'bytes32', indexed: false },\n { name: 'schemaUID', type: 'bytes32', indexed: true },\n ],\n },\n ...EAS_ERRORS_ABI,\n] as const\n","/** Attestation request tuple shared by multiPublish variants. */\nconst attestationDataComponents = [\n { name: 'recipient', type: 'address' },\n { name: 'expirationTime', type: 'uint64' },\n { name: 'revocable', type: 'bool' },\n { name: 'refUID', type: 'bytes32' },\n { name: 'data', type: 'bytes' },\n { name: 'value', type: 'uint256' },\n] as const\n\nconst listOfAttestationsComponents = [\n { name: 'schema', type: 'bytes32' },\n {\n name: 'data',\n type: 'tuple[]',\n components: attestationDataComponents,\n },\n] as const\n\n/**\n * `multiPublish` (selector 0x2a29fadc) on SeedProtocolExtension and SeedProtocolExecutor, which take\n * the same `PublishRequestData`: `propertiesToUpdate` names its target by `publishIndex`, the\n * target's position in `requests`.\n */\nexport const multiPublishAbi = [\n {\n type: 'function',\n name: 'multiPublish',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'requests',\n type: 'tuple[]',\n components: [\n { name: 'localId', type: 'string' },\n { name: 'seedUid', type: 'bytes32' },\n { name: 'seedSchemaUid', type: 'bytes32' },\n { name: 'versionUid', type: 'bytes32' },\n { name: 'versionSchemaUid', type: 'bytes32' },\n { name: 'seedIsRevocable', type: 'bool' },\n {\n name: 'listOfAttestations',\n type: 'tuple[]',\n components: listOfAttestationsComponents,\n },\n {\n name: 'propertiesToUpdate',\n type: 'tuple[]',\n components: [\n { name: 'publishIndex', type: 'uint256' },\n { name: 'propertySchemaUid', type: 'bytes32' },\n ],\n },\n ],\n },\n ],\n outputs: [{ type: 'bytes32[]' }],\n },\n] as const\n\nexport const publisherReadWriteAbi = [\n {\n type: 'function',\n name: 'getEas',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'address' }],\n },\n {\n type: 'function',\n name: 'setEas',\n stateMutability: 'nonpayable',\n inputs: [{ name: '_eas', type: 'address' }],\n outputs: [{ type: 'string' }],\n },\n {\n type: 'function',\n name: 'isActiveSigner',\n stateMutability: 'view',\n inputs: [{ name: 'signer', type: 'address' }],\n outputs: [{ type: 'bool' }],\n },\n {\n type: 'function',\n name: 'isAdmin',\n stateMutability: 'view',\n inputs: [{ name: 'signer', type: 'address' }],\n outputs: [{ type: 'bool' }],\n },\n] as const\n\n/** Extension / ManagedAccount publisher events. */\nexport const publisherEventsAbi = [\n {\n type: 'event',\n name: 'CreatedAttestation',\n inputs: [\n {\n name: 'result',\n type: 'tuple',\n indexed: false,\n components: [\n { name: 'schemaUid', type: 'bytes32' },\n { name: 'attestationUid', type: 'bytes32' },\n ],\n },\n ],\n },\n {\n type: 'event',\n name: 'SeedPublished',\n inputs: [{ name: 'returnedDataFromEAS', type: 'bytes', indexed: false }],\n },\n] as const\n","/** Thirdweb ManagedAccount factory ABI (see `MANAGED_ACCOUNT_FACTORY_ADDRESSES` for deployments). */\nexport const managedAccountFactoryAbi = [\n {\n type: 'function',\n name: 'getAddress',\n stateMutability: 'view',\n inputs: [\n { name: '_adminSigner', type: 'address' },\n { name: '_data', type: 'bytes' },\n ],\n outputs: [{ type: 'address' }],\n },\n {\n type: 'function',\n name: 'createAccount',\n stateMutability: 'nonpayable',\n inputs: [\n { name: '_admin', type: 'address' },\n { name: '_data', type: 'bytes' },\n ],\n outputs: [{ type: 'address' }],\n },\n {\n type: 'function',\n name: 'getImplementationForFunction',\n stateMutability: 'view',\n inputs: [{ name: '_functionSelector', type: 'bytes4' }],\n outputs: [{ type: 'address' }],\n },\n] as const\n","import { multiPublishAbi } from './publisher'\n\n/**\n * Modular executor module events (0x043462…).\n * CreatedAttestation matches publisher; SeedPublished uses typed bytes32 args.\n */\nexport const executorEventsAbi = [\n {\n type: 'event',\n name: 'CreatedAttestation',\n inputs: [\n {\n name: 'result',\n type: 'tuple',\n indexed: false,\n components: [\n { name: 'schemaUid', type: 'bytes32' },\n { name: 'attestationUid', type: 'bytes32' },\n ],\n },\n ],\n },\n {\n type: 'event',\n name: 'SeedPublished',\n inputs: [\n { name: 'seedUid', type: 'bytes32', indexed: false },\n { name: 'versionUid', type: 'bytes32', indexed: false },\n ],\n },\n] as const\n\n/**\n * SeedProtocolExecutor (ERC-7579 executor module) calls and errors.\n * `multiPublish` takes the same `PublishRequestData` as the ManagedAccount extension (selector\n * 0x2a29fadc), so it shares `multiPublishAbi`'s entry.\n */\nexport const executorModuleAbi = [\n multiPublishAbi[0],\n {\n type: 'function',\n name: 'isInitialized',\n stateMutability: 'view',\n inputs: [{ name: 'account', type: 'address' }],\n outputs: [{ name: '', type: 'bool' }],\n },\n {\n type: 'function',\n name: 'getEAS',\n stateMutability: 'view',\n inputs: [{ name: 'account', type: 'address' }],\n outputs: [{ name: '', type: 'address' }],\n },\n {\n type: 'event',\n name: 'ModuleInitialized',\n inputs: [\n { name: 'account', type: 'address', indexed: true },\n { name: 'eas', type: 'address', indexed: true },\n ],\n },\n { type: 'error', name: 'AlreadyInitialized', inputs: [{ name: 'account', type: 'address' }] },\n { type: 'error', name: 'NotInitialized', inputs: [{ name: 'account', type: 'address' }] },\n { type: 'error', name: 'InvalidEASAddress', inputs: [] },\n { type: 'error', name: 'AttestationFailed', inputs: [] },\n { type: 'error', name: 'MultiAttestFailed', inputs: [] },\n] as const\n","/**\n * `SeedExecutorRouterExtension`, routed on ManagedAccounts by the factory\n * (seed-protocol contracts/SeedExecutorRouterExtension.sol). Installs the Seed executor on a\n * Router account.\n */\nexport const seedExecutorRouterAbi = [\n { type: 'function', name: 'installSeedExecutor', stateMutability: 'nonpayable', inputs: [], outputs: [] },\n {\n type: 'function',\n name: 'getSeedExecutor',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n { name: 'executor', type: 'address' },\n { name: 'eas', type: 'address' },\n ],\n },\n {\n type: 'function',\n name: 'isModuleInstalled',\n stateMutability: 'view',\n inputs: [\n { name: 'moduleTypeId', type: 'uint256' },\n { name: 'module', type: 'address' },\n { name: 'additionalContext', type: 'bytes' },\n ],\n outputs: [{ name: '', type: 'bool' }],\n },\n {\n type: 'event',\n name: 'SeedExecutorInstalled',\n inputs: [{ name: 'executor', type: 'address', indexed: true }],\n },\n { type: 'error', name: 'Unauthorized', inputs: [{ name: 'caller', type: 'address' }] },\n { type: 'error', name: 'SeedExecutorAlreadyInstalled', inputs: [] },\n { type: 'error', name: 'SeedExecutorNotInstalled', inputs: [] },\n] as const\n\n/** ERC-7579 module type id for executors. */\nexport const MODULE_TYPE_EXECUTOR = 2n\n","/** EAS Schema Registry on OP Stack predeploy. */\nexport const schemaRegistryAbi = [\n {\n type: 'function',\n name: 'getSchema',\n stateMutability: 'view',\n inputs: [{ name: 'uid', type: 'bytes32' }],\n outputs: [\n {\n name: '',\n type: 'tuple',\n components: [\n { name: 'uid', type: 'bytes32' },\n { name: 'resolver', type: 'address' },\n { name: 'revocable', type: 'bool' },\n { name: 'schema', type: 'string' },\n ],\n },\n ],\n },\n {\n type: 'function',\n name: 'register',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'schema', type: 'string' },\n { name: 'resolver', type: 'address' },\n { name: 'revocable', type: 'bool' },\n ],\n outputs: [{ type: 'bytes32' }],\n },\n] as const\n","export class AttestationVerificationError extends Error {\n constructor(\n message: string,\n public readonly seedLocalId: string,\n public readonly expectedSchemas: string[],\n public readonly foundSchemas: string[],\n public readonly code: 'METADATA_PROPERTIES_MISSING' = 'METADATA_PROPERTIES_MISSING',\n ) {\n super(message)\n this.name = 'AttestationVerificationError'\n }\n}\n\nexport type ManagedAccountPublishErrorCode =\n | 'MANAGED_ACCOUNT_NOT_DEPLOYED'\n | 'MANAGED_ACCOUNT_UNAVAILABLE'\n | 'EXECUTOR_MODULE_NOT_INSTALLED'\n | 'MANAGED_ACCOUNT_SET_EAS_FAILED'\n | 'MODULAR_SIGNER_ACTIVATION_FAILED'\n | 'AUTOMATION_UNSUPPORTED_ACCOUNT'\n | 'AUTOMATION_PREFLIGHT_FAILED'\n | 'PUBLISH_PREFLIGHT_FAILED'\n | 'USEROP_FAILED_NO_REASON'\n | 'USEROP_REVERTED'\n\n/**\n * Best-effort string for RPC / thirdweb / viem failures that are not plain `Error`\n * (so logs and UIs can show the real revert or RPC reason).\n */\nexport function stringifyUnderlyingCause(u: unknown, maxLen = 700): string {\n if (u == null) return ''\n if (u instanceof Error) {\n const nested = u.cause instanceof Error ? ` | cause: ${u.cause.message}` : ''\n return (u.message + nested).slice(0, maxLen)\n }\n if (typeof u === 'object') {\n const o = u as Record<string, unknown>\n const parts: string[] = []\n if (typeof o.message === 'string') parts.push(o.message)\n if (typeof o.shortMessage === 'string') parts.push(o.shortMessage)\n if (typeof o.details === 'string') parts.push(o.details)\n if (typeof o.reason === 'string') parts.push(o.reason)\n if (parts.length) return parts.join(' | ').slice(0, maxLen)\n try {\n return JSON.stringify(u).slice(0, maxLen)\n } catch {\n return String(u).slice(0, maxLen)\n }\n }\n return String(u).slice(0, maxLen)\n}\n\n/**\n * Thrown or returned when the managed publishing account (on the publish chain) is missing,\n * unreachable, missing the executor module for the modular executor path, or EAS\n * pointer setup (`getEas` / `setEas`) fails, or modular session-signer activation fails.\n */\nexport class ManagedAccountPublishError extends Error {\n /** Original error when connection or deployment failed (avoids shadowing `Error.cause`). */\n public readonly underlyingCause?: unknown\n\n constructor(\n message: string,\n public readonly code: ManagedAccountPublishErrorCode,\n public readonly managedAddress?: string,\n underlyingCause?: unknown,\n ) {\n const extra =\n underlyingCause != null && underlyingCause !== ''\n ? ` (${stringifyUnderlyingCause(underlyingCause)})`\n : ''\n super(message + extra)\n this.name = 'ManagedAccountPublishError'\n this.underlyingCause = underlyingCause\n }\n}\n\n/** Thrown by `waitForPublishReceipt` when the transaction was mined but reverted. */\nexport class PublishTransactionRevertedError extends Error {\n constructor(\n public readonly transactionHash: string,\n /** The viem `TransactionReceipt`. */\n public readonly receipt: unknown,\n ) {\n super(`Transaction ${transactionHash} reverted.`)\n this.name = 'PublishTransactionRevertedError'\n }\n}\n\n/**\n * True when `e` is a managed-account publish error. Uses `name` + `code` as a fallback\n * when `instanceof` fails across duplicate bundled class identities.\n */\nexport function isManagedAccountPublishError(e: unknown): e is ManagedAccountPublishError {\n if (e instanceof ManagedAccountPublishError) return true\n if (typeof e !== 'object' || e === null) return false\n const o = e as { name?: string; code?: unknown }\n return o.name === 'ManagedAccountPublishError' && typeof o.code === 'string'\n}\n\nexport type Eip7702ModularAccountPublishErrorCode =\n | 'EIP7702_MODULAR_ACCOUNT_UNAVAILABLE'\n | 'EIP7702_MODULAR_NOT_UPGRADED'\n | 'EIP7702_MODULAR_DEPLOY_FAILED'\n | 'EIP7702_MODULAR_NOT_CONFIRMED'\n\n/**\n * Thrown when the in-app modular (EIP-7702) wallet is missing, not upgraded on-chain, or deploy/bootstrap failed.\n */\nexport class Eip7702ModularAccountPublishError extends Error {\n public readonly underlyingCause?: unknown\n\n constructor(\n message: string,\n public readonly code: Eip7702ModularAccountPublishErrorCode,\n public readonly modularAddress?: string,\n underlyingCause?: unknown,\n ) {\n const extra =\n underlyingCause != null && underlyingCause !== ''\n ? ` (${stringifyUnderlyingCause(underlyingCause)})`\n : ''\n super(message + extra)\n this.name = 'Eip7702ModularAccountPublishError'\n this.underlyingCause = underlyingCause\n }\n}\n\nconst eip7702ModularCodes: Eip7702ModularAccountPublishErrorCode[] = [\n 'EIP7702_MODULAR_ACCOUNT_UNAVAILABLE',\n 'EIP7702_MODULAR_NOT_UPGRADED',\n 'EIP7702_MODULAR_DEPLOY_FAILED',\n 'EIP7702_MODULAR_NOT_CONFIRMED',\n]\n\nexport function isEip7702ModularAccountPublishError(e: unknown): e is Eip7702ModularAccountPublishError {\n if (e instanceof Eip7702ModularAccountPublishError) return true\n if (typeof e !== 'object' || e === null) return false\n const o = e as { name?: string; code?: unknown }\n return (\n o.name === 'Eip7702ModularAccountPublishError' &&\n typeof o.code === 'string' &&\n (eip7702ModularCodes as string[]).includes(o.code)\n )\n}\n\n/**\n * True when the RPC/contract error indicates the account is **not** Thirdweb ModularCore\n * (no Router / `getInstalledModules`), e.g. default EIP-4337 smart accounts.\n * Includes viem \"Cannot decode zero data\" when `eth_call` returns `0x` for a missing Router view.\n */\nexport function isRouterNonModularCoreAccountError(cause: unknown): boolean {\n const msg = stringifyUnderlyingCause(cause)\n if (/Router:\\s*function does not exist/i.test(msg)) return true\n if (/Cannot decode zero data\\s*\\(\\s*[\"']0x[\"']\\s*\\)/i.test(msg)) return true\n return false\n}\n","import {\n createPublicClient,\n http,\n type Address,\n type Hex,\n type PublicClient,\n type TransactionReceipt,\n} from 'viem'\nimport { getPublishConfig } from '../config'\nimport { PublishTransactionRevertedError } from '../errors'\nimport { getPublishRpcUrl, getPublishViemChain } from './chainConfig'\n\ntype PublishPublicClient = PublicClient\n\nlet _client: PublishPublicClient | null = null\nlet _clientKey: string | null = null\n\nfunction publishRpcFetchOptions(): { headers: { 'x-secret-key': string } } | undefined {\n try {\n const secret = getPublishConfig().thirdwebSecretKey\n if (!secret) return undefined\n return { headers: { 'x-secret-key': secret } }\n } catch {\n return undefined\n }\n}\n\nfunction createPublishPublicClient(): PublishPublicClient {\n const chain = getPublishViemChain()\n const rpcUrl = getPublishRpcUrl()\n const fetchOptions = publishRpcFetchOptions()\n return createPublicClient({\n chain,\n transport: http(rpcUrl, fetchOptions ? { fetchOptions } : undefined),\n })\n}\n\n/**\n * Viem public client for reads / receipts on the configured publish chain.\n */\nexport function getPublishPublicClient(): PublishPublicClient {\n const chain = getPublishViemChain()\n const rpcUrl = getPublishRpcUrl()\n let secret = ''\n try {\n secret = getPublishConfig().thirdwebSecretKey ?? ''\n } catch {\n secret = ''\n }\n const key = `${chain.id}:${rpcUrl}:${secret ? '1' : '0'}:${secret}`\n if (!_client || _clientKey !== key) {\n _clientKey = key\n _client = createPublishPublicClient()\n }\n return _client\n}\n\n/** Reset cached client (tests). */\nexport function resetPublishPublicClient(): void {\n _client = null\n _clientKey = null\n}\n\n/**\n * Waits for `transactionHash` to be mined and returns its receipt.\n *\n * @throws PublishTransactionRevertedError when the transaction reverted. A successful receipt\n * only covers the outer transaction: for a sponsored (relayed) send, check the receipt's logs to\n * confirm the inner call did what it should.\n */\nexport async function waitForPublishReceipt(transactionHash: Hex): Promise<TransactionReceipt> {\n const receipt = await getPublishPublicClient().waitForTransactionReceipt({ hash: transactionHash })\n if (receipt.status === 'reverted') throw new PublishTransactionRevertedError(transactionHash, receipt)\n return receipt\n}\n\n/**\n * Calls `read` until `accept` passes on its result, up to `attempts` times, and returns the last\n * result either way. For reads right after a receipt: a load-balanced RPC can serve them from a\n * node that has not seen the receipt's block yet, and pinning `blockNumber` does not help there.\n */\nexport async function readUntil<T>(\n read: () => Promise<T>,\n accept: (value: T) => boolean,\n { attempts = 5, intervalMs = 2_000 }: { attempts?: number; intervalMs?: number } = {},\n): Promise<T> {\n let value = await read()\n for (let i = 1; i < attempts && !accept(value); i++) {\n await new Promise((resolve) => setTimeout(resolve, intervalMs))\n value = await read()\n }\n return value\n}\n\nexport async function isContractDeployed(address: string): Promise<boolean> {\n const code = await getPublishPublicClient().getBytecode({\n address: address as Address,\n })\n return !!code && code !== '0x'\n}\n\nexport async function getBlockTimestampMs(blockNumber: bigint): Promise<number | null> {\n try {\n const block = await getPublishPublicClient().getBlock({ blockNumber })\n if (block?.timestamp != null) return Number(block.timestamp) * 1000\n } catch {\n // ignore\n }\n return null\n}\n\nconst DEFAULT_DEPLOY_POLL_ATTEMPTS = 5\nconst DEFAULT_DEPLOY_POLL_INTERVAL_MS = 6_000\n\n/** Polls chain bytecode until the smart account is deployed or attempts are exhausted. */\nexport async function pollSmartWalletDeployed(\n smartWalletAddress: string,\n attempts: number = DEFAULT_DEPLOY_POLL_ATTEMPTS,\n intervalMs: number = DEFAULT_DEPLOY_POLL_INTERVAL_MS,\n): Promise<boolean> {\n for (let i = 0; i < attempts; i++) {\n if (await isContractDeployed(smartWalletAddress)) {\n return true\n }\n if (i < attempts - 1) {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, intervalMs)\n })\n }\n }\n return false\n}\n","import {\n encodeFunctionData,\n getAbiItem,\n toFunctionSelector,\n zeroAddress,\n type Address,\n type Hex,\n} from 'viem'\nimport {\n multiPublishAbi,\n publisherReadWriteAbi,\n} from '../abi/publisher'\nimport { managedAccountFactoryAbi } from '../abi/factory'\nimport { executorModuleAbi } from '../abi/executor'\nimport { MODULE_TYPE_EXECUTOR, seedExecutorRouterAbi } from '../abi/seedExecutorRouter'\nimport { easAbi } from '../abi/eas'\nimport { schemaRegistryAbi } from '../abi/schemaRegistry'\nimport type { SeedTxRequest } from '../seedSigner'\nimport { getPublishPublicClient } from '../chainClient'\nimport { getPublishConfig, requireManagedAccountFactoryAddress } from '../../config'\n\nexport type MultiPublishRequest = {\n localId: string\n seedUid: `0x${string}`\n seedSchemaUid: `0x${string}`\n versionUid: `0x${string}`\n versionSchemaUid: `0x${string}`\n seedIsRevocable: boolean\n listOfAttestations: Array<{\n schema: `0x${string}`\n data: Array<{\n recipient: `0x${string}`\n expirationTime: bigint\n revocable: boolean\n refUID: `0x${string}`\n data: `0x${string}`\n value: bigint\n }>\n }>\n propertiesToUpdate: Array<{\n publishLocalId: string\n propertySchemaUid: `0x${string}`\n }>\n}\n\n/**\n * Resolves a request's `propertiesToUpdate` to `publishIndex`es: the position in `requests` of the\n * request whose `localId` each one names. Throws rather than guess, since the contract can't tell\n * when an index lands on the wrong request: on a duplicate `localId`, or a `publishLocalId` that is\n * missing, empty or not in `requests`.\n */\nfunction publishIndexResolver(requests: MultiPublishRequest[]) {\n const indexByLocalId = new Map<string, bigint>()\n requests.forEach((r, i) => {\n if (!r.localId) return\n if (indexByLocalId.has(r.localId)) {\n throw new Error(`multiPublish: duplicate localId \"${r.localId}\" in the batch`)\n }\n indexByLocalId.set(r.localId, BigInt(i))\n })\n return (r: MultiPublishRequest) =>\n (r.propertiesToUpdate ?? []).map((pu) => {\n if (!pu.publishLocalId) {\n throw new Error(`multiPublish: request \"${r.localId}\" has a cross-reference with no publishLocalId`)\n }\n const publishIndex = indexByLocalId.get(pu.publishLocalId)\n if (publishIndex === undefined) {\n throw new Error(\n `multiPublish: request \"${r.localId}\" cross-references localId \"${pu.publishLocalId}\", which isn't in the batch`,\n )\n }\n return { publishIndex, propertySchemaUid: pu.propertySchemaUid }\n })\n}\n\n/**\n * Encode `multiPublish` for the account's SeedProtocolExtension, mapping each `publishLocalId` to\n * its index in `requests`.\n */\nexport function encodeMultiPublish(\n to: Address,\n requests: MultiPublishRequest[],\n gas?: bigint,\n): SeedTxRequest {\n const publishIndexes = publishIndexResolver(requests)\n return {\n to,\n data: encodeFunctionData({\n abi: multiPublishAbi,\n functionName: 'multiPublish',\n args: [\n requests.map((r) => ({\n localId: r.localId,\n seedUid: r.seedUid,\n seedSchemaUid: r.seedSchemaUid,\n versionUid: r.versionUid,\n versionSchemaUid: r.versionSchemaUid,\n seedIsRevocable: r.seedIsRevocable,\n listOfAttestations: r.listOfAttestations,\n propertiesToUpdate: publishIndexes(r),\n })),\n ],\n }),\n gas,\n }\n}\n\n/**\n * Encode `multiPublish` for the SeedProtocolExecutor module, which takes the same request struct\n * as the extension: only the target differs from {@link encodeMultiPublish}.\n */\nexport function encodeExecutorMultiPublish(\n to: Address,\n requests: MultiPublishRequest[],\n gas?: bigint,\n): SeedTxRequest {\n return encodeMultiPublish(to, requests, gas)\n}\n\nexport async function readExecutorModuleIsInitialized(\n moduleAddress: Address,\n account: Address,\n): Promise<boolean> {\n return getPublishPublicClient().readContract({\n address: moduleAddress,\n abi: executorModuleAbi,\n functionName: 'isInitialized',\n args: [account],\n })\n}\n\nexport async function readExecutorModuleEas(\n moduleAddress: Address,\n account: Address,\n): Promise<Address> {\n return getPublishPublicClient().readContract({\n address: moduleAddress,\n abi: executorModuleAbi,\n functionName: 'getEAS',\n args: [account],\n })\n}\n\n/**\n * The executor and EAS pinned by the account's `SeedExecutorRouterExtension`, or `null` when the\n * account has no such extension (pre-rollout Router accounts, ModularCore accounts).\n */\nexport async function readSeedExecutorRouter(\n account: Address,\n): Promise<{ executor: Address; eas: Address } | null> {\n try {\n const [executor, eas] = await getPublishPublicClient().readContract({\n address: account,\n abi: seedExecutorRouterAbi,\n functionName: 'getSeedExecutor',\n })\n return { executor, eas }\n } catch {\n return null\n }\n}\n\n/**\n * The executor and EAS that accounts from `factory` get from their `SeedExecutorRouterExtension`,\n * or `null` when the factory routes no such extension. For checking `modularAccountModuleContract`\n * at startup instead of at the first publish. `factory` defaults to the configured factory.\n */\nexport async function readFactorySeedExecutor(\n factory: Address = requireManagedAccountFactoryAddress() as Address,\n): Promise<{ executor: Address; eas: Address } | null> {\n const client = getPublishPublicClient()\n const extension = await client.readContract({\n address: factory,\n abi: managedAccountFactoryAbi,\n functionName: 'getImplementationForFunction',\n args: [toFunctionSelector(getAbiItem({ abi: seedExecutorRouterAbi, name: 'getSeedExecutor' }))],\n })\n if (extension === zeroAddress) return null\n // The extension keeps both as immutables, so the implementation reports what accounts see.\n const [executor, eas] = await client.readContract({\n address: extension,\n abi: seedExecutorRouterAbi,\n functionName: 'getSeedExecutor',\n })\n return { executor, eas }\n}\n\n/** Whether the router extension reports `executor` installed on `account`. */\nexport async function readSeedExecutorInstalled(account: Address, executor: Address): Promise<boolean> {\n return getPublishPublicClient().readContract({\n address: account,\n abi: seedExecutorRouterAbi,\n functionName: 'isModuleInstalled',\n args: [MODULE_TYPE_EXECUTOR, executor, '0x'],\n })\n}\n\n/**\n * `installSeedExecutor()` on `account`. Admin-only: send it from the account's admin EOA\n * directly; a self-call via `execute` (what smart-account wallets send) is rejected.\n */\nexport function encodeInstallSeedExecutor(account: Address): SeedTxRequest {\n return {\n to: account,\n data: encodeFunctionData({ abi: seedExecutorRouterAbi, functionName: 'installSeedExecutor' }),\n }\n}\n\nexport function encodeSetEas(to: Address, eas: Address): SeedTxRequest {\n return {\n to,\n data: encodeFunctionData({\n abi: publisherReadWriteAbi,\n functionName: 'setEas',\n args: [eas],\n }),\n }\n}\n\nexport async function readGetEas(managedAddress: Address): Promise<Address> {\n return getPublishPublicClient().readContract({\n address: managedAddress,\n abi: publisherReadWriteAbi,\n functionName: 'getEas',\n })\n}\n\nexport async function readIsActiveSigner(\n managedAddress: Address,\n signer: Address,\n): Promise<boolean> {\n return getPublishPublicClient().readContract({\n address: managedAddress,\n abi: publisherReadWriteAbi,\n functionName: 'isActiveSigner',\n args: [signer],\n })\n}\n\nexport async function readIsAdmin(managedAddress: Address, signer: Address): Promise<boolean> {\n return getPublishPublicClient().readContract({\n address: managedAddress,\n abi: publisherReadWriteAbi,\n functionName: 'isAdmin',\n args: [signer],\n })\n}\n\nexport async function readFactoryGetAddress(\n adminSigner: Address,\n data: Hex = '0x',\n): Promise<Address> {\n return getPublishPublicClient().readContract({\n address: requireManagedAccountFactoryAddress() as Address,\n abi: managedAccountFactoryAbi,\n functionName: 'getAddress',\n args: [adminSigner, data],\n })\n}\n\nexport function encodeCreateAccount(\n admin: Address,\n data: Hex = '0x',\n): SeedTxRequest {\n return {\n to: requireManagedAccountFactoryAddress() as Address,\n data: encodeFunctionData({\n abi: managedAccountFactoryAbi,\n functionName: 'createAccount',\n args: [admin, data],\n }),\n }\n}\n\nexport type EasAttestParams = {\n schema: `0x${string}`\n data: {\n recipient?: `0x${string}`\n expirationTime?: bigint\n revocable?: boolean\n refUID: `0x${string}`\n data: `0x${string}`\n value?: bigint\n }\n}\n\nconst ZERO_ADDRESS = '0x0000000000000000000000000000000000000000' as const\n\nexport function encodeEasAttest(params: EasAttestParams): SeedTxRequest {\n const { easContractAddress } = getPublishConfig()\n return {\n to: easContractAddress as Address,\n data: encodeFunctionData({\n abi: easAbi,\n functionName: 'attest',\n args: [\n {\n schema: params.schema,\n data: {\n recipient: (params.data.recipient ?? ZERO_ADDRESS) as Address,\n expirationTime: params.data.expirationTime ?? 0n,\n revocable: params.data.revocable ?? true,\n refUID: params.data.refUID,\n data: params.data.data,\n value: params.data.value ?? 0n,\n },\n },\n ],\n }),\n }\n}\n\nexport type MultiAttestationRequest = {\n schema: `0x${string}`\n data: Array<{\n recipient: `0x${string}`\n expirationTime: bigint\n revocable: boolean\n refUID: `0x${string}`\n data: `0x${string}`\n value: bigint\n }>\n}\n\nexport function encodeEasMultiAttest(requests: MultiAttestationRequest[]): SeedTxRequest {\n const { easContractAddress } = getPublishConfig()\n return {\n to: easContractAddress as Address,\n data: encodeFunctionData({\n abi: easAbi,\n functionName: 'multiAttest',\n args: [requests],\n }),\n }\n}\n\nexport type MultiRevocationRequest = {\n schema: `0x${string}`\n data: Array<{\n uid: `0x${string}`\n value?: bigint\n }>\n}\n\nexport function encodeEasMultiRevoke(requests: MultiRevocationRequest[]): SeedTxRequest {\n const { easContractAddress } = getPublishConfig()\n return {\n to: easContractAddress as Address,\n data: encodeFunctionData({\n abi: easAbi,\n functionName: 'multiRevoke',\n args: [\n requests.map((r) => ({\n schema: r.schema,\n data: r.data.map((d) => ({\n uid: d.uid,\n value: d.value ?? 0n,\n })),\n })),\n ],\n }),\n }\n}\n\nexport type SchemaRecord = {\n uid: string\n resolver: string\n revocable: boolean\n schema: string\n}\n\nconst ZERO_BYTES32 = '0x' + '0'.repeat(64)\n\nexport async function readSchemaRecord(uid: string): Promise<SchemaRecord | null> {\n const result = await getPublishPublicClient().readContract({\n address: getPublishConfig().schemaRegistryAddress as Address,\n abi: schemaRegistryAbi,\n functionName: 'getSchema',\n args: [uid as Hex],\n })\n if (!result || result.uid === ZERO_BYTES32) return null\n return {\n uid: result.uid,\n resolver: result.resolver,\n revocable: result.revocable,\n schema: result.schema,\n }\n}\n\nexport function encodeRegisterSchema(params: {\n schema: string\n resolverAddress: string\n revocable: boolean\n}): SeedTxRequest {\n return {\n to: getPublishConfig().schemaRegistryAddress as Address,\n data: encodeFunctionData({\n abi: schemaRegistryAbi,\n functionName: 'register',\n args: [params.schema, params.resolverAddress as Address, params.revocable],\n }),\n }\n}\n","import { encodeAbiParameters, parseEventLogs, type Log } from 'viem'\nimport { easAbi } from './abi/eas'\nimport {\n encodeEasAttest,\n encodeEasMultiAttest,\n encodeEasMultiRevoke,\n type EasAttestParams,\n type MultiAttestationRequest,\n type MultiRevocationRequest,\n} from './contracts'\nimport type { SeedTxRequest } from './seedSigner'\n\nexport type { EasAttestParams, MultiAttestationRequest, MultiRevocationRequest }\n\nconst ZERO_ADDRESS = '0x0000000000000000000000000000000000000000' as const\nconst ZERO_BYTES32 = ('0x' + '0'.repeat(64)) as `0x${string}`\n\n/**\n * Prepares a single EAS attest call (encoded SeedTxRequest).\n */\nexport function prepareEasAttest(params: EasAttestParams): SeedTxRequest {\n return encodeEasAttest(params)\n}\n\n/**\n * Prepares an EAS multiAttest call for batch attestations.\n */\nexport function prepareEasMultiAttest(requests: MultiAttestationRequest[]): SeedTxRequest {\n return encodeEasMultiAttest(requests)\n}\n\n/**\n * Encodes a bytes32 value for Seed/Version attestation data.\n * Equivalent to Solidity abi.encode(bytes32).\n */\nexport function encodeBytes32(value: `0x${string}`): `0x${string}` {\n return encodeAbiParameters([{ type: 'bytes32' }], [value]) as `0x${string}`\n}\n\n/**\n * Extracts the attestation UID from an EAS attest transaction receipt.\n */\nexport function getAttestationUidFromReceipt(\n receipt: { logs?: Array<{ address?: string; data?: string; topics?: unknown[] }> },\n easContractAddress: string,\n): string | undefined {\n const all = getAttestedUidsFromReceipt(receipt, easContractAddress)\n return all[0]?.uid\n}\n\nexport type EasAttestedPair = { schemaUid: string; uid: string }\n\n/**\n * All `Attested` events from the EAS contract in this receipt, in log order.\n */\nexport function getAttestedUidsFromReceipt(\n receipt: { logs?: Array<{ address?: string; data?: string; topics?: unknown[] }> },\n easContractAddress: string,\n): EasAttestedPair[] {\n if (!receipt.logs?.length) return []\n const want = easContractAddress.toLowerCase()\n const logs = receipt.logs.filter((l) => l.address && l.address.toLowerCase() === want)\n if (!logs.length) return []\n try {\n const parsed = parseEventLogs({\n abi: easAbi,\n eventName: 'Attested',\n logs: logs as Log[],\n strict: false,\n })\n const out: EasAttestedPair[] = []\n for (const ev of parsed) {\n const uid = ev.args?.uid as string | undefined\n const schemaUid = ev.args?.schemaUID as string | undefined\n if (!uid || uid === ZERO_BYTES32) continue\n if (!schemaUid) continue\n out.push({ schemaUid, uid })\n }\n return out\n } catch {\n return []\n }\n}\n\n/**\n * Prepares an EAS multiRevoke call for batch revocation. Targets EAS directly; only the attester\n * (an EOA, or a ManagedAccount executing as itself) can revoke. The Seed executor module has no\n * revoke path.\n */\nexport function prepareEasMultiRevoke(requests: MultiRevocationRequest[]): SeedTxRequest {\n return encodeEasMultiRevoke(requests)\n}\n\nexport { ZERO_ADDRESS, ZERO_BYTES32 }\n","/**\n * Custom errors a publish call can revert with on the ManagedAccount stack: SeedPublishLib,\n * the Seed protocol extensions, SeedAccountAuth and the Seed executor router extension.\n * The executor module's own errors are in `executorModuleAbi`, EAS's in `easAbi`.\n */\nexport const seedErrorsAbi = [\n // SeedPublishLib\n {\n type: 'error',\n name: 'PublishIndexOutOfBounds',\n inputs: [\n { name: 'targetIndex', type: 'uint256' },\n { name: 'length', type: 'uint256' },\n ],\n },\n { type: 'error', name: 'UnknownPublishLocalId', inputs: [{ name: 'publishLocalId', type: 'string' }] },\n {\n type: 'error',\n name: 'PublishTargetAlreadyAttested',\n inputs: [\n { name: 'requestIndex', type: 'uint256' },\n { name: 'targetIndex', type: 'uint256' },\n ],\n },\n {\n type: 'error',\n name: 'EmptyAttestationData',\n inputs: [\n { name: 'targetIndex', type: 'uint256' },\n { name: 'propertySchemaUid', type: 'bytes32' },\n ],\n },\n {\n type: 'error',\n name: 'PropertyToUpdateNotFound',\n inputs: [\n { name: 'requestIndex', type: 'uint256' },\n { name: 'targetIndex', type: 'uint256' },\n { name: 'propertySchemaUid', type: 'bytes32' },\n ],\n },\n {\n type: 'error',\n name: 'AmbiguousPropertyToUpdate',\n inputs: [\n { name: 'targetIndex', type: 'uint256' },\n { name: 'propertySchemaUid', type: 'bytes32' },\n ],\n },\n // SeedProtocolExtensionBase (the executor module's AttestationFailed() has no argument)\n { type: 'error', name: 'InvalidEAS', inputs: [{ name: 'eas', type: 'address' }] },\n { type: 'error', name: 'AttestationFailed', inputs: [{ name: 'schemaUid', type: 'bytes32' }] },\n // SeedAccountAuth\n { type: 'error', name: 'Unauthorized', inputs: [{ name: 'caller', type: 'address' }] },\n // SeedExecutorRouterExtension\n { type: 'error', name: 'InvalidAddress', inputs: [{ name: 'addr', type: 'address' }] },\n { type: 'error', name: 'SeedExecutorAlreadyInstalled', inputs: [] },\n { type: 'error', name: 'SeedExecutorNotInstalled', inputs: [] },\n { type: 'error', name: 'NotSeedExecutor', inputs: [{ name: 'caller', type: 'address' }] },\n { type: 'error', name: 'UnsupportedExecutionMode', inputs: [{ name: 'mode', type: 'bytes32' }] },\n { type: 'error', name: 'TargetNotAllowed', inputs: [{ name: 'target', type: 'address' }] },\n { type: 'error', name: 'SelectorNotAllowed', inputs: [{ name: 'selector', type: 'bytes4' }] },\n {\n type: 'error',\n name: 'ValueMismatch',\n inputs: [\n { name: 'encodedValue', type: 'uint256' },\n { name: 'sentValue', type: 'uint256' },\n ],\n },\n] as const\n","import { BaseError, decodeErrorResult, toFunctionSelector, type Abi, type Hex } from 'viem'\nimport { easAbi } from './abi/eas'\nimport { executorModuleAbi } from './abi/executor'\nimport { seedErrorsAbi } from './abi/seedErrors'\nimport { ManagedAccountPublishError } from '../errors'\n\n/** Every error a publish call can revert with. `Error(string)` and `Panic` decode without it. */\nconst publishErrorsAbi = [...seedErrorsAbi, ...executorModuleAbi, ...easAbi] as Abi\n\nexport function findRevertData(err: unknown): Hex | undefined {\n if (!(err instanceof BaseError)) return undefined\n const withData = err.walk((e) => {\n const data = (e as { data?: unknown }).data\n return typeof data === 'string' && data.startsWith('0x') && data.length > 2\n }) as { data?: Hex } | null\n return withData?.data\n}\n\nexport function isRevert(err: unknown): boolean {\n if (findRevertData(err)) return true\n const msg = err instanceof BaseError ? `${err.shortMessage} ${err.details}` : String(err)\n return /revert/i.test(msg)\n}\n\nconst NO_DATA_REASON =\n 'reverted with no data. The target likely has no matching function or the account cannot run executor calls'\n\n/** \"reverted with UnknownPublishLocalId(abc)\", decoded with the Seed, executor and EAS errors. */\nexport function describeRevert(data: Hex | undefined, noDataReason = NO_DATA_REASON): string {\n if (!data || data === '0x') return noDataReason\n try {\n const decoded = decodeErrorResult({ abi: publishErrorsAbi, data })\n const args = decoded.args?.length ? `(${decoded.args.map(String).join(', ')})` : ''\n return `reverted with ${decoded.errorName}${args}`\n } catch {\n return `reverted with data ${data}`\n }\n}\n\n/**\n * Message for a UserOp that failed in transaction `txHash`. With no revert data it was usually\n * out of gas: the bundler's callGasLimit estimate was too low. Sponsored managed-account UserOps\n * get headroom on that estimate (see `seedPaymaster`); unsponsored ones still use it as is,\n * because thirdweb replaces the transaction's own gas limit with it.\n */\nexport function describeFailedUserOp(txHash: string, revertData?: Hex): string {\n if (revertData && revertData !== '0x') {\n return `The publish UserOp in transaction ${txHash} ${describeRevert(revertData)}.`\n }\n return (\n `The publish UserOp in transaction ${txHash} failed with no revert reason. That usually means it ran out of gas ` +\n `(the bundler's gas estimate was too low), not that the publish data is wrong. ` +\n `To confirm, run \\`npx hardhat seed:explain-userop --network <network> --tx ${txHash}\\` in seed-protocol.`\n )\n}\n\n/**\n * Error for a UserOp that failed in transaction `txHash`: `USEROP_REVERTED` with revert data,\n * `USEROP_FAILED_NO_REASON` (usually out of gas) without.\n */\nexport function userOpFailureError(params: {\n txHash: string\n revertData?: Hex\n sender?: string\n cause?: unknown\n}): ManagedAccountPublishError {\n const { txHash, revertData, sender, cause } = params\n const reverted = !!revertData && revertData !== '0x'\n return new ManagedAccountPublishError(\n describeFailedUserOp(txHash, revertData),\n reverted ? 'USEROP_REVERTED' : 'USEROP_FAILED_NO_REASON',\n sender,\n cause,\n )\n}\n\nfunction errorChain(err: unknown): unknown[] {\n const chain: unknown[] = []\n for (let cur = err; cur && chain.length < 6; cur = (cur as { cause?: unknown }).cause) chain.push(cur)\n return chain\n}\n\nlet selectorNames: Map<string, string> | undefined\nfunction errorNameForSelector(selector: string): string | undefined {\n selectorNames ??= new Map(\n publishErrorsAbi\n .filter((item) => item.type === 'error')\n .map((item) => [\n toFunctionSelector(`${item.name}(${item.inputs.map((i) => i.type).join(',')})`),\n item.name,\n ]),\n )\n return selectorNames.get(selector.toLowerCase())\n}\n\n/**\n * Turns the two unhelpful errors a failed thirdweb UserOp produces into ManagedAccountPublishErrors,\n * keeping the original as `underlyingCause`; returns anything else unchanged.\n * - \"UserOp failed at txHash: 0x…\": no revert reason was logged, usually out of gas.\n * `USEROP_FAILED_NO_REASON`.\n * - viem's AbiErrorSignatureNotFoundError: thirdweb decodes the logged revert reason without\n * an ABI, so every custom error fails to decode. Names the error from its selector.\n * `USEROP_REVERTED`.\n */\nexport function explainUserOpError(err: unknown, sender?: string): unknown {\n for (const e of errorChain(err)) {\n const message = String((e as { message?: unknown }).message ?? '')\n const failed = message.match(/UserOp failed at txHash: (0x[0-9a-f]{64})/i)\n if (failed) return userOpFailureError({ txHash: failed[1]!, sender, cause: err })\n\n const signature = (e as { name?: unknown; signature?: unknown }).signature\n if ((e as { name?: unknown }).name === 'AbiErrorSignatureNotFoundError' && typeof signature === 'string') {\n const name = errorNameForSelector(signature)\n if (name) {\n return new ManagedAccountPublishError(\n `The publish transaction reverted with ${name} (its arguments were not decoded).`,\n 'USEROP_REVERTED',\n sender,\n err,\n )\n }\n }\n }\n return err\n}\n","import { client as seedClient } from '@seedprotocol/sdk'\nimport type { PublishWallet, SeedSigner, SeedTxSender } from './seedSigner'\n\nexport type PublishWalletSession = PublishWallet & {\n /** Addresses to treat as owned in the Seed SDK (EOA + smart account, etc.). */\n ownedAddresses?: string[]\n /** Preferred publisher address for new seeds (defaults to signer.address). */\n publisherAddress?: string\n /**\n * Admin (EOA) of the smart account this session publishes from, when there is one. Lets publish\n * tell an undeployed smart account from an EOA, which both have no bytecode.\n */\n adminAddress?: string\n}\n\nlet session: PublishWalletSession | null = null\n\nfunction waitUntilSeedInitialized(): Promise<void> {\n if (seedClient.isInitialized()) return Promise.resolve()\n return new Promise((resolve) => {\n seedClient.onReady(() => resolve())\n })\n}\n\n/**\n * Register the active publish wallet (EIP-1193, ethers, Thirdweb adapter, etc.).\n * Syncs owned addresses into the Seed SDK when possible.\n */\nexport async function setPublishWallet(\n next: PublishWalletSession | null,\n): Promise<void> {\n session = next\n if (!next) return\n await waitUntilSeedInitialized()\n const owned = new Set<string>()\n for (const a of next.ownedAddresses ?? []) {\n if (a) owned.add(a.toLowerCase())\n }\n owned.add(next.signer.address.toLowerCase())\n owned.add(next.txSender.address.toLowerCase())\n if (next.publisherAddress) owned.add(next.publisherAddress.toLowerCase())\n try {\n // Watched addresses aren't the wallet's: keep them (setAddresses replaces both lists).\n const { watched } = await seedClient.getAddresses()\n await seedClient.setAddresses({ owned: [...owned], watched })\n const claimAs = next.publisherAddress ?? next.signer.address\n if (claimAs) {\n await seedClient.claimUnpublishedDrafts(claimAs)\n }\n } catch (err) {\n console.warn('[publishWalletRegistry] Failed to set seed client addresses:', err)\n }\n}\n\nexport function getPublishWallet(): PublishWalletSession | null {\n return session\n}\n\n/**\n * Forget the publish wallet and stop treating its addresses as owned in the Seed SDK (watched\n * addresses are kept). New drafts are then signed-out drafts, editable until a wallet connects\n * and claims them; drafts stamped with the old wallet are read-only until it reconnects.\n */\nexport async function clearPublishWallet(): Promise<void> {\n session = null\n if (!seedClient.isInitialized()) return\n try {\n const { watched } = await seedClient.getAddresses()\n // A wallet connected while we read: its addresses win.\n if (session) return\n await seedClient.setAddresses({ owned: [], watched })\n } catch (err) {\n console.warn('[publishWalletRegistry] Failed to clear seed client owned addresses:', err)\n }\n}\n\n/** Convenience for callers that only need signing. */\nexport function getRegisteredSigner(): SeedSigner | null {\n return session?.signer ?? null\n}\n\n/** Convenience for callers that only need sending. */\nexport function getRegisteredTxSender(): SeedTxSender | null {\n return session?.txSender ?? null\n}\n","/** True for \"the nonce was already used\" rejections, which mean the tx was not accepted. */\nexport function isNonceTooLowError(err: unknown): boolean {\n const parts: string[] = []\n let cur: unknown = err\n for (let i = 0; cur && i < 5; i++) {\n const e = cur as { message?: unknown; shortMessage?: unknown; details?: unknown; code?: unknown; cause?: unknown }\n parts.push(String(e.message ?? ''), String(e.shortMessage ?? ''), String(e.details ?? ''), String(e.code ?? ''))\n cur = e.cause\n }\n return /nonce too low|nonce has already been used|NONCE_EXPIRED|nonce.*already.*(used|known)|lower than the current nonce/i.test(parts.join(' '))\n}\n\n/**\n * Retries `send` when the node rejects it for a stale nonce. A local fork's pending-nonce lookup\n * can trail the chain by a block, so back-to-back sends from one EOA may pick a used nonce.\n * Such a rejection means nothing was sent, so retrying cannot double-send.\n */\nexport async function retryNonceTooLow<T>(\n send: () => Promise<T>,\n { attempts = 3, delayMs = 1000 }: { attempts?: number; delayMs?: number } = {},\n): Promise<T> {\n for (let attempt = 1; ; attempt++) {\n try {\n return await send()\n } catch (err) {\n if (attempt >= attempts || !isNonceTooLowError(err)) throw err\n await new Promise((resolve) => setTimeout(resolve, delayMs))\n }\n }\n}\n","import type { Address, Hex, SignableMessage } from 'viem'\nimport { retryNonceTooLow } from './retryNonceTooLow'\nimport { ethers } from 'ethers'\n\n/** Encoded calldata ready for submission (viem path). */\nexport type SeedTxRequest = {\n to: Address\n data: Hex\n value?: bigint\n gas?: bigint\n}\n\n/**\n * Vendor-neutral key custody for Arweave DataItems and message signing.\n * Does not submit on-chain transactions.\n */\nexport interface SeedSigner {\n readonly address: Address\n\n /**\n * personal_sign. For Arweave/ANS-104 use `message: { raw: Hex | Uint8Array }`.\n * Plain string is UTF-8 prefixed hash.\n */\n signMessage(args: { message: SignableMessage }): Promise<Hex>\n}\n\n/**\n * Vendor-neutral transaction submission (EOA, AA, sponsored, etc.).\n */\nexport interface SeedTxSender {\n readonly address: Address\n\n /** Submit already-encoded calldata. */\n sendTransaction(tx: SeedTxRequest): Promise<{ transactionHash: Hex }>\n\n waitForReceipt?(transactionHash: Hex): Promise<{ status: 'success' | 'reverted' }>\n}\n\n/** Bundle used by publish / revoke flows that need both signing and sending. */\nexport type PublishWallet = {\n signer: SeedSigner\n txSender: SeedTxSender\n}\n\nconst SEED_SIGNER_BRAND = Symbol.for('seedprotocol.SeedSigner')\nconst SEED_TX_SENDER_BRAND = Symbol.for('seedprotocol.SeedTxSender')\n\ntype BrandedSeedSigner = SeedSigner & { readonly [SEED_SIGNER_BRAND]: true }\ntype BrandedSeedTxSender = SeedTxSender & { readonly [SEED_TX_SENDER_BRAND]: true }\n\nfunction brandSigner(signer: SeedSigner): SeedSigner {\n return Object.assign(signer, { [SEED_SIGNER_BRAND]: true as const }) as BrandedSeedSigner\n}\n\nfunction brandTxSender(sender: SeedTxSender): SeedTxSender {\n return Object.assign(sender, { [SEED_TX_SENDER_BRAND]: true as const }) as BrandedSeedTxSender\n}\n\nexport function isSeedSigner(value: unknown): value is SeedSigner {\n return !!value && typeof value === 'object' && SEED_SIGNER_BRAND in value\n}\n\nexport function isSeedTxSender(value: unknown): value is SeedTxSender {\n return !!value && typeof value === 'object' && SEED_TX_SENDER_BRAND in value\n}\n\nexport function isPublishWallet(value: unknown): value is PublishWallet {\n return (\n !!value &&\n typeof value === 'object' &&\n 'signer' in value &&\n 'txSender' in value &&\n isSeedSigner((value as PublishWallet).signer) &&\n isSeedTxSender((value as PublishWallet).txSender)\n )\n}\n\n/**\n * Wrap an ethers Wallet for tests / EOA scripts (signs + sends; no AA sponsorship).\n * Suitable for ANS-104 DataItem signing. Not a ManagedAccount session-key UserOp sender —\n * for automation on-chain publish, use a PublishWallet whose txSender submits UserOps\n * through the ManagedAccount (see docs/PUBLISH_AUTOMATION.md).\n */\nexport function fromEthersWallet(wallet: ethers.Wallet): PublishWallet {\n const address = wallet.address as Address\n const signer = brandSigner({\n address,\n signMessage: async ({ message }) => {\n if (typeof message === 'string') {\n return (await wallet.signMessage(message)) as Hex\n }\n const raw = message.raw\n const bytes =\n typeof raw === 'string'\n ? ethers.getBytes(raw)\n : raw instanceof Uint8Array\n ? raw\n : new Uint8Array(raw)\n return (await wallet.signMessage(bytes)) as Hex\n },\n })\n const txSender = brandTxSender({\n address,\n sendTransaction: async (tx) => {\n const result = await retryNonceTooLow(() =>\n wallet.sendTransaction({\n to: tx.to,\n data: tx.data,\n value: tx.value,\n gasLimit: tx.gas,\n }),\n )\n return { transactionHash: result.hash as Hex }\n },\n })\n return { signer, txSender }\n}\n\n/**\n * Coerce a branded SeedSigner, PublishWallet.signer, or pass-through unknown branded value.\n * Does not wrap Thirdweb Accounts — use `fromThirdwebAccount` from `@seedprotocol/publish/thirdweb`.\n */\nexport function asSeedSigner(value: SeedSigner | PublishWallet): SeedSigner {\n if (isPublishWallet(value)) return value.signer\n if (isSeedSigner(value)) return value\n throw new Error(\n '@seedprotocol/publish: expected a SeedSigner or PublishWallet. Use fromEthersWallet, fromEip1193Provider, or fromThirdwebAccount.',\n )\n}\n\n/** Resolve tx sender from a PublishWallet or branded SeedTxSender. */\nexport function asSeedTxSender(value: SeedTxSender | PublishWallet): SeedTxSender {\n if (isPublishWallet(value)) return value.txSender\n if (isSeedTxSender(value)) return value\n throw new Error(\n '@seedprotocol/publish: expected a SeedTxSender or PublishWallet. Use fromEthersWallet, fromEip1193Provider, or fromThirdwebAccount.',\n )\n}\n\n/** Prefer PublishWallet; if only a branded SeedSigner is passed, throw (tx path needs a sender). */\nexport function asPublishWallet(value: PublishWallet | SeedSigner): PublishWallet {\n if (isPublishWallet(value)) return value\n throw new Error(\n '@seedprotocol/publish: expected a PublishWallet (signer + txSender). Use fromEthersWallet, fromEip1193Provider, or fromThirdwebAccount.',\n )\n}\n\n/** @internal used by optional Thirdweb adapter */\nexport { brandSigner, brandTxSender }\n","import { defineChain, optimismSepolia, type Chain as ThirdwebChain } from 'thirdweb/chains'\nimport type { Chain as ViemChain } from 'viem'\nimport { getConfigRef } from '../config'\nimport { DEFAULT_PUBLISH_CHAIN } from './defaultChain'\n\nlet cached: { key: string; chain: ThirdwebChain } | null = null\n\n/**\n * Thirdweb chain matching the publish chain (`PublishConfig.chain`) and RPC (`PublishConfig.rpcUrl`).\n * All Thirdweb wallet connect / deploy / contract calls must use this instead of a fixed chain.\n *\n * With `rpcUrl` set, Thirdweb uses it too, so Seed's own reads and Thirdweb's calls always reach\n * the same node (e.g. a local fork). Without it, Thirdweb uses its RPC edge, as viem does.\n *\n * Pass `source` when the config ref may not be set yet (e.g. first React render).\n */\nexport function getPublishThirdwebChain(source?: { chain?: ViemChain; rpcUrl?: string }): ThirdwebChain {\n const ref = source ?? getConfigRef() ?? {}\n const viemChain = ref.chain ?? DEFAULT_PUBLISH_CHAIN\n const rpcUrl = ref.rpcUrl?.trim() || undefined\n const key = `${viemChain.id}|${rpcUrl ?? ''}`\n if (cached?.key === key) return cached.chain\n\n let chain: ThirdwebChain\n if (viemChain.id === optimismSepolia.id && !rpcUrl) {\n chain = optimismSepolia\n } else {\n // Without `rpc`, defineChain fills in Thirdweb's RPC edge for the chain id.\n chain = defineChain({\n id: viemChain.id,\n name: viemChain.name,\n nativeCurrency: viemChain.nativeCurrency,\n testnet: viemChain.testnet ? true : undefined,\n blockExplorers: viemChain.blockExplorers\n ? Object.values(viemChain.blockExplorers).map(({ name, url, apiUrl }) => ({ name, url, apiUrl }))\n : undefined,\n ...(rpcUrl ? { rpc: rpcUrl } : {}),\n })\n }\n cached = { key, chain }\n return chain\n}\n\nconst LOCAL_CHAIN_IDS = new Set([31337, 1337])\n\n/**\n * True for a dev chain (Anvil / Hardhat ids) or any chain reached through a loopback or `.localhost`\n * RPC, such as a fork. Thirdweb's hosted bundler, paymaster and EIP-7702 relayer cannot reach these.\n */\nexport function isLocalThirdwebChain(chain: Pick<ThirdwebChain, 'id' | 'rpc'>): boolean {\n if (LOCAL_CHAIN_IDS.has(chain.id)) return true\n try {\n const host = new URL(chain.rpc).hostname.replace(/^\\[|\\]$/g, '')\n return host === 'localhost' || host === '127.0.0.1' || host === '::1' || host.endsWith('.localhost')\n } catch {\n return false\n }\n}\n","/**\n * Console logging for UserOp gas limits, to tell whether a gas problem starts in our code or in\n * thirdweb. Filter the console on `[seed:gas]`. Bigints print as decimal strings.\n */\nexport function logGas(stage: string, data: Record<string, unknown>): void {\n const printable = Object.fromEntries(\n Object.entries(data).map(([k, v]) => [k, typeof v === 'bigint' ? v.toString() : v]),\n )\n console.info(`[seed:gas] ${stage}`, printable)\n}\n\n/** The gas fields of a UserOp (or paymaster result), with `paymasterAndData` shortened. */\nexport function gasFields(op: Record<string, any>): Record<string, unknown> {\n const pad = op.paymasterAndData as string | undefined\n return {\n callGasLimit: op.callGasLimit,\n verificationGasLimit: op.verificationGasLimit,\n preVerificationGas: op.preVerificationGas,\n ...(pad !== undefined ? { paymasterAndData: pad.length > 20 ? `${pad.slice(0, 20)}… (${(pad.length - 2) / 2} bytes)` : pad } : {}),\n }\n}\n","import { prepareTransaction, sendTransaction, type ThirdwebClient } from 'thirdweb'\nimport type { Account } from 'thirdweb/wallets'\nimport type { Address, Hex } from 'viem'\nimport {\n brandSigner,\n brandTxSender,\n isPublishWallet,\n isSeedSigner,\n type PublishWallet,\n type SeedSigner,\n} from '../seedSigner'\nimport { getPublishThirdwebChain } from '../thirdwebChain'\nimport { retryNonceTooLow } from '../retryNonceTooLow'\nimport { logGas } from '../gasLog'\n\nexport type FromThirdwebAccountOptions = {\n /**\n * Thirdweb client for `prepareTransaction`. A Thirdweb Account does not carry a client.\n * Pass the secret-key client from the server, or omit this to use `getClient()`.\n */\n client?: ThirdwebClient\n}\n\n/**\n * Wrap a Thirdweb Account so AA gas sponsorship still flows through thirdweb `sendTransaction`.\n */\nexport function fromThirdwebAccount(\n account: Account,\n options?: FromThirdwebAccountOptions,\n): PublishWallet {\n const explicitClient = options?.client\n const address = account.address as Address\n const signer = brandSigner({\n address,\n signMessage: async ({ message }) => {\n const sig = await account.signMessage({ message })\n return sig as Hex\n },\n })\n const txSender = brandTxSender({\n address,\n sendTransaction: async (tx) => {\n const client = explicitClient ?? (await import('../publishThirdwebClient')).getClient()\n const chain = getPublishThirdwebChain()\n const transaction = prepareTransaction({\n client,\n chain,\n to: tx.to,\n data: tx.data,\n value: tx.value,\n gas: tx.gas,\n })\n logGas('sending transaction through thirdweb', {\n account: address,\n chainId: chain.id,\n to: tx.to,\n dataBytes: tx.data ? (tx.data.length - 2) / 2 : 0,\n txGas: tx.gas ?? '(none: thirdweb estimates)',\n })\n // Smart accounts send UserOps (EntryPoint nonces); this only matters for plain EOAs.\n let result\n try {\n result = await retryNonceTooLow(() => sendTransaction({ account, transaction }))\n } catch (error) {\n logGas('thirdweb sendTransaction failed', {\n account: address,\n error: error instanceof Error ? error.message : String(error),\n })\n throw error\n }\n logGas('thirdweb sendTransaction returned', { account: address, transactionHash: result.transactionHash })\n return { transactionHash: result.transactionHash as Hex }\n },\n })\n return { signer, txSender }\n}\n\n/**\n * Coerce Thirdweb Account, SeedSigner, or PublishWallet to PublishWallet.\n */\nexport function asThirdwebPublishWallet(\n accountOrWallet: Account | SeedSigner | PublishWallet,\n options?: FromThirdwebAccountOptions,\n): PublishWallet {\n if (isPublishWallet(accountOrWallet)) return accountOrWallet\n if (isSeedSigner(accountOrWallet)) {\n throw new Error(\n '@seedprotocol/publish/thirdweb: SeedSigner alone cannot send sponsored txs. Pass fromThirdwebAccount(account) or a PublishWallet.',\n )\n }\n return fromThirdwebAccount(accountOrWallet, options)\n}\n\n/** @deprecated Prefer {@link asThirdwebPublishWallet}; kept for call-site migration. */\nexport function asSeedSignerFromThirdweb(\n accountOrWallet: Account | SeedSigner | PublishWallet,\n): SeedSigner {\n if (isPublishWallet(accountOrWallet)) return accountOrWallet.signer\n if (isSeedSigner(accountOrWallet)) return accountOrWallet\n return fromThirdwebAccount(accountOrWallet).signer\n}\n","import { getPublishConfig } from '../config'\nimport { getPublishPublicClient, isContractDeployed } from './chainClient'\nimport { getPublishRpcUrl } from './chainConfig'\n\n/** Thrown by {@link verifyPublishChain}; `problems` lists every check that failed. */\nexport class PublishChainConfigError extends Error {\n override name = 'PublishChainConfigError'\n constructor(\n readonly chainId: number,\n readonly problems: string[],\n ) {\n super(\n `@seedprotocol/publish: chain ${chainId} is not set up for publishing:\\n- ${problems.join('\\n- ')}`,\n )\n }\n}\n\nlet verified: { key: string; result: Promise<void> } | null = null\n\nfunction configKey(): string {\n const cfg = getPublishConfig()\n return [\n cfg.chain.id,\n getPublishRpcUrl(),\n cfg.easContractAddress,\n cfg.schemaRegistryAddress,\n cfg.thirdwebAccountFactoryAddress ?? '',\n cfg.modularAccountModuleContract ?? '',\n ]\n .join('|')\n .toLowerCase()\n}\n\nasync function runChecks(): Promise<void> {\n const cfg = getPublishConfig()\n const { chain } = cfg\n const problems: string[] = []\n\n let rpcChainId: number | undefined\n try {\n rpcChainId = await getPublishPublicClient().getChainId()\n } catch (cause) {\n throw new PublishChainConfigError(chain.id, [\n `could not reach the RPC (${redactRpcUrl(getPublishRpcUrl())}): ${cause instanceof Error ? cause.message : String(cause)}`,\n ])\n }\n if (rpcChainId !== chain.id) {\n // Contract checks against the wrong chain would only add noise.\n throw new PublishChainConfigError(chain.id, [\n `the RPC reports chain ${rpcChainId}, but PublishConfig.chain is ${chain.name} (${chain.id}). Point rpcUrl at ${chain.name}.`,\n ])\n }\n\n const contracts: Array<[label: string, address: string | undefined, fix: string]> = [\n ['EAS contract', cfg.easContractAddress, 'set easContractAddress'],\n ['EAS SchemaRegistry', cfg.schemaRegistryAddress, 'set schemaRegistryAddress'],\n [\n 'ManagedAccount factory',\n cfg.thirdwebAccountFactoryAddress,\n 'deploy the factory or fix managedAccountFactoryAddress',\n ],\n [\n 'executor module',\n cfg.modularAccountModuleContract?.trim() || undefined,\n 'deploy the module or fix modularAccountModuleContract',\n ],\n ]\n const results = await Promise.all(\n contracts.map(async ([label, address, fix]) => {\n if (!address) return null\n const deployed = await isContractDeployed(address)\n return deployed ? null : `no ${label} at ${address} on ${chain.name}; ${fix}.`\n }),\n )\n for (const r of results) if (r) problems.push(r)\n\n if (problems.length > 0) throw new PublishChainConfigError(chain.id, problems)\n}\n\n/** Hide API keys embedded in RPC URLs (e.g. Thirdweb client ids) from error messages. */\nfunction redactRpcUrl(url: string): string {\n try {\n const u = new URL(url)\n return `${u.protocol}//${u.host}`\n } catch {\n return 'configured rpcUrl'\n }\n}\n\n/**\n * Checks that the configured chain is usable before anything is sent: the RPC reports\n * `PublishConfig.chain.id`, and EAS, the SchemaRegistry and (when configured) the ManagedAccount\n * factory and executor module have code at their addresses.\n *\n * Runs once per configuration (cached; a failure is retried on the next call). The publish\n * flow calls it before the first attestation; apps can call it at startup to fail early.\n *\n * @throws PublishChainConfigError listing every failed check\n */\nexport function verifyPublishChain(): Promise<void> {\n const key = configKey()\n if (verified?.key === key) return verified.result\n const result = runChecks()\n verified = { key, result }\n result.catch(() => {\n if (verified?.result === result) verified = null\n })\n return result\n}\n\n/** @internal Tests only. */\nexport function resetVerifiedPublishChain(): void {\n verified = null\n}\n","import { prepareEasMultiRevoke } from '~/helpers/easDirect'\nimport { getPublishPublicClient, waitForPublishReceipt } from '~/helpers/chainClient'\nimport { easAbi } from '~/helpers/abi/eas'\nimport { findRevertData } from '~/helpers/describeRevert'\nimport { getPublishWallet } from '~/helpers/publishWalletRegistry'\nimport { fromThirdwebAccount } from '~/helpers/adapters/thirdwebAccount'\nimport type { PublishWallet } from '~/helpers/seedSigner'\nimport type { Hex } from 'viem'\nimport { getPublishConfig } from '~/config'\nimport { verifyPublishChain } from '~/helpers/verifyPublishChain'\nimport {\n getVersionsForSeedUid,\n getMetadataAttestationUidsForSeedUid,\n getAttesterForSeed,\n updateSeedRevokedAt,\n VERSION_SCHEMA_UID,\n isValidEasAttestationUid,\n getGetAdditionalSyncAddresses,\n assertLocalDbChain,\n} from '@seedprotocol/sdk'\n\n/**\n * True when the EAS attester is the configured executor module (legacy path where the\n * module itself was recorded as attester). ManagedAccount attesters are not blocked.\n */\nasync function isLegacyModularExecutorAttester(attester: string | null): Promise<boolean> {\n if (!attester) return false\n const additionalGetter = getGetAdditionalSyncAddresses()\n if (!additionalGetter) return false\n const additional = await additionalGetter()\n const attesterLower = attester.toLowerCase()\n return !!additional?.some((a: string | undefined) => a?.toLowerCase() === attesterLower)\n}\n\n/**\n * True when `wallet` is an automation session key on the ManagedAccount that attested the seed.\n * Read failures count as false: the revoke then goes to EAS, and the account rejects it.\n */\nasync function isAutomationRevoke(\n wallet: PublishWallet,\n attester: string | null,\n): Promise<boolean> {\n if (!attester || !getPublishConfig().modularAccountModuleContract?.trim()) return false\n const signerAddress = wallet.signer?.address\n if (!signerAddress || signerAddress.toLowerCase() === attester.toLowerCase()) return false\n try {\n const { isAutomationSessionActive } = await import('~/helpers/ensureAutomationSessionKey')\n return await isAutomationSessionActive(attester, signerAddress)\n } catch {\n return false\n }\n}\n\nconst ALREADY_REVOKED_SELECTOR = '0x905e7107'\nconst ACCESS_DENIED_SELECTOR = '0x4ca88867'\n\nfunction sameAddress(a: string | null | undefined, b: string | null | undefined): boolean {\n return !!a && !!b && a.toLowerCase() === b.toLowerCase()\n}\n\nfunction revertMatches(err: unknown, name: string, selector: string): boolean {\n const data = findRevertData(err)\n if (data?.toLowerCase().startsWith(selector)) return true\n const msg = err instanceof Error ? err.message : String(err)\n return msg.includes(name) || msg.toLowerCase().includes(selector)\n}\n\n/**\n * Picks the wallet that sends `multiRevoke`: it must be the attester, since EAS lets only the\n * attester revoke. The registered wallet is used when it is the attester. Otherwise (no wallet\n * registered, or the registered one is a different account, e.g. the in-app admin wallet that\n * ConnectButton registers under `useModularExecutor` while the ManagedAccount attested) the\n * connected Thirdweb account is resolved to the attester's account. When that fails and a wallet\n * is registered, the registered wallet is kept: the automation check below, or EAS's\n * AccessDenied, then says why it cannot revoke.\n */\nasync function resolveRevokeWallet(attester: string | null): Promise<PublishWallet> {\n const registered = getPublishWallet()\n if (registered && (!attester || sameAddress(registered.txSender.address, attester))) {\n return registered\n }\n try {\n const { getConnectedAccount } = await import('~/helpers/thirdweb')\n const { resolveRevokeAccount } = await import('~/helpers/resolveRevokeAccount')\n const account = await getConnectedAccount()\n if (!account) {\n throw new Error('No wallet connected. Connect a wallet to revoke attestations.')\n }\n const revokeAccount = await resolveRevokeAccount({ account, attester })\n if (!registered || sameAddress(revokeAccount.address, attester)) {\n return fromThirdwebAccount(revokeAccount)\n }\n } catch (err) {\n if (registered) return registered\n if (err instanceof Error && err.message.includes('No wallet connected')) throw err\n if (err instanceof Error && err.message.includes('Revocation not supported')) throw err\n throw new Error(\n 'No wallet connected. Use useSeedWallet / setPublishWallet, or @seedprotocol/publish/thirdweb ConnectButton.',\n { cause: err },\n )\n }\n return registered\n}\n\n/**\n * UIDs among `uids` that EAS already shows as revoked. A failed read counts as not revoked:\n * the revoke is then sent, and an AlreadyRevoked revert is handled by the caller.\n */\nasync function findRevokedUids(uids: readonly Hex[]): Promise<Set<string>> {\n const revoked = new Set<string>()\n const { easContractAddress } = getPublishConfig()\n if (!easContractAddress || uids.length === 0) return revoked\n let client: ReturnType<typeof getPublishPublicClient>\n try {\n client = getPublishPublicClient()\n } catch {\n return revoked\n }\n await Promise.all(\n uids.map(async (uid) => {\n try {\n const attestation = await client.readContract({\n address: easContractAddress as Hex,\n abi: easAbi,\n functionName: 'getAttestation',\n args: [uid],\n })\n if (attestation.revocationTime > 0n) revoked.add(uid.toLowerCase())\n } catch {\n // Unknown state: leave it in the batch.\n }\n }),\n )\n return revoked\n}\n\n/**\n * Sends one per-schema `multiRevoke`, leaving out uids EAS already shows as revoked. EAS reverts\n * the whole batch on one already-revoked uid, so on AlreadyRevoked the state is read again and\n * the rest are sent once more. A batch of one that reverts AlreadyRevoked is done.\n */\nasync function revokeBatch(\n txSender: PublishWallet['txSender'],\n req: { schema: Hex; data: Array<{ uid: Hex; value?: bigint }> },\n): Promise<void> {\n let data = req.data\n for (let attempt = 0; ; attempt++) {\n const revoked = await findRevokedUids(data.map((d) => d.uid))\n data = data.filter((d) => !revoked.has(d.uid.toLowerCase()))\n if (data.length === 0) return\n try {\n const result = await txSender.sendTransaction(prepareEasMultiRevoke([{ schema: req.schema, data }]))\n await waitForPublishReceipt(result.transactionHash)\n return\n } catch (err: unknown) {\n if (revertMatches(err, 'AccessDenied', ACCESS_DENIED_SELECTOR)) {\n throw new Error(\n 'Only the original attester can revoke attestations. Connect the wallet that published this item.',\n )\n }\n if (!revertMatches(err, 'AlreadyRevoked', ALREADY_REVOKED_SELECTOR)) throw err\n if (data.length === 1) return\n if (attempt > 0) {\n throw new Error(\n `multiRevoke for schema ${req.schema} reverted with AlreadyRevoked, and EAS could not be read to tell which of its ${data.length} attestations are already revoked. Retry the revoke.`,\n { cause: err },\n )\n }\n }\n }\n}\n\n/**\n * Revokes the Seed attestation and all Version and metadata attestations on EAS.\n * Sends from the attester: the registered publish wallet when it is the attester, else the\n * connected Thirdweb account resolved to the attester (see {@link resolveRevokeWallet}).\n *\n * Only the attester's owner can revoke: `multiRevoke` goes to EAS from the publishing account\n * (for a ManagedAccount, a UserOp `execute(EAS, multiRevoke)`). The Seed executor has no revoke,\n * so automation session keys and seeds attested by the executor itself cannot be revoked here.\n */\nexport async function revokeAttestations(params: {\n seedLocalId: string\n seedUid: string\n seedSchemaUid: string\n}): Promise<void> {\n const { seedLocalId, seedUid, seedSchemaUid } = params\n // Revoking on one chain must not update revokedAt for a seed attested on another.\n await assertLocalDbChain()\n await verifyPublishChain()\n const attester = await getAttesterForSeed({ seedLocalId, seedUid })\n if (await isLegacyModularExecutorAttester(attester)) {\n throw new Error(\n 'Revocation not supported for items attested by the Seed executor module: the executor has no revoke and is the only attester that could revoke them.',\n )\n }\n\n const wallet = await resolveRevokeWallet(attester)\n\n const txSender = wallet.txSender\n if (await isAutomationRevoke(wallet, attester)) {\n throw new Error(\n 'Automation session keys cannot revoke attestations. Revoking is owner-only: connect the account that published this item.',\n )\n }\n\n const [versionRows, metadataRows] = await Promise.all([\n getVersionsForSeedUid(seedUid),\n getMetadataAttestationUidsForSeedUid(seedUid),\n ])\n\n const versionUids = versionRows\n .map((r: { uid: string }) => r.uid)\n .filter((uid: string) => isValidEasAttestationUid(uid))\n const metadataBySchema = new Map<string, string[]>()\n for (const { uid, schemaUid } of metadataRows) {\n if (!isValidEasAttestationUid(uid)) continue\n const list = metadataBySchema.get(schemaUid) ?? []\n list.push(uid)\n metadataBySchema.set(schemaUid, list)\n }\n\n const requests: Array<{\n schema: `0x${string}`\n data: Array<{ uid: `0x${string}`; value?: bigint }>\n }> = []\n\n for (const [schemaUid, uids] of metadataBySchema) {\n if (uids.length > 0) {\n requests.push({\n schema: schemaUid as `0x${string}`,\n data: uids.map((uid: string) => ({ uid: uid as `0x${string}` })),\n })\n }\n }\n\n if (versionUids.length > 0) {\n requests.push({\n schema: VERSION_SCHEMA_UID as `0x${string}`,\n data: versionUids.map((uid: string) => ({ uid: uid as `0x${string}` })),\n })\n }\n\n requests.push({\n schema: seedSchemaUid as `0x${string}`,\n data: [{ uid: seedUid as `0x${string}` }],\n })\n\n for (const req of requests) {\n if (req.data.length === 0) continue\n await revokeBatch(txSender, req)\n }\n\n const revokedAt = Math.floor(Date.now() / 1000)\n // Mark the revoked version and property attestations too, so local rows read as revoked before the\n // next EAS sync confirms it (sync keeps them as the item's last values, see ADR 0006).\n await updateSeedRevokedAt({\n seedLocalId,\n revokedAt,\n metadataUids: [...metadataBySchema.values()].flat(),\n versionUids,\n })\n}\n","import { assign } from 'xstate'\n\nexport const assignRestoreFromDb = assign(({ context, event }) => {\n const ev = event as {\n publishProcesses?: Map<string, unknown>\n subscriptions?: Map<string, unknown>\n }\n const incomingProcesses = ev.publishProcesses ?? new Map()\n const incomingSubscriptions = ev.subscriptions ?? new Map()\n return {\n publishProcesses: new Map(incomingProcesses as Map<string, import('xstate').ActorRef<any, any>>),\n subscriptions: new Map(\n incomingSubscriptions as Map<string, import('xstate').ActorRef<any, import('xstate').EventObject>>\n ),\n }\n})\n","import Arweave from 'arweave'\nimport { BaseArweaveClient } from '@seedprotocol/sdk'\n\n/**\n * `arweave` client for the configured gateway, keeping its protocol and port so local gateways\n * (e.g. `http://localhost:1984`) work. See {@link BaseArweaveClient.getArweaveJsApiConfig}.\n */\nexport const getArweave = (): Arweave => {\n const options = BaseArweaveClient.getArweaveJsApiConfig()\n\n const ArweaveModule = Arweave as typeof Arweave & { default?: typeof Arweave }\n if (Object.keys(ArweaveModule).includes('default') && ArweaveModule.default) {\n return ArweaveModule.default.init(options)\n }\n\n return ArweaveModule.init(options)\n}\n","import { Item, type IItem } from '@seedprotocol/sdk'\n\nexport const ZERO_BYTES32 = '0x' + '0'.repeat(64)\nexport const BYTES32_LEN = 64\n\nexport const waitForItem = async (seedLocalId: string): Promise<IItem<any>> => {\n let item: IItem<any> | undefined\n\n try {\n item = await Item.find({ seedLocalId } as Parameters<typeof Item.find>[0])\n } catch {\n // No-op: Error is intentionally ignored\n }\n\n if (item) {\n return item\n }\n\n return new Promise<IItem<any>>((resolve) => {\n const interval = setInterval(() => {\n try {\n Item.find({ seedLocalId } as Parameters<typeof Item.find>[0])\n .then((found: IItem<any> | undefined) => {\n if (found) {\n clearInterval(interval)\n resolve(found)\n }\n })\n } catch {\n // No-op: Error is intentionally ignored\n }\n }, 200)\n })\n}\n\nexport function deserializeChunks(\n serialized: unknown\n): {\n data_root: Uint8Array\n chunks: Array<{ dataHash: Uint8Array; minByteRange: number; maxByteRange: number }>\n proofs: Array<{ offset: number; proof: Uint8Array }>\n} | undefined {\n if (!serialized || typeof serialized !== 'object') return undefined\n const s = serialized as {\n data_root?: number[]\n chunks?: Array<{ dataHash: number[]; minByteRange: number; maxByteRange: number }>\n proofs?: Array<{ offset: number; proof: number[] }>\n }\n if (!Array.isArray(s.data_root)) return undefined\n return {\n data_root: new Uint8Array(s.data_root),\n chunks: (s.chunks ?? []).map((c) => ({ ...c, dataHash: new Uint8Array(c.dataHash ?? []) })),\n proofs: (s.proofs ?? []).map((p) => ({ ...p, proof: new Uint8Array(p.proof ?? []) })),\n }\n}\n\nexport function serializeChunks(chunks: {\n data_root: Uint8Array\n chunks: Array<{ dataHash: Uint8Array; minByteRange: number; maxByteRange: number }>\n proofs: Array<{ offset: number; proof: Uint8Array }>\n}): unknown {\n return {\n data_root: Array.from(chunks.data_root),\n chunks: chunks.chunks.map((c) => ({ ...c, dataHash: Array.from(c.dataHash) })),\n proofs: chunks.proofs.map((p) => ({ ...p, proof: Array.from(p.proof) })),\n }\n}\n","import type { GetPublishUploadsOptions } from '@seedprotocol/sdk'\nimport { fromPromise } from 'xstate'\nimport type { PublishMachineContext } from '../../../types'\nimport type { ArweaveTransactionInfo } from '../../../types'\nimport type { PublishUpload } from '../../../types'\nimport Transaction from 'arweave/web/lib/transaction'\nimport { getArweave } from '~/helpers/blockchain'\nimport { getPublishConfig } from '~/config'\nimport { waitForItem, deserializeChunks, serializeChunks } from './utils'\n\nexport type CreateArweaveTransactionsResult = {\n arweaveTransactions: ArweaveTransactionInfo[]\n publishUploads: PublishUpload[]\n}\n\ntype PublishInput = { input: { context: PublishMachineContext; event: unknown } }\n\nexport const createArweaveTransactions = fromPromise(\n async ({ input: { context } }: PublishInput): Promise<CreateArweaveTransactionsResult> => {\n let { item } = context\n\n if (!item.getPublishUploads) {\n item = await waitForItem(item.seedLocalId)\n }\n\n const publishOpts: GetPublishUploadsOptions = {}\n if (context.arweaveUploadTags?.length) {\n publishOpts.arweaveUploadTags = context.arweaveUploadTags\n }\n const def = context.htmlEmbeddedDeferredHtmlSeedLocalIds\n if (def?.length) {\n publishOpts.deferHtmlStorageSeedLocalIds = def\n }\n const publishUploads = await item.getPublishUploads(\n Object.keys(publishOpts).length ? publishOpts : undefined,\n )\n\n const config = getPublishConfig()\n const signArweaveTransactions = context.signArweaveTransactions ?? config.signArweaveTransactions\n const arweaveJwk = context.arweaveJwk ?? config.arweaveJwk\n const uploads = publishUploads.map((u: PublishUpload) => ({\n versionLocalId: u.versionLocalId,\n itemPropertyName: u.itemPropertyName,\n transactionJson: (u.transactionToSign as Transaction).toJSON(),\n }))\n\n let results: Array<{ transaction: Record<string, unknown>; versionId?: string; modelName?: string }>\n if (signArweaveTransactions) {\n results = await signArweaveTransactions(uploads)\n } else if (arweaveJwk) {\n const arweave = getArweave()\n const jwk = arweaveJwk\n results = []\n for (const upload of uploads) {\n const tx = arweave.transactions.fromRaw(upload.transactionJson)\n if (tx.data && tx.data.byteLength > 0 && !tx.chunks) {\n await tx.prepareChunks(tx.data)\n }\n await arweave.transactions.sign(tx, jwk)\n const json = tx.toJSON() as Record<string, unknown>\n results.push({\n transaction: {\n ...json,\n chunks: tx.chunks ? serializeChunks(tx.chunks) : undefined,\n },\n versionId: upload.versionLocalId,\n modelName: upload.itemPropertyName,\n })\n }\n } else {\n throw new Error(\n 'Arweave signing not configured. Provide signArweaveTransactions or arweaveJwk at createPublish or in PublishProvider config.'\n )\n }\n\n const arweave = getArweave()\n const arweaveTransactions: ArweaveTransactionInfo[] = (\n results as Array<{ transaction: Record<string, unknown>; versionId?: string; modelName?: string }>\n ).map((r) => {\n const { chunks: serializedChunks, ...rest } = r.transaction as Record<string, unknown>\n const attrs = { ...rest }\n const chunks = deserializeChunks(serializedChunks)\n if (chunks) (attrs as Record<string, unknown>).chunks = chunks\n const tx = arweave.transactions.fromRaw(attrs)\n return {\n transaction: tx,\n versionId: r.versionId,\n modelName: r.modelName,\n }\n })\n\n return {\n arweaveTransactions,\n publishUploads,\n }\n }\n)\n","import type { GetPublishUploadsOptions } from '@seedprotocol/sdk'\nimport { fromPromise } from 'xstate'\nimport type { PublishMachineContext } from '../../../types'\nimport type { ArweaveTransactionInfo } from '../../../types'\nimport type { PublishUpload } from '../../../types'\nimport Transaction from 'arweave/web/lib/transaction'\nimport { getArweave } from '~/helpers/blockchain'\nimport { getPublishConfig } from '~/config'\nimport { waitForItem, deserializeChunks, serializeChunks } from './utils'\nimport type { CreateArweaveTransactionsResult } from './createArweaveTransactions'\n\ntype PublishInput = { input: { context: PublishMachineContext; event: unknown } }\n\n/** Phase 2: deferred Html storage files only (after embedded images uploaded + Html rewritten). */\nexport const createArweaveTransactionsPhase2 = fromPromise(\n async ({ input: { context } }: PublishInput): Promise<CreateArweaveTransactionsResult> => {\n let { item } = context\n\n if (!item.getPublishUploads) {\n item = await waitForItem(item.seedLocalId)\n }\n\n const publishOpts: GetPublishUploadsOptions = {}\n if (context.arweaveUploadTags?.length) {\n publishOpts.arweaveUploadTags = context.arweaveUploadTags\n }\n const def = context.htmlEmbeddedDeferredHtmlSeedLocalIds\n if (def?.length) {\n publishOpts.onlyHtmlStorageSeedLocalIds = def\n // Walks relations: a related draft's deferred Html (embedded images) is uploaded here too.\n }\n\n const publishUploads = await item.getPublishUploads(\n Object.keys(publishOpts).length ? publishOpts : undefined,\n )\n\n const config = getPublishConfig()\n const signArweaveTransactions = context.signArweaveTransactions ?? config.signArweaveTransactions\n const arweaveJwk = context.arweaveJwk ?? config.arweaveJwk\n const uploads = publishUploads.map((u: PublishUpload) => ({\n versionLocalId: u.versionLocalId,\n itemPropertyName: u.itemPropertyName,\n transactionJson: (u.transactionToSign as Transaction).toJSON(),\n }))\n\n let results: Array<{ transaction: Record<string, unknown>; versionId?: string; modelName?: string }>\n if (signArweaveTransactions) {\n results = await signArweaveTransactions(uploads)\n } else if (arweaveJwk) {\n const arweave = getArweave()\n const jwk = arweaveJwk\n results = []\n for (const upload of uploads) {\n const tx = arweave.transactions.fromRaw(upload.transactionJson)\n if (tx.data && tx.data.byteLength > 0 && !tx.chunks) {\n await tx.prepareChunks(tx.data)\n }\n await arweave.transactions.sign(tx, jwk)\n const json = tx.toJSON() as Record<string, unknown>\n results.push({\n transaction: {\n ...json,\n chunks: tx.chunks ? serializeChunks(tx.chunks) : undefined,\n },\n versionId: upload.versionLocalId,\n modelName: upload.itemPropertyName,\n })\n }\n } else {\n throw new Error(\n 'Arweave signing not configured. Provide signArweaveTransactions or arweaveJwk at createPublish or in PublishProvider config.'\n )\n }\n\n const arweave = getArweave()\n const arweaveTransactions: ArweaveTransactionInfo[] = (\n results as Array<{ transaction: Record<string, unknown>; versionId?: string; modelName?: string }>\n ).map((r) => {\n const { chunks: serializedChunks, ...rest } = r.transaction as Record<string, unknown>\n const attrs = { ...rest }\n const chunks = deserializeChunks(serializedChunks)\n if (chunks) (attrs as Record<string, unknown>).chunks = chunks\n const tx = arweave.transactions.fromRaw(attrs)\n return {\n transaction: tx,\n versionId: r.versionId,\n modelName: r.modelName,\n }\n })\n\n return {\n arweaveTransactions,\n publishUploads,\n }\n },\n)\n","import { prepareHtmlEmbeddedImagesForPublish } from '@seedprotocol/sdk'\nimport { fromPromise } from 'xstate'\nimport type { PublishMachineContext } from '../../../types'\n\ntype Input = { input: { context: PublishMachineContext } }\n\n/**\n * Creates Image items + co-publish rows for Html `data:image/*` URIs before Arweave/DataItem build.\n * Runs for both L1 and bundler; deferred Html ids drive two-phase upload + rewrite in the machine.\n */\nexport const preparingHtmlEmbedded = fromPromise(\n async ({ input: { context } }: Input): Promise<{ deferredHtmlSeedLocalIds: string[] }> => {\n const policy = context.htmlEmbeddedDataUriPolicy ?? 'materialize'\n const r = await prepareHtmlEmbeddedImagesForPublish(context.item, policy)\n return { deferredHtmlSeedLocalIds: r.deferredHtmlSeedLocalIds }\n },\n)\n","import { rewriteHtmlEmbeddedImagesOnDisk } from '@seedprotocol/sdk'\nimport { fromPromise } from 'xstate'\nimport type { PublishMachineContext } from '../../../types'\nimport type { ArweaveTransactionInfo } from '../../../types'\nimport type { PublishUpload } from '../../../types'\n\ntype Input = { input: { context: PublishMachineContext } }\n\nfunction toUploadedPairs(\n txs: ArweaveTransactionInfo[] | undefined,\n ups: PublishUpload[] | undefined,\n): { txId: string; seedLocalId?: string; versionLocalId?: string }[] {\n const out: { txId: string; seedLocalId?: string; versionLocalId?: string }[] = []\n const n = Math.min(txs?.length ?? 0, ups?.length ?? 0)\n for (let i = 0; i < n; i++) {\n const t = txs![i]!\n const u = ups![i]!\n const id = t.transaction?.id\n if (typeof id === 'string' && id.length > 0) {\n out.push({ txId: id, seedLocalId: u.seedLocalId, versionLocalId: u.versionLocalId })\n }\n }\n return out\n}\n\nexport const rewritingHtmlEmbedded = fromPromise(\n async ({ input: { context } }: Input): Promise<void> => {\n const pairs = toUploadedPairs(\n context.htmlEmbeddedPhase1ArweaveTransactions,\n context.htmlEmbeddedPhase1PublishUploads as PublishUpload[] | undefined,\n )\n await rewriteHtmlEmbeddedImagesOnDisk(\n context.item.seedLocalId,\n pairs,\n context.htmlEmbeddedDeferredHtmlSeedLocalIds,\n )\n },\n)\n","/**\n * Raw upload data (bytes + Content-SHA-256 / Content-Type / configured tags) for the bundler /\n * DataItem path. The builder lives in the SDK (`getPublishUploadData`, next to `getPublishUploads`,\n * which makes L1 transactions from the same data), so both publish paths upload the same bytes\n * with the same tags.\n *\n * Kept as a module of its own so publish actors (and their tests) have one import to mock.\n */\nimport { getPublishUploadData as sdkGetPublishUploadData } from '@seedprotocol/sdk'\nimport type { GetPublishUploadsOptions, PublishUploadData } from '@seedprotocol/sdk'\n\nexport type { PublishUploadData }\n\n/** Same options as the SDK's getPublishUploads (extra tags, two-phase Html embedded-image publish). */\nexport type GetPublishUploadDataOptions = GetPublishUploadsOptions\n\nexport const getPublishUploadData = (\n ...args: Parameters<typeof sdkGetPublishUploadData>\n): ReturnType<typeof sdkGetPublishUploadData> => sdkGetPublishUploadData(...args)\n","import { ethers } from 'ethers'\nimport type { SeedSigner } from './seedSigner'\n\n// ============================================================================\n// ANS-104 Data Item construction — zero Node.js dependencies\n//\n// A data item is a binary structure:\n// [signature type (2 bytes)]\n// [signature (65 bytes for Ethereum)]\n// [owner/public key (65 bytes for Ethereum)]\n// [target flag (1 byte) + optional target (32 bytes)]\n// [anchor flag (1 byte) + optional anchor (32 bytes)]\n// [number of tags (8 bytes, little-endian)]\n// [number of tag bytes (8 bytes, little-endian)]\n// [serialized tags (Avro ZigZag VInt format per ANS-104)]\n// [data]\n// ============================================================================\n\nconst SIG_TYPE_ETHEREUM = 3\nconst SIG_LENGTH = 65\n\nconst PLACEHOLDER_MESSAGE = new TextEncoder().encode('seed-recovery')\n\ninterface Tag {\n name: string\n value: string\n}\n\nconst ANCHOR_LENGTH = 32\n\n/**\n * 32-byte ANS-104 anchor for publish uniqueness (timestamp + signer + nonce).\n * Matches arbundles: presence flag + exactly 32 bytes when set.\n */\nconst UINT64_MASK = 0xffffffffffffffffn\n\nexport function buildPublishAnchorBytes(\n walletAddress: string,\n timestampMs: number,\n uniqueness: bigint,\n): Uint8Array {\n const hash = ethers.solidityPackedKeccak256(\n ['uint256', 'address', 'uint64'],\n [BigInt(timestampMs), walletAddress, uniqueness & UINT64_MASK],\n )\n return ethers.getBytes(hash)\n}\n\nfunction encodeTargetOrAnchorSection(raw: Uint8Array): Uint8Array {\n if (raw.length === 0) return new Uint8Array([0])\n if (raw.length !== ANCHOR_LENGTH) {\n throw new Error(`ANS-104 target/anchor must be empty or ${ANCHOR_LENGTH} bytes, got ${raw.length}`)\n }\n const out = new Uint8Array(1 + ANCHOR_LENGTH)\n out[0] = 1\n out.set(raw, 1)\n return out\n}\n\n/**\n * Type guard: true if signer is ethers.Wallet (has privateKey). SeedSigner / Thirdweb Account do not.\n */\nexport function isEthersWallet(signer: unknown): signer is ethers.Wallet {\n return (\n signer != null &&\n typeof signer === 'object' &&\n 'privateKey' in signer &&\n typeof (signer as ethers.Wallet).privateKey === 'string'\n )\n}\n\n/**\n * Write ZigZag-encoded variable-length integer (Avro long format).\n * Used for tag array and per-tag name/value lengths per ANS-104.\n */\nfunction writeZigZagVInt(n: number, out: Uint8Array, offset: number): number {\n const zigzag = n >= 0 ? n << 1 : (~n << 1) | 1\n let m = zigzag\n let pos = offset\n do {\n const byte = m & 0x7f\n m >>>= 7\n out[pos++] = m ? byte | 0x80 : byte\n } while (m)\n return pos - offset\n}\n\n/**\n * Serialize tags into ANS-104 Avro format (matches arbundles/Irys).\n * Format: [block count VInt][for each tag: name_len VInt][name][value_len VInt][value]][0 VInt]\n */\nexport const serializeTags = (tags: Tag[]): Uint8Array => {\n if (!tags?.length) return new Uint8Array(0)\n\n const encoder = new TextEncoder()\n const temp = new Uint8Array(16)\n const chunks: Uint8Array[] = []\n\n const appendLong = (n: number) => {\n const len = writeZigZagVInt(n, temp, 0)\n chunks.push(temp.slice(0, len))\n }\n\n appendLong(tags.length)\n for (const tag of tags) {\n const nameBytes = encoder.encode(tag.name)\n const valueBytes = encoder.encode(tag.value)\n appendLong(nameBytes.length)\n chunks.push(nameBytes)\n appendLong(valueBytes.length)\n chunks.push(valueBytes)\n }\n appendLong(0)\n\n const totalLength = chunks.reduce((sum, c) => sum + c.length, 0)\n const result = new Uint8Array(totalLength)\n let pos = 0\n for (const chunk of chunks) {\n result.set(chunk, pos)\n pos += chunk.length\n }\n return result\n}\n\n/**\n * Write a 64-bit little-endian unsigned integer into a Uint8Array.\n * (Tag counts and byte lengths use 8-byte LE in ANS-104)\n */\nexport const writeUint64LE = (value: number): Uint8Array => {\n const buf = new Uint8Array(8)\n const view = new DataView(buf.buffer)\n // Safe for values up to Number.MAX_SAFE_INTEGER\n view.setUint32(0, value & 0xffffffff, true)\n view.setUint32(4, Math.floor(value / 0x100000000), true)\n return buf\n}\n\n/**\n * Arweave deep-hash (SHA-384 based). Used for ANS-104 DataItem signing.\n * Matches arbundles/Irys getSignatureData flow.\n */\nasync function sha384(data: Uint8Array): Promise<Uint8Array> {\n // TS 5.9+: Uint8Array<ArrayBufferLike> is not assignable to BufferSource without narrowing\n return new Uint8Array(\n await crypto.subtle.digest('SHA-384', data as BufferSource),\n )\n}\n\nfunction concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n const out = new Uint8Array(a.length + b.length)\n out.set(a, 0)\n out.set(b, a.length)\n return out\n}\n\nasync function deepHash(data: Uint8Array | Uint8Array[]): Promise<Uint8Array> {\n const enc = new TextEncoder()\n if (Array.isArray(data)) {\n const tag = concat(enc.encode('list'), enc.encode(data.length.toString()))\n let acc = await sha384(tag)\n for (const chunk of data) {\n const chunkHash = await deepHash(chunk)\n acc = await sha384(concat(acc, chunkHash))\n }\n return acc\n }\n const tag = concat(enc.encode('blob'), enc.encode(data.byteLength.toString()))\n const tagHash = await sha384(tag)\n const dataHash = await sha384(data)\n return sha384(concat(tagHash, dataHash))\n}\n\n/**\n * Build the message to sign per ANS-104 / arbundles: deep-hash of DataItem components.\n */\nasync function getSignatureData(\n ownerBytes: Uint8Array,\n rawTarget: Uint8Array,\n rawAnchor: Uint8Array,\n rawTags: Uint8Array,\n rawData: Uint8Array,\n): Promise<Uint8Array> {\n const enc = new TextEncoder()\n return deepHash([\n enc.encode('dataitem'),\n enc.encode('1'),\n enc.encode(SIG_TYPE_ETHEREUM.toString()),\n ownerBytes,\n rawTarget,\n rawAnchor,\n rawTags,\n rawData,\n ])\n}\n\n/**\n * Build the ANS-104 message bytes (everything from owner onward) for the raw DataItem.\n */\nfunction buildMessageBytes(\n ownerBytes: Uint8Array,\n tags: Tag[],\n data: Uint8Array,\n rawTarget: Uint8Array,\n rawAnchor: Uint8Array,\n): Uint8Array {\n const serializedTags = serializeTags(tags)\n const numTagsBytes = writeUint64LE(tags.length)\n const numTagBytesBytes = writeUint64LE(serializedTags.length)\n const targetSection = encodeTargetOrAnchorSection(rawTarget)\n const anchorSection = encodeTargetOrAnchorSection(rawAnchor)\n const messageparts = [\n ownerBytes,\n targetSection,\n anchorSection,\n numTagsBytes,\n numTagBytesBytes,\n serializedTags,\n data,\n ]\n const messageLength = messageparts.reduce((s, p) => s + p.length, 0)\n const message = new Uint8Array(messageLength)\n let offset = 0\n for (const part of messageparts) {\n message.set(part, offset)\n offset += part.length\n }\n return message\n}\n\n/**\n * Assemble the full ANS-104 data item binary and compute its ID.\n * [sig type 2B][signature 65B][owner 65B][...rest of message]\n */\nasync function assembleDataItemAndId(\n signature: Uint8Array,\n message: Uint8Array,\n): Promise<{ id: string; raw: Uint8Array }> {\n const sigTypeBytes = new Uint8Array(2)\n new DataView(sigTypeBytes.buffer).setUint16(0, SIG_TYPE_ETHEREUM, true)\n const fullLength = 2 + SIG_LENGTH + message.length\n const raw = new Uint8Array(fullLength)\n raw.set(sigTypeBytes, 0)\n raw.set(signature, 2)\n raw.set(message, 2 + SIG_LENGTH)\n const hashBuffer = await crypto.subtle.digest('SHA-256', new Uint8Array(signature))\n const id = base64url(new Uint8Array(hashBuffer))\n return { id, raw }\n}\n\n/**\n * Create a signed ANS-104 DataItem. Uses deep-hash for the message to sign (per arbundles/Irys).\n */\nexport const createSignedDataItem = async (\n data: Uint8Array,\n signer: ethers.Wallet,\n tags: Tag[],\n rawAnchor: Uint8Array = new Uint8Array(0),\n): Promise<{ id: string; raw: Uint8Array }> => {\n const pubKeyHex = ethers.SigningKey.computePublicKey(signer.privateKey, false)\n const ownerBytes = ethers.getBytes(pubKeyHex)\n const serializedTags = serializeTags(tags)\n const rawTarget = new Uint8Array(0)\n\n const signatureData = await getSignatureData(\n ownerBytes,\n rawTarget,\n rawAnchor,\n serializedTags,\n data,\n )\n const signature = ethers.getBytes(await signer.signMessage(signatureData))\n\n const message = buildMessageBytes(ownerBytes, tags, data, rawTarget, rawAnchor)\n return assembleDataItemAndId(signature, message)\n}\n\n/**\n * Create a signed ANS-104 DataItem using a SeedSigner (EOA, ManagedAccount, Modular Account).\n * Uses deep-hash for the message to sign (per arbundles/Irys).\n */\nexport const createSignedDataItemWithAccount = async (\n data: Uint8Array,\n account: SeedSigner,\n tags: Tag[],\n rawAnchor: Uint8Array = new Uint8Array(0),\n): Promise<{ id: string; raw: Uint8Array }> => {\n // 1. Recover public key via placeholder sign (Account has no privateKey)\n const placeholderHex = ethers.hexlify(PLACEHOLDER_MESSAGE) as `0x${string}`\n const placeholderSig = await account.signMessage({\n message: { raw: placeholderHex },\n })\n const digest = ethers.hashMessage(PLACEHOLDER_MESSAGE)\n const pubKeyHex = ethers.SigningKey.recoverPublicKey(digest, placeholderSig)\n const ownerBytes = ethers.getBytes(pubKeyHex)\n\n // 2. Build signature data (deep-hash) and sign it\n const serializedTags = serializeTags(tags)\n const rawTarget = new Uint8Array(0)\n const signatureData = await getSignatureData(\n ownerBytes,\n rawTarget,\n rawAnchor,\n serializedTags,\n data,\n )\n const signatureDataHex = ethers.hexlify(signatureData) as `0x${string}`\n const sigHex = await account.signMessage({\n message: { raw: signatureDataHex },\n })\n const signature = ethers.getBytes(sigHex)\n\n // 3. Assemble and return\n const message = buildMessageBytes(ownerBytes, tags, data, rawTarget, rawAnchor)\n return assembleDataItemAndId(signature, message)\n}\n\nconst OWNER_LENGTH_ETHEREUM = 65\n\n/**\n * Byte offset of the tags section (8-byte tag count + 8-byte tag bytes length + tags + data).\n * Mirrors arbundles DataItem.getTagsStart / getAnchorStart.\n */\nfunction getTagsStartOffset(raw: Uint8Array): number | null {\n const targetStart = 2 + SIG_LENGTH + OWNER_LENGTH_ETHEREUM\n if (raw.length < targetStart + 1) return null\n const targetFlag = raw[targetStart]!\n if (targetFlag !== 0 && targetFlag !== 1) return null\n const targetPresent = targetFlag === 1\n if (targetPresent && raw.length < targetStart + 33) return null\n let pos = targetStart + (targetPresent ? 33 : 1)\n if (raw.length < pos + 1) return null\n const anchorFlag = raw[pos]!\n if (anchorFlag !== 0 && anchorFlag !== 1) return null\n const anchorPresent = anchorFlag === 1\n if (anchorPresent && raw.length < pos + 33) return null\n return pos + (anchorPresent ? 33 : 1)\n}\n\nfunction sliceTargetAndAnchor(\n raw: Uint8Array,\n): { rawTarget: Uint8Array; rawAnchor: Uint8Array; tagsStart: number } | null {\n const tagsStart = getTagsStartOffset(raw)\n if (tagsStart == null) return null\n const targetStart = 2 + SIG_LENGTH + OWNER_LENGTH_ETHEREUM\n const targetPresent = raw[targetStart] === 1\n const rawTarget = targetPresent ? raw.slice(targetStart + 1, targetStart + 33) : new Uint8Array(0)\n const anchorStart = targetStart + (targetPresent ? 33 : 1)\n const anchorPresent = raw[anchorStart] === 1\n const rawAnchor = anchorPresent ? raw.slice(anchorStart + 1, anchorStart + 33) : new Uint8Array(0)\n return { rawTarget, rawAnchor, tagsStart }\n}\n\n/**\n * Verify an ANS-104 DataItem (Ethereum sig type 3) before upload.\n * Uses deep-hash for the expected message (per arbundles/Irys).\n */\nexport async function verifyDataItem(raw: Uint8Array): Promise<boolean> {\n const parsed = sliceTargetAndAnchor(raw)\n if (parsed == null) return false\n const { rawTarget, rawAnchor, tagsStart } = parsed\n const minLength = tagsStart + 16\n if (raw.length < minLength) return false\n\n const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength)\n const sigType = view.getUint16(0, true)\n if (sigType !== SIG_TYPE_ETHEREUM) return false\n\n const signature = raw.slice(2, 2 + SIG_LENGTH)\n const ownerBytes = raw.slice(2 + SIG_LENGTH, 2 + SIG_LENGTH + OWNER_LENGTH_ETHEREUM)\n\n const numTagBytes = Number(\n view.getUint32(tagsStart + 8, true) + view.getUint32(tagsStart + 12, true) * 0x100000000\n )\n const tagsEnd = tagsStart + 16 + numTagBytes\n if (raw.length < tagsEnd) return false\n\n const rawTags = raw.slice(tagsStart + 16, tagsEnd)\n const rawData = raw.slice(tagsEnd)\n\n try {\n const signatureData = await getSignatureData(\n ownerBytes,\n rawTarget,\n rawAnchor,\n rawTags,\n rawData,\n )\n const digest = ethers.hashMessage(signatureData)\n const sigHex = ethers.hexlify(signature)\n const recoveredPubKey = ethers.SigningKey.recoverPublicKey(digest, sigHex)\n const recoveredBytes = ethers.getBytes(recoveredPubKey)\n return (\n recoveredBytes.length === ownerBytes.length &&\n recoveredBytes.every((b, i) => b === ownerBytes[i])\n )\n } catch {\n return false\n }\n}\n\n/**\n * Base64url encode (no padding) — used for data item IDs\n */\nexport const base64url = (bytes: Uint8Array): string => {\n let binary = ''\n for (const byte of bytes) {\n binary += String.fromCharCode(byte)\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}","import type { GetPublishUploadDataOptions, PublishUploadData } from '../helpers/getPublishUploadData'\nimport debug from 'debug'\nimport { fromPromise } from 'xstate'\nimport type { PublishMachineContext } from '../../../types'\nimport type { ArweaveTransactionInfo } from '../../../types'\nimport type { PublishUpload } from '../../../types'\nimport { waitForItem } from './utils'\nimport { getPublishUploadData } from '../helpers/getPublishUploadData'\nimport { getPublishConfig } from '~/config'\nimport {\n buildPublishAnchorBytes,\n createSignedDataItem,\n createSignedDataItemWithAccount,\n isEthersWallet,\n verifyDataItem,\n} from '~/helpers/arweave'\nimport { isPublishWallet, type SeedSigner } from '~/helpers/seedSigner'\n\nconst logger = debug('seedProtocol:createArweaveDataItems')\n\n\n\nexport type CreateArweaveDataItemsResult = {\n arweaveTransactions: ArweaveTransactionInfo[]\n publishUploads: PublishUpload[]\n /** Signed DataItems for uploadViaBundler (dataItemSigner path only). */\n signedDataItems?: unknown[]\n}\n\ntype PublishInput = { input: { context: PublishMachineContext; event: unknown } }\n\ntype Signers = {\n signDataItems: PublishMachineContext['signDataItems']\n dataItemSigner: PublishMachineContext['dataItemSigner']\n}\n\n/**\n * Sign raw upload payloads as DataItems (phase 1 or phase 2). Shared by createArweaveDataItems and phase-2 actor.\n */\nexport async function signBundlerUploadDataList(\n uploadDataList: PublishUploadData[],\n signDataItems: Signers['signDataItems'],\n dataItemSigner: Signers['dataItemSigner'],\n): Promise<CreateArweaveDataItemsResult> {\n let arweaveTransactions: ArweaveTransactionInfo[]\n let signedDataItems: unknown[] | undefined\n\n if (signDataItems) {\n const result = await signDataItems(uploadDataList)\n arweaveTransactions = result.map((r) => ({\n transaction: { id: r.transaction.id },\n versionId: r.versionId,\n modelName: r.modelName,\n }))\n } else if (dataItemSigner) {\n const items: Awaited<ReturnType<typeof createSignedDataItem>>[] = []\n const timestampMs = Date.now()\n for (let i = 0; i < uploadDataList.length; i++) {\n const upload = uploadDataList[i]!\n const tags = upload.tags\n const randomUniq = new Uint8Array(8)\n crypto.getRandomValues(randomUniq)\n const uniqueness =\n (new DataView(randomUniq.buffer).getBigUint64(0, false) ^ BigInt(i)) &\n 0xffffffffffffffffn\n\n let dataItem: Awaited<ReturnType<typeof createSignedDataItem>>\n if (isEthersWallet(dataItemSigner)) {\n const rawAnchor = buildPublishAnchorBytes(dataItemSigner.address, timestampMs, uniqueness)\n dataItem = await createSignedDataItem(upload.data, dataItemSigner, tags, rawAnchor)\n } else {\n const seedSigner: SeedSigner = isPublishWallet(dataItemSigner)\n ? dataItemSigner.signer\n : dataItemSigner\n const rawAnchor = buildPublishAnchorBytes(seedSigner.address, timestampMs, uniqueness)\n dataItem = await createSignedDataItemWithAccount(\n upload.data,\n seedSigner,\n tags,\n rawAnchor,\n )\n }\n\n const isValid = await verifyDataItem(dataItem.raw)\n if (!isValid) {\n logger('DataItem verification failed: id=%s modelName=%s', dataItem.id, upload.itemPropertyName)\n throw new Error(\n `DataItem signature verification failed for ${upload.itemPropertyName}. ` +\n 'The signing key may not match the owner, or the payload may have been modified.'\n )\n }\n items.push(dataItem)\n }\n signedDataItems = items\n arweaveTransactions = items.map((dataItem, i) => ({\n transaction: { id: dataItem.id },\n versionId: uploadDataList[i]?.versionLocalId,\n modelName: uploadDataList[i]?.itemPropertyName,\n }))\n } else {\n throw new Error(\n '@seedprotocol/publish: useArweaveBundler requires signDataItems or dataItemSigner (pass at createPublish or in PublishProvider config)'\n )\n }\n\n const publishUploads: PublishUpload[] = uploadDataList.map((u) => ({\n itemPropertyName: u.itemPropertyName,\n itemPropertyLocalId: u.itemPropertyLocalId,\n seedLocalId: u.seedLocalId,\n versionLocalId: u.versionLocalId,\n transactionToSign: null,\n }))\n\n return {\n arweaveTransactions,\n publishUploads,\n signedDataItems,\n }\n}\n\n/**\n * Creates DataItems from raw upload data, signs them via signDataItems or dataItemSigner,\n * and returns arweaveTransactions for createAttestations compatibility.\n */\nexport const createArweaveDataItems = fromPromise(\n async ({ input: { context } }: PublishInput): Promise<CreateArweaveDataItemsResult> => {\n let { item } = context\n\n if (!item.getPublishUploads) {\n item = await waitForItem(item.seedLocalId)\n }\n\n const uploadDataOpts: GetPublishUploadDataOptions = {}\n if (context.arweaveUploadTags?.length) {\n uploadDataOpts.arweaveUploadTags = context.arweaveUploadTags\n }\n const def = context.htmlEmbeddedDeferredHtmlSeedLocalIds\n if (def?.length) {\n uploadDataOpts.deferHtmlStorageSeedLocalIds = def\n }\n const uploadDataList = await getPublishUploadData(\n item,\n [],\n undefined,\n Object.keys(uploadDataOpts).length ? uploadDataOpts : undefined,\n )\n const config = getPublishConfig()\n const signDataItems = context.signDataItems ?? config.signDataItems\n const dataItemSigner = context.dataItemSigner ?? config.dataItemSigner\n\n return signBundlerUploadDataList(uploadDataList, signDataItems, dataItemSigner)\n }\n)\n","import type { GetPublishUploadDataOptions } from '../helpers/getPublishUploadData'\nimport { fromPromise } from 'xstate'\nimport type { PublishMachineContext } from '../../../types'\nimport { waitForItem } from './utils'\nimport { getPublishUploadData } from '../helpers/getPublishUploadData'\nimport { getPublishConfig } from '~/config'\nimport { signBundlerUploadDataList, type CreateArweaveDataItemsResult } from './createArweaveDataItems'\n\ntype PublishInput = { input: { context: PublishMachineContext; event: unknown } }\n\n/**\n * Phase 2 (bundler): Html storage DataItems only, after embedded images uploaded and Html rewritten on disk.\n * Exported for unit tests; the XState actor wraps this.\n */\nexport async function executeCreateArweaveDataItemsPhase2(\n context: PublishMachineContext,\n): Promise<CreateArweaveDataItemsResult> {\n let { item } = context\n\n if (!item.getPublishUploads) {\n item = await waitForItem(item.seedLocalId)\n }\n\n const uploadDataOpts: GetPublishUploadDataOptions = {}\n if (context.arweaveUploadTags?.length) {\n uploadDataOpts.arweaveUploadTags = context.arweaveUploadTags\n }\n const def = context.htmlEmbeddedDeferredHtmlSeedLocalIds\n if (def?.length) {\n uploadDataOpts.onlyHtmlStorageSeedLocalIds = def\n // Walks relations: a related draft's deferred Html (embedded images) is uploaded here too.\n }\n const uploadDataList = await getPublishUploadData(\n item,\n [],\n undefined,\n Object.keys(uploadDataOpts).length ? uploadDataOpts : undefined,\n )\n\n const config = getPublishConfig()\n const signDataItems = context.signDataItems ?? config.signDataItems\n const dataItemSigner = context.dataItemSigner ?? config.dataItemSigner\n\n if (uploadDataList.length === 0) {\n return {\n arweaveTransactions: [],\n publishUploads: [],\n signedDataItems: undefined,\n }\n }\n\n return signBundlerUploadDataList(uploadDataList, signDataItems, dataItemSigner)\n}\n\nexport const createArweaveDataItemsPhase2 = fromPromise(\n async ({ input: { context } }: PublishInput): Promise<CreateArweaveDataItemsResult> =>\n executeCreateArweaveDataItemsPhase2(context),\n)\n","import type { IItem } from '@seedprotocol/sdk'\nimport type { ResolvedPublishPayment } from './payment'\nimport type { PublishCostEstimate, PublishMode } from './services/publishCost/types'\n\n/** What an {@link AuthorizePublish} hook is asked to approve. */\nexport interface PublishAuthorizationRequest {\n item: IItem<any>\n seedLocalId: string\n publishMode: PublishMode\n /** Who will pay gas and storage (see `resolvePublishPayment`). */\n payment: ResolvedPublishPayment\n /** Cost estimate for this publish. Fetches market prices, so call it only if you need it. */\n getEstimate: () => Promise<PublishCostEstimate>\n}\n\n/** An approval. `token` goes to the upload API with this publish's requests. */\nexport interface PublishAuthorization {\n /**\n * Sent as the {@link PUBLISH_AUTHORIZATION_HEADER} header on upload API requests (not to Turbo),\n * so an operator can meter or bill the publish against it.\n */\n token?: string\n}\n\n/**\n * Runs before a publish spends anything (before schema registration, uploads and attestations).\n * Return `false` or throw to refuse: the publish fails with {@link PublishNotAuthorizedError}.\n * Return `true`, nothing, or a {@link PublishAuthorization} to go ahead. A resumed publish that\n * already got past this step is not asked again.\n */\nexport type AuthorizePublish = (\n request: PublishAuthorizationRequest,\n) => PublishAuthorization | boolean | void | Promise<PublishAuthorization | boolean | void>\n\n/** Header carrying {@link PublishAuthorization.token} to the upload API. */\nexport const PUBLISH_AUTHORIZATION_HEADER = 'X-Seed-Publish-Authorization'\n\nexport class PublishNotAuthorizedError extends Error {\n constructor(seedLocalId: string, cause?: unknown) {\n const reason = cause instanceof Error ? `: ${cause.message}` : ''\n super(`@seedprotocol/publish: publish of ${seedLocalId} was not authorized${reason}`, { cause })\n this.name = 'PublishNotAuthorizedError'\n }\n}\n\n/**\n * Calls the hook and normalizes its answer. Without a hook every publish is approved.\n * @throws PublishNotAuthorizedError when the hook returns false or throws\n */\nexport async function runAuthorizePublish(\n hook: AuthorizePublish | undefined,\n request: PublishAuthorizationRequest,\n): Promise<PublishAuthorization> {\n if (!hook) return {}\n let answer: Awaited<ReturnType<AuthorizePublish>>\n try {\n answer = await hook(request)\n } catch (error) {\n throw new PublishNotAuthorizedError(request.seedLocalId, error)\n }\n if (answer === false) throw new PublishNotAuthorizedError(request.seedLocalId)\n if (answer && typeof answer === 'object') {\n return typeof answer.token === 'string' && answer.token.length > 0 ? { token: answer.token } : {}\n }\n return {}\n}\n\n/** Headers to add to upload API requests for a publish with this authorization. */\nexport function publishAuthorizationHeaders(authorization: PublishAuthorization | undefined): Record<string, string> {\n return authorization?.token ? { [PUBLISH_AUTHORIZATION_HEADER]: authorization.token } : {}\n}\n","/**\n * Serialized form part for IPC to main process (avoids CORS by proxying uploads).\n */\nexport type UploadFormPart = {\n name: string\n value: string\n encoding?: 'base64'\n filename?: string\n}\n\n/** Chunk size for base64 encoding; spreading large arrays blows the call stack. */\nconst BASE64_CHUNK_SIZE = 8192\n\nfunction arrayBufferToBase64(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer)\n let binary = ''\n for (let i = 0; i < bytes.length; i += BASE64_CHUNK_SIZE) {\n const chunk = bytes.subarray(i, Math.min(i + BASE64_CHUNK_SIZE, bytes.length))\n binary += String.fromCharCode.apply(null, chunk as unknown as number[])\n }\n return btoa(binary)\n}\n\n/**\n * Convert FormData to a serializable array for IPC. Blobs are base64-encoded.\n */\nexport async function formDataToSerializableParts(\n formData: FormData\n): Promise<UploadFormPart[]> {\n const parts: UploadFormPart[] = []\n for (const [name, value] of formData.entries()) {\n const entry = value as string | Blob\n if (typeof entry === 'object' && entry !== null && 'arrayBuffer' in entry) {\n const buf = await entry.arrayBuffer()\n const base64 = arrayBufferToBase64(buf)\n const file = entry as File\n parts.push({\n name,\n value: base64,\n encoding: 'base64',\n filename: file.name || undefined,\n })\n } else {\n parts.push({ name, value: String(value) })\n }\n }\n return parts\n}\n\n/** Result from upload POST (status 0 = network/proxy error). */\nexport type PostUploadResult = {\n status: number\n body: unknown\n error?: string\n message?: string\n}\n\n/** Build a user-facing message when the upload API returns a non-2xx status. */\nexport function uploadServerErrorMessage(\n status: number,\n body: unknown,\n transactionKeys?: string | null\n): string {\n const parts: string[] = ['Upload server returned ', String(status)]\n const msg =\n body && typeof body === 'object' && 'message' in body\n ? String((body as { message: unknown }).message)\n : body && typeof body === 'object' && 'error' in body\n ? String((body as { error: unknown }).error)\n : null\n if (msg) parts.push(`: ${msg}`)\n else if (transactionKeys) parts.push(` (${transactionKeys})`)\n return parts.join('')\n}\n\n/** Map technical network error messages to a short, user-facing message. */\nexport function uploadNetworkErrorMessage(technicalMessage?: string | null): string {\n if (!technicalMessage) {\n return 'Upload server unavailable. Please try again or check your connection.'\n }\n const t = technicalMessage.toLowerCase()\n if (/other side closed|econnreset|socket hang up|connection closed/i.test(t)) {\n return 'Upload server closed the connection. It may be busy or the request may be too large—try again.'\n }\n if (/etimedout|timeout/i.test(t)) {\n return 'Upload request timed out. Please try again.'\n }\n if (/enotfound|getaddrinfo|dns/i.test(t)) {\n return 'Upload server could not be reached. Check the upload URL and your network.'\n }\n return 'Upload failed. Please try again or check the upload server.'\n}\n\n/**\n * POST to the upload API. Uses main-process proxy in Electron to avoid CORS;\n * falls back to fetch when not in Electron (e.g. browser tests).\n */\nexport async function postUploadArweaveStart(\n url: string,\n formData: FormData,\n uploadApiBaseUrl: string,\n /** Extra request headers, e.g. the publish authorization token. */\n headers: Record<string, string> = {},\n): Promise<PostUploadResult> {\n const api = typeof window !== 'undefined' ? (window as Window & { Main?: { uploadArweaveStart?: (url: string, parts: UploadFormPart[], headers?: Record<string, string>) => Promise<PostUploadResult> } }).Main : undefined\n if (api?.uploadArweaveStart) {\n const parts = await formDataToSerializableParts(formData)\n // Older Electron proxies take two arguments and drop the headers.\n return api.uploadArweaveStart(url, parts, headers)\n }\n const res = await fetch(url, {\n method: 'POST',\n headers,\n body: formData,\n })\n const body = await res.json().catch(() => ({}))\n return { status: res.status, body }\n}\n\n/**\n * POST to Arweave bundler for instant uploads. Same FormData format as upload API.\n * Uses main-process proxy in Electron to avoid CORS.\n */\nexport async function postUploadBundler(\n url: string,\n formData: FormData\n): Promise<PostUploadResult> {\n const api = typeof window !== 'undefined' ? (window as Window & { Main?: { uploadArweaveStart?: (url: string, parts: UploadFormPart[]) => Promise<PostUploadResult> } }).Main : undefined\n if (api?.uploadArweaveStart) {\n const parts = await formDataToSerializableParts(formData)\n return api.uploadArweaveStart(url, parts)\n }\n const res = await fetch(url, {\n method: 'POST',\n body: formData,\n })\n const body = await res.json().catch(() => ({}))\n return { status: res.status, body }\n}\n","import { publishAuthorizationHeaders } from '~/authorization'\nimport { fromPromise } from 'xstate'\nimport type { PublishMachineContext } from '../../../types'\nimport type { ArweaveTransactionInfo } from '../../../types'\nimport type { ReimbursementResponse } from '../../../types'\nimport { getPublishConfig } from '~/config'\nimport {\n postUploadArweaveStart,\n uploadNetworkErrorMessage,\n uploadServerErrorMessage,\n} from '~/helpers/uploadApi'\n\ntype PublishInput = { input: { context: PublishMachineContext; event: unknown } }\n\nexport const sendReimbursementRequest = fromPromise(\n async ({ input: { context, event } }: PublishInput): Promise<ReimbursementResponse> => {\n const { arweaveTransactions = [], transactionKeys, reimbursementTransactionId } = context\n\n if (reimbursementTransactionId) {\n return {\n transactionId: reimbursementTransactionId,\n }\n }\n\n const transactions = arweaveTransactions.map(({ transaction }: ArweaveTransactionInfo) => transaction)\n\n const formData = new FormData()\n\n type ArweaveTx = { id: string; data?: unknown; chunks?: unknown; [key: string]: unknown }\n for (const transaction of transactions as ArweaveTx[]) {\n let { data, chunks, ...json } = transaction\n const dataBlob = data instanceof Blob ? data : new Blob([data as BlobPart])\n formData.append(`${transaction.id}-data`, dataBlob, `${transaction.id}-data`)\n const chunksBlob = new Blob([JSON.stringify(chunks)], { type: 'application/json' })\n formData.append(`${transaction.id}-chunks`, chunksBlob, `${transaction.id}-chunks`)\n const jsonBlob = new Blob([JSON.stringify(json)], { type: 'application/json' })\n formData.append(`${transaction.id}-json`, jsonBlob, `${transaction.id}-json`)\n }\n\n const { uploadApiBaseUrl } = getPublishConfig()\n const url = `${uploadApiBaseUrl}/api/upload/arweave/start`\n const { status, body, message: serverMessage } = await postUploadArweaveStart(\n url,\n formData,\n uploadApiBaseUrl,\n publishAuthorizationHeaders(context.publishAuthorization),\n )\n\n if (status >= 300 || status < 200) {\n const technicalMsg = status === 0 ? serverMessage : null\n if (technicalMsg) console.error('[upload]', technicalMsg)\n const errMsg =\n status === 0\n ? uploadNetworkErrorMessage(technicalMsg as string | undefined)\n : uploadServerErrorMessage(status, body, transactionKeys)\n throw new Error(errMsg)\n }\n\n return body as ReimbursementResponse\n }\n)\n","import { fromPromise } from 'xstate'\nimport type { PublishMachineContext } from '../../../types'\nimport { getArweave } from '~/helpers/blockchain'\n\ntype PublishInput = { input: { context: PublishMachineContext; event: unknown } }\n\nexport const pollForConfirmation = fromPromise(async ({ input: { context, event } }: PublishInput): Promise<void> => {\n const { requestResponse, reimbursementTransactionId } = context\n\n if (!requestResponse) {\n throw new Error('No request response')\n }\n\n if (!reimbursementTransactionId) {\n throw new Error('No reimbursement transaction id')\n }\n\n const arweave = getArweave()\n\n const _pollForConfirmation = new Promise<void>((resolve, reject) => {\n const interval = setInterval(async () => {\n let response\n try {\n response = await arweave.transactions.getStatus(reimbursementTransactionId)\n } catch (error) {\n return\n }\n if (response && response.confirmed) {\n clearInterval(interval)\n resolve()\n }\n }, 5000)\n })\n\n await _pollForConfirmation\n})\n","import { EventObject, fromCallback } from 'xstate'\nimport type { PublishMachineContext } from '../../../types'\nimport type { ArweaveTransactionInfo } from '../../../types'\nimport { getArweave } from '~/helpers/blockchain'\nimport debug from 'debug'\n\nconst logger = debug('seedProtocol:services:publish:actors')\n\nfunction ensureUint8Array(data: unknown): Uint8Array {\n if (data instanceof Uint8Array) return data\n if (data instanceof ArrayBuffer) return new Uint8Array(data)\n throw new Error('Transaction data must be Uint8Array or ArrayBuffer for upload resume')\n}\n\nexport const uploadData = fromCallback<EventObject, { context: PublishMachineContext }>(\n ({ sendBack, input }) => {\n const ctx = input.context\n const arweaveTransactions = ctx.arweaveTransactions ?? []\n const transactions = arweaveTransactions.map(({ transaction }: ArweaveTransactionInfo) => transaction)\n const arweave = getArweave()\n\n const resumeState = ctx.uploaderState && typeof ctx.currentTransactionIndex === 'number'\n const startIndex = resumeState ? ctx.currentTransactionIndex! : 0\n\n const processTransactions = async (): Promise<string> => {\n const total = transactions.length\n for (let i = startIndex; i < total; i++) {\n const rawTransaction = transactions[i]\n if (!rawTransaction) continue\n const transaction = arweave.transactions.fromRaw(rawTransaction as object)\n\n const verified = await arweave.transactions.verify(transaction)\n if (!verified) {\n throw new Error('Transaction verification failed')\n }\n\n let uploader: Awaited<ReturnType<typeof arweave.transactions.getUploader>>\n const uploaderState = ctx.uploaderState\n if (resumeState && i === startIndex && uploaderState) {\n const data = transaction.data\n const dataBytes = data instanceof Uint8Array ? data : ensureUint8Array(data)\n uploader = await arweave.transactions.getUploader(uploaderState as unknown as Parameters<typeof arweave.transactions.getUploader>[0], dataBytes)\n } else {\n uploader = await arweave.transactions.getUploader(transaction, transaction.data)\n }\n\n while (!uploader.isComplete) {\n logger('uploading chunk')\n logger(`uploader.pctComplete: ${uploader.pctComplete}`)\n logger(`uploader.uploadedChunks: ${uploader.uploadedChunks}`)\n logger(`uploader.totalChunks: ${uploader.totalChunks}`)\n logger(uploader.lastResponseError)\n logger(uploader.lastResponseStatus)\n try {\n await uploader.uploadChunk()\n const pct = Math.trunc(((i + uploader.pctComplete / 100) / total) * 100)\n sendBack({\n type: 'updatePercentage',\n completionPercentage: pct,\n uploaderState: uploader.toJSON(),\n currentTransactionIndex: i,\n })\n logger(`${uploader.pctComplete}% complete, ${uploader.uploadedChunks}/${uploader.totalChunks}`)\n } catch (error) {\n logger(error)\n }\n }\n }\n\n return 'done'\n }\n\n processTransactions()\n .then((result) => {\n sendBack({ type: 'uploadComplete', result })\n })\n .catch((error) => {\n sendBack({ type: 'uploadError', error })\n })\n }\n)\n","/**\n * Minimal Turbo (ArDrive) client for user-paid storage: balances, prices, and uploads of data\n * items the user's EVM key already signed. Raw HTTP rather than @ardrive/turbo-sdk, which would\n * bring its own signers and a large dependency tree for four calls.\n */\n\nimport { computeAddress } from 'ethers'\n\nexport type TurboEndpoints = { uploadUrl: string; paymentUrl: string }\n\n/** Turbo credits are denominated in winc (winston credits), like AR winston. */\nexport class InsufficientStorageCreditsError extends Error {\n readonly address: string\n readonly requiredWinc: bigint | undefined\n readonly balanceWinc: bigint | undefined\n\n constructor(params: { address: string; requiredWinc?: bigint; balanceWinc?: bigint; detail?: string }) {\n const amounts =\n params.requiredWinc !== undefined && params.balanceWinc !== undefined\n ? ` (needs ${params.requiredWinc} winc, has ${params.balanceWinc})`\n : ''\n super(\n `@seedprotocol/publish: ${params.address} does not have enough Turbo credits to store this publish${amounts}. ` +\n `Top up that address with Turbo credits (card or crypto through ArDrive Turbo), then publish again.` +\n (params.detail ? ` ${params.detail}` : ''),\n )\n this.name = 'InsufficientStorageCreditsError'\n this.address = params.address\n this.requiredWinc = params.requiredWinc\n this.balanceWinc = params.balanceWinc\n }\n}\n\nasync function getJson(url: string): Promise<{ status: number; body: any }> {\n const res = await fetch(url)\n const text = await res.text()\n let body: any = text\n try {\n body = JSON.parse(text)\n } catch {\n // Turbo answers some 404s in plain text (\"User Not Found\", \"TX doesn't exist\")\n }\n return { status: res.status, body }\n}\n\n/** Spendable winc for an EVM address. An address Turbo has never seen has 0. */\nexport async function getTurboBalanceWinc(endpoints: TurboEndpoints, address: string): Promise<bigint> {\n const { status, body } = await getJson(\n `${endpoints.paymentUrl}/v1/account/balance/ethereum?address=${encodeURIComponent(address)}`,\n )\n if (status === 404) return 0n\n if (status !== 200) throw new Error(`Turbo balance lookup failed: HTTP ${status}`)\n return BigInt(body?.effectiveBalance ?? body?.winc ?? '0')\n}\n\n/** winc Turbo charges to store `bytes`. */\nexport async function getTurboPriceWinc(endpoints: TurboEndpoints, bytes: number): Promise<bigint> {\n const { status, body } = await getJson(`${endpoints.paymentUrl}/v1/price/bytes/${bytes}`)\n if (status !== 200) throw new Error(`Turbo price lookup failed: HTTP ${status}`)\n return BigInt(body?.winc ?? '0')\n}\n\n/** Largest data item Turbo stores for free, from `GET /v1/info` (0 when it doesn't say). */\nexport async function getTurboFreeUploadLimitBytes(endpoints: TurboEndpoints): Promise<number> {\n try {\n const { status, body } = await getJson(`${endpoints.uploadUrl}/v1/info`)\n if (status !== 200) return 0\n return Number(body?.freeUploadLimitBytes ?? body?.freeTier?.maxItemBytes ?? 0) || 0\n } catch {\n return 0\n }\n}\n\nexport type TurboUploadReceipt = { id: string; owner?: string; winc?: string }\n\n/**\n * POSTs one signed (signature type 3, Ethereum) data item. Turbo charges the signer, or first the\n * `paidBy` addresses' shared credits.\n * @throws InsufficientStorageCreditsError on HTTP 402\n */\nexport async function uploadDataItemToTurbo(\n endpoints: TurboEndpoints,\n raw: Uint8Array,\n options: { signerAddress: string; paidBy?: string[] },\n): Promise<TurboUploadReceipt> {\n const headers: Record<string, string> = { 'Content-Type': 'application/octet-stream' }\n if (options.paidBy && options.paidBy.length > 0) headers['x-paid-by'] = options.paidBy.join(',')\n const res = await fetch(`${endpoints.uploadUrl}/v1/tx/ethereum`, { method: 'POST', headers, body: raw as BodyInit })\n const text = await res.text()\n if (res.status === 402) {\n throw new InsufficientStorageCreditsError({ address: options.signerAddress, detail: text.slice(0, 200) })\n }\n if (res.status !== 200 && res.status !== 202) {\n throw new Error(`Turbo upload failed: HTTP ${res.status} ${text.slice(0, 200)}`)\n }\n return JSON.parse(text) as TurboUploadReceipt\n}\n\n/** HTTP status of `GET /v1/tx/:id/status`: 200 when Turbo has the item, 404 when it doesn't. */\nexport async function getTurboDataItemStatus(endpoints: TurboEndpoints, id: string): Promise<number> {\n const res = await fetch(`${endpoints.uploadUrl}/v1/tx/${encodeURIComponent(id)}/status`)\n await res.body?.cancel().catch(() => {})\n return res.status\n}\n\n/**\n * Throws {@link InsufficientStorageCreditsError} when `address` can't pay for `itemSizes`, before\n * anything is uploaded. Items at or under Turbo's free size cost nothing. Shared credits\n * (`paidBy`) aren't counted, so callers skip this check when `paidBy` is set.\n */\nexport async function assertTurboCanPay(\n endpoints: TurboEndpoints,\n address: string,\n itemSizes: number[],\n): Promise<void> {\n const freeLimit = await getTurboFreeUploadLimitBytes(endpoints)\n const paid = itemSizes.filter((size) => size > freeLimit)\n if (paid.length === 0) return\n const prices = await Promise.all(paid.map((size) => getTurboPriceWinc(endpoints, size)))\n const required = prices.reduce((sum, p) => sum + p, 0n)\n const balance = await getTurboBalanceWinc(endpoints, address)\n if (balance < required) {\n throw new InsufficientStorageCreditsError({ address, requiredWinc: required, balanceWinc: balance })\n }\n}\n\n/**\n * EVM address that signed an ANS-104 data item with signature type 3 (Ethereum): the owner\n * field is the uncompressed secp256k1 public key. Returns undefined for other signature types.\n */\nexport function ethereumSignerOfDataItem(raw: Uint8Array): string | undefined {\n if (raw.length < 2 + 65 + 65) return undefined\n const sigType = raw[0]! | (raw[1]! << 8)\n if (sigType !== 3) return undefined\n const owner = raw.subarray(2 + 65, 2 + 65 + 65)\n return computeAddress('0x' + Buffer.from(owner).toString('hex'))\n}\n","import type { PublishMachineContext } from '../../../types'\nimport type { ResolvedPublishPayment } from '~/payment'\nimport { assertTurboCanPay, ethereumSignerOfDataItem, uploadDataItemToTurbo } from '~/helpers/turbo'\n\n// Kept out of the uploadViaBundler actor module so it can be imported (and tested) without\n// pulling in ~/config, which imports the publish machine.\n\ntype DataItemLike = {\n raw?: Uint8Array\n filename?: string\n getRaw?: () => Buffer | Promise<Buffer>\n}\n\nconst importDynamic = new Function('s', 'return import(s)') as (specifier: string) => Promise<{\n readFile: (path: string) => Promise<Buffer>\n}>\n\nasync function readNodeFile(filename: string): Promise<Buffer> {\n if (typeof window !== 'undefined') {\n throw new Error('DataItem.filename requires Node.js fs access. In browser runtime, provide DataItem.raw or DataItem.getRaw().')\n }\n const { readFile } = await importDynamic(`node:${['fs', 'promises'].join('/')}`)\n return readFile(filename)\n}\n\n/** Raw bytes of one signed DataItem (raw, getRaw() or a Node file). */\nasync function rawBytesOf(item: unknown): Promise<Buffer> {\n const o = item as DataItemLike\n if (o.raw != null && (o.raw instanceof Uint8Array || Buffer.isBuffer(o.raw))) {\n return Buffer.isBuffer(o.raw) ? o.raw : Buffer.from(o.raw)\n }\n if (typeof o.getRaw === 'function') {\n const resolved = await o.getRaw()\n return Buffer.isBuffer(resolved) ? resolved : Buffer.from(resolved)\n }\n if (o.filename != null) return readNodeFile(o.filename)\n throw new Error('Cannot get raw bytes from DataItem')\n}\n\n/**\n * User-paid storage (`payment.storage: 'user'`): checks the signer's Turbo credits cover the\n * items, then POSTs each to Turbo, which charges the signer (or `paidBy`).\n */\nexport async function uploadToTurbo(\n items: unknown[],\n turbo: NonNullable<ResolvedPublishPayment['storage']['turbo']>,\n context: PublishMachineContext,\n): Promise<void> {\n const raws = await Promise.all(items.map(rawBytesOf))\n const signerAddress =\n (context.dataItemSigner as { address?: string } | undefined)?.address ??\n (raws[0] ? ethereumSignerOfDataItem(raws[0]) : undefined)\n if (!signerAddress) {\n throw new Error('User-paid storage needs Ethereum-signed data items (dataItemSigner).')\n }\n if (turbo.paidBy.length === 0) {\n await assertTurboCanPay(turbo, signerAddress, raws.map((r) => r.byteLength))\n }\n for (const raw of raws) {\n await uploadDataItemToTurbo(turbo, raw, { signerAddress, paidBy: turbo.paidBy })\n }\n}\n","import { EventObject, fromCallback } from 'xstate'\nimport type { PublishMachineContext } from '../../../types'\nimport { getPublishConfig } from '~/config'\nimport { resolvePublishPayment } from '~/payment'\nimport { uploadToTurbo } from '../helpers/uploadToTurbo'\nimport { publishAuthorizationHeaders } from '~/authorization'\n\nconst BATCH_UPLOAD_TIMEOUT_MS = 120_000\nconst importDynamic = new Function('s', 'return import(s)') as (specifier: string) => Promise<{\n readFile: (path: string) => Promise<Buffer>\n stat: (path: string) => Promise<{ size: number }>\n}>\n\ntype DataItemLike = {\n raw?: Uint8Array\n filename?: string\n getRaw?: () => Buffer | Promise<Buffer>\n}\n\nlet nodeFsPromisesCache: { readFile: (path: string) => Promise<Buffer>; stat: (path: string) => Promise<{ size: number }> } | null = null\n\nconst getNodeFsPromises = async () => {\n if (nodeFsPromisesCache) return nodeFsPromisesCache\n if (typeof window !== 'undefined') return null\n\n try {\n const specifier = `node:${['fs', 'promises'].join('/')}`\n const mod = await importDynamic(specifier)\n nodeFsPromisesCache = {\n readFile: mod.readFile,\n stat: mod.stat,\n }\n return nodeFsPromisesCache\n } catch {\n return null\n }\n}\n\n/**\n * Bundler batch upload reads from context.signedDataItems (dataItemSigner path only).\n * arweaveTransactions / publishUploads hold ids and metadata for later attestations.\n * When signDataItems is used, the callback handles upload (e.g. ArConnect) so signedDataItems\n * is undefined — we skip the upload step and send uploadComplete immediately.\n */\nexport const uploadViaBundler = fromCallback<EventObject, { context: PublishMachineContext }>(\n ({ sendBack, input: { context } }) => {\n const { signedDataItems } = context\n\n const config = getPublishConfig()\n const { uploadApiBaseUrl, useArweaveBundler } = config\n const { storage } = resolvePublishPayment(config)\n\n if (storage.uploadTo === 'turbo' && storage.turbo) {\n if (!signedDataItems || signedDataItems.length === 0) {\n sendBack({ type: 'uploadComplete', result: 'done' })\n return\n }\n uploadToTurbo(signedDataItems as unknown[], storage.turbo, context)\n .then(() => sendBack({ type: 'uploadComplete', result: 'done' }))\n .catch((error) => sendBack({ type: 'uploadError', error }))\n return\n }\n\n if (!useArweaveBundler || !uploadApiBaseUrl) {\n sendBack({\n type: 'uploadError',\n error: new Error(\n 'Arweave bundler not configured. Set useArweaveBundler and uploadApiBaseUrl.'\n ),\n })\n return\n }\n\n const bundlerUrl = `${uploadApiBaseUrl.replace(/\\/$/, '')}/api/upload/arweave/batch`\n\n if (!signedDataItems || signedDataItems.length === 0) {\n // signDataItems path: external signer (e.g. ArConnect) already uploaded; skip and proceed\n sendBack({ type: 'uploadComplete', result: 'done' })\n return\n }\n\n const _uploadViaBundler = async () => {\n const items = signedDataItems as unknown[]\n const itemCount = items.length\n const getRawCache: (Buffer | null)[] = new Array(itemCount).fill(null)\n\n /** Length only (pass 1). Caches buffer for getRaw() items to avoid a second read. */\n const rawByteLength = async (item: unknown, i: number): Promise<number> => {\n const o = item as DataItemLike\n if (o.raw != null && (o.raw instanceof Uint8Array || Buffer.isBuffer(o.raw))) {\n return o.raw.byteLength\n }\n if (typeof o.getRaw === 'function') {\n const r = o.getRaw()\n const resolved = r instanceof Promise ? await r : r\n const buf = Buffer.isBuffer(resolved) ? resolved : Buffer.from(resolved)\n getRawCache[i] = buf\n return buf.length\n }\n if (o.filename != null) {\n const nodeFsPromises = await getNodeFsPromises()\n if (!nodeFsPromises) {\n throw new Error(\n 'DataItem.filename requires Node.js fs access. In browser runtime, provide DataItem.raw or DataItem.getRaw().'\n )\n }\n const st = await nodeFsPromises.stat(o.filename)\n return st.size\n }\n throw new Error('Cannot get raw bytes from DataItem')\n }\n\n let totalSize = 4\n const lengths: number[] = []\n for (let i = 0; i < itemCount; i++) {\n const len = await rawByteLength(items[i], i)\n lengths.push(len)\n totalSize += 4 + len\n }\n\n const payload = Buffer.alloc(totalSize)\n let offset = 0\n payload.writeUInt32BE(itemCount, offset)\n offset += 4\n\n for (let i = 0; i < itemCount; i++) {\n const len = lengths[i]!\n const cached = getRawCache[i]\n if (cached) {\n payload.writeUInt32BE(len, offset)\n offset += 4\n cached.copy(payload, offset)\n offset += len\n continue\n }\n\n const o = items[i] as DataItemLike\n if (o.raw != null && (o.raw instanceof Uint8Array || Buffer.isBuffer(o.raw))) {\n payload.writeUInt32BE(len, offset)\n offset += 4\n payload.set(o.raw, offset)\n offset += len\n continue\n }\n if (o.filename != null) {\n const nodeFsPromises = await getNodeFsPromises()\n if (!nodeFsPromises) {\n throw new Error(\n 'DataItem.filename requires Node.js fs access. In browser runtime, provide DataItem.raw or DataItem.getRaw().'\n )\n }\n const buf = await nodeFsPromises.readFile(o.filename)\n payload.writeUInt32BE(buf.length, offset)\n offset += 4\n buf.copy(payload, offset)\n offset += buf.length\n continue\n }\n throw new Error('Cannot get raw bytes from DataItem')\n }\n\n const controller = new AbortController()\n const uploadTimeoutId = setTimeout(() => controller.abort(), BATCH_UPLOAD_TIMEOUT_MS)\n\n let response: Response\n try {\n response = await fetch(bundlerUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/octet-stream',\n ...publishAuthorizationHeaders(context.publishAuthorization),\n },\n body: payload,\n signal: controller.signal,\n })\n } catch (err) {\n clearTimeout(uploadTimeoutId)\n if (err instanceof Error && err.name === 'AbortError') {\n throw new Error(\n `Arweave batch upload timed out after ${BATCH_UPLOAD_TIMEOUT_MS / 1000}s (upload API did not respond). Check uploadApiBaseUrl and network.`,\n )\n }\n throw err\n }\n clearTimeout(uploadTimeoutId)\n\n if (!response.ok) {\n throw new Error(`Batch upload failed: ${response.status}`)\n }\n\n const body = (await response.json().catch(() => ({}))) as { failed?: number; total?: number; succeeded?: number }\n const failed = typeof body.failed === 'number' ? body.failed : 0\n if (failed > 0) {\n const total = body.total ?? '?'\n const succeeded = body.succeeded ?? 0\n throw new Error(\n `Arweave batch upload failed: ${failed} of ${total} item(s) failed (${succeeded} succeeded)`\n )\n }\n }\n\n _uploadViaBundler()\n .then(() => sendBack({ type: 'uploadComplete', result: 'done' }))\n .catch((error) => sendBack({ type: 'uploadError', error }))\n }\n)\n","import { getBlockTimestampMs } from '~/helpers/chainClient'\n\n/**\n * Block time in milliseconds for the receipt's block, or `Date.now()` if unavailable.\n */\nexport async function attestationMsFromReceipt(\n receipt: { blockNumber?: bigint },\n): Promise<number> {\n const bn = receipt?.blockNumber\n if (bn == null) return Date.now()\n const ms = await getBlockTimestampMs(bn)\n return ms ?? Date.now()\n}\n","import { parseEventLogs, decodeAbiParameters, type Log } from 'viem'\nimport { publisherEventsAbi } from '~/helpers/abi/publisher'\nimport { executorEventsAbi } from '~/helpers/abi/executor'\nimport { getAttestedUidsFromReceipt } from '~/helpers/easDirect'\nimport { ZERO_BYTES32 } from './utils'\n\nexport function toHex32Normalized(v: string | undefined): string {\n if (v == null || v === '') return ZERO_BYTES32\n const raw = v.startsWith('0x') ? v.slice(2) : v\n const hex = raw.replace(/[^0-9a-fA-F]/g, '0').padStart(64, '0').slice(-64)\n return ('0x' + hex).toLowerCase()\n}\n\n/**\n * Extract the seed attestation UID by matching the request's seedSchemaUid to a CreatedAttestation\n * event.\n */\nexport function seedUidFromCreatedAttestationEvents(\n receipt: { logs?: Array<{ address?: string; data?: string; topics?: unknown[] }> },\n seedSchemaUid: string | undefined,\n useModularExecutor: boolean,\n): string | undefined {\n if (!seedSchemaUid || !receipt.logs?.length) return undefined\n const wantSchema = toHex32Normalized(seedSchemaUid)\n if (wantSchema === ZERO_BYTES32) return undefined\n const abi = useModularExecutor ? executorEventsAbi : publisherEventsAbi\n try {\n const parsed = parseEventLogs({\n abi,\n eventName: 'CreatedAttestation',\n logs: receipt.logs as Log[],\n strict: false,\n })\n for (const ev of parsed) {\n const result = ev.args?.result as { schemaUid?: string; attestationUid?: string } | undefined\n if (!result?.attestationUid) continue\n if (toHex32Normalized(result.schemaUid) === wantSchema) {\n const uid = result.attestationUid\n if (uid && toHex32Normalized(uid) !== ZERO_BYTES32) return uid\n return undefined\n }\n }\n } catch {\n // ignore\n }\n return undefined\n}\n\nexport type SeedPublishedPair = {\n seedUid?: string\n versionUid?: string\n}\n\n/**\n * Seed + Version UIDs from SeedPublished (executor: typed args; extension: bytes32[] layout).\n */\nexport function uidsFromSeedPublished(\n receipt: { logs?: Array<{ address?: string; data?: string; topics?: unknown[] }> },\n contractAddress: string,\n listOfAttestationsCount: number,\n useModularExecutor: boolean,\n): SeedPublishedPair {\n const want = contractAddress.toLowerCase()\n const logs = receipt.logs?.filter((l) => l.address && l.address.toLowerCase() === want)\n if (!logs?.length) return {}\n try {\n if (useModularExecutor) {\n const parsed = parseEventLogs({\n abi: executorEventsAbi,\n eventName: 'SeedPublished',\n logs: logs as Log[],\n strict: false,\n })\n const first = parsed[0]\n if (!first) return {}\n const args = first.args as { seedUid?: string; versionUid?: string }\n const seedUid =\n args?.seedUid && toHex32Normalized(args.seedUid) !== ZERO_BYTES32 ? args.seedUid : undefined\n const versionUid =\n args?.versionUid && toHex32Normalized(args.versionUid) !== ZERO_BYTES32\n ? args.versionUid\n : undefined\n return { seedUid, versionUid }\n }\n const parsed = parseEventLogs({\n abi: publisherEventsAbi,\n eventName: 'SeedPublished',\n logs: logs as Log[],\n strict: false,\n })\n const first = parsed[0]\n if (!first) return {}\n const args = first.args as { returnedDataFromEAS?: `0x${string}` }\n const data = args?.returnedDataFromEAS\n if (!data || data === '0x') return {}\n const decoded = decodeAbiParameters([{ type: 'bytes32[]' }], data)\n const uids = decoded[0] as readonly `0x${string}`[]\n if (!uids?.length) return {}\n const seedIndex = listOfAttestationsCount\n const atSeed = uids[seedIndex]\n const atVersion = uids[seedIndex + 1]\n const seedUid =\n atSeed && atSeed !== ZERO_BYTES32\n ? (atSeed as string)\n : uids.length === 1 && uids[0] && uids[0] !== ZERO_BYTES32\n ? (uids[0] as string)\n : undefined\n const versionUid =\n atVersion && atVersion !== ZERO_BYTES32 ? (atVersion as string) : undefined\n return { seedUid, versionUid }\n } catch {\n return {}\n }\n}\n\nexport function seedUidFromSeedPublished(\n receipt: { logs?: Array<{ address?: string; data?: string; topics?: unknown[] }> },\n contractAddress: string,\n listOfAttestationsCount: number,\n useModularExecutor: boolean,\n): string | undefined {\n return uidsFromSeedPublished(\n receipt,\n contractAddress,\n listOfAttestationsCount,\n useModularExecutor,\n ).seedUid\n}\n\nexport function versionUidFromCreatedAttestationEvents(\n receipt: { logs?: Array<{ address?: string; data?: string; topics?: unknown[] }> },\n versionSchemaUid: string | undefined,\n useModularExecutor: boolean,\n): string | undefined {\n if (!versionSchemaUid || !receipt.logs?.length) return undefined\n const wantSchema = toHex32Normalized(versionSchemaUid)\n if (wantSchema === ZERO_BYTES32) return undefined\n const abi = useModularExecutor ? executorEventsAbi : publisherEventsAbi\n try {\n const parsed = parseEventLogs({\n abi,\n eventName: 'CreatedAttestation',\n logs: receipt.logs as Log[],\n strict: false,\n })\n for (const ev of parsed) {\n const result = ev.args?.result as { schemaUid?: string; attestationUid?: string } | undefined\n if (!result?.attestationUid) continue\n if (toHex32Normalized(result.schemaUid) === wantSchema) {\n const uid = result.attestationUid\n if (uid && toHex32Normalized(uid) !== ZERO_BYTES32) return uid\n return undefined\n }\n }\n } catch {\n // ignore\n }\n return undefined\n}\n\nexport type CreatedAttestationPair = { schemaUid: string; attestationUid: string }\n\nexport function listCreatedAttestationPairsFromReceipt(\n receipt: { logs?: Array<{ address?: string; data?: string; topics?: unknown[] }> },\n useModularExecutor: boolean,\n): CreatedAttestationPair[] {\n if (!receipt.logs?.length) return []\n const abi = useModularExecutor ? executorEventsAbi : publisherEventsAbi\n try {\n const parsed = parseEventLogs({\n abi,\n eventName: 'CreatedAttestation',\n logs: receipt.logs as Log[],\n strict: false,\n })\n const out: CreatedAttestationPair[] = []\n for (const ev of parsed) {\n const result = ev.args?.result as\n | { schemaUid?: string; attestationUid?: string }\n | undefined\n if (!result?.attestationUid) continue\n const uid = result.attestationUid\n if (!uid || toHex32Normalized(uid) === ZERO_BYTES32) continue\n const su = result.schemaUid\n if (!su) continue\n out.push({ schemaUid: su, attestationUid: uid })\n }\n return out\n } catch {\n return []\n }\n}\n\nfunction nonModularSeedPublishedUids(\n receipt: { logs?: Array<{ address?: string; data?: string; topics?: unknown[] }> },\n contractAddress: string,\n): readonly `0x${string}`[] {\n const want = contractAddress.toLowerCase()\n const logs = receipt.logs?.filter((l) => l.address && l.address.toLowerCase() === want)\n if (!logs?.length) return []\n try {\n const parsed = parseEventLogs({\n abi: publisherEventsAbi,\n eventName: 'SeedPublished',\n logs: logs as Log[],\n strict: false,\n })\n const first = parsed[0]\n if (!first) return []\n const args = first.args as { returnedDataFromEAS?: `0x${string}` }\n const data = args?.returnedDataFromEAS\n if (!data || data === '0x') return []\n const decoded = decodeAbiParameters([{ type: 'bytes32[]' }], data)\n return (decoded[0] as readonly `0x${string}`[]) ?? []\n } catch {\n return []\n }\n}\n\nfunction propertyPairsFromNonModularSeedPublished(\n receipt: { logs?: Array<{ address?: string; data?: string; topics?: unknown[] }> },\n contractAddress: string,\n listOfAttestations: Array<{ schema?: string }>,\n): CreatedAttestationPair[] {\n if (!listOfAttestations.length) return []\n const uids = nonModularSeedPublishedUids(receipt, contractAddress)\n const n = listOfAttestations.length\n if (uids.length < n) return []\n const out: CreatedAttestationPair[] = []\n for (let i = 0; i < n; i++) {\n const uid = uids[i]\n const schemaUid = listOfAttestations[i]?.schema\n if (!uid || toHex32Normalized(uid) === ZERO_BYTES32 || !schemaUid) continue\n out.push({ schemaUid, attestationUid: uid })\n }\n return out\n}\n\nexport type ListPropertyAttestationPairsParams = {\n receipt: { logs?: Array<{ address?: string; data?: string; topics?: unknown[] }> }\n useModularExecutor: boolean\n easContractAddress: string\n contractAddressForEvents: string\n /** Used to zip non-modular SeedPublished property UIDs (indices 0..n-1) with schemas. */\n listOfAttestations?: Array<{ schema?: string }>\n}\n\n/**\n * Property (and seed/version) attestation pairs from a multiPublish receipt.\n * Order: CreatedAttestation, then EAS Attested, then non-modular SeedPublished bytes32[0..n-1].\n * Modular SeedPublished is seed+version only and is not a property source.\n */\nexport function listPropertyAttestationPairsFromReceipt(\n params: ListPropertyAttestationPairsParams,\n): CreatedAttestationPair[] {\n const created = listCreatedAttestationPairsFromReceipt(\n params.receipt,\n params.useModularExecutor,\n )\n if (created.length) return created\n\n const attested = getAttestedUidsFromReceipt(params.receipt, params.easContractAddress)\n if (attested.length) {\n return attested.map((a) => ({\n schemaUid: a.schemaUid,\n attestationUid: a.uid,\n }))\n }\n\n if (params.useModularExecutor) return []\n\n return propertyPairsFromNonModularSeedPublished(\n params.receipt,\n params.contractAddressForEvents,\n params.listOfAttestations ?? [],\n )\n}\n","import { parseEventLogs, decodeAbiParameters, type Log } from 'viem'\nimport { publisherEventsAbi } from '~/helpers/abi/publisher'\nimport { executorEventsAbi } from '~/helpers/abi/executor'\nimport { getAttestedUidsFromReceipt } from '~/helpers/easDirect'\nimport { listCreatedAttestationPairsFromReceipt, toHex32Normalized } from './seedUidHelpers'\nimport { ZERO_BYTES32 } from './utils'\n\ntype ReceiptLike = {\n logs?: Array<{ address?: string; data?: string; topics?: unknown[] }>\n}\n\n/** The fields of a normalized multiPublish request this module reads. */\nexport type MultiPublishRequestLike = {\n localId?: string\n seedUid?: string\n seedSchemaUid?: string\n versionUid?: string\n versionSchemaUid?: string\n listOfAttestations?: Array<{ schema?: string; data?: unknown[]; _propertyName?: string }>\n}\n\nexport type AttributedPropertyPair = {\n schemaUid: string\n attestationUid: string\n propertyName?: string\n}\n\n/** What one request of a multiPublish transaction created. */\nexport type RequestAttestations = {\n /** Seed attestation created for the request (only when it had no seed uid). */\n seedUid?: string\n /** Version attestation created for the request (only when it had no version uid). */\n versionUid?: string\n propertyPairs: AttributedPropertyPair[]\n}\n\nconst isZero = (uid: string | undefined): boolean =>\n !uid || toHex32Normalized(uid) === ZERO_BYTES32\n\nconst sameSchema = (a: string | undefined, b: string | undefined): boolean =>\n !!a && !!b && toHex32Normalized(a) === toHex32Normalized(b)\n\n/** Property attestations EAS creates for one request: one per data entry of each list entry. */\nfunction expandPropertySlots(\n req: MultiPublishRequestLike,\n): Array<{ schema?: string; propertyName?: string }> {\n const out: Array<{ schema?: string; propertyName?: string }> = []\n for (const att of req.listOfAttestations ?? []) {\n const count = Array.isArray(att?.data) ? att.data.length : 1\n const propertyName =\n typeof att?._propertyName === 'string' && att._propertyName !== '' ? att._propertyName : undefined\n for (let k = 0; k < count; k++) out.push({ schema: att?.schema, propertyName })\n }\n return out\n}\n\ntype SeedPublishedEvent = { seedUid?: string; versionUid?: string; uids?: readonly string[] }\n\nfunction seedPublishedEvents(\n receipt: ReceiptLike,\n contractAddress: string,\n useModularExecutor: boolean,\n): SeedPublishedEvent[] {\n const want = contractAddress.toLowerCase()\n const logs = receipt.logs?.filter((l) => l.address && l.address.toLowerCase() === want)\n if (!logs?.length) return []\n try {\n if (useModularExecutor) {\n return parseEventLogs({\n abi: executorEventsAbi,\n eventName: 'SeedPublished',\n logs: logs as Log[],\n strict: false,\n }).map((ev) => {\n const args = ev.args as { seedUid?: string; versionUid?: string }\n return {\n seedUid: isZero(args?.seedUid) ? undefined : args.seedUid,\n versionUid: isZero(args?.versionUid) ? undefined : args.versionUid,\n }\n })\n }\n return parseEventLogs({\n abi: publisherEventsAbi,\n eventName: 'SeedPublished',\n logs: logs as Log[],\n strict: false,\n }).map((ev) => {\n const data = (ev.args as { returnedDataFromEAS?: `0x${string}` })?.returnedDataFromEAS\n if (!data || data === '0x') return { uids: [] }\n try {\n const decoded = decodeAbiParameters([{ type: 'bytes32[]' }], data)\n return { uids: (decoded[0] as readonly string[]) ?? [] }\n } catch {\n return { uids: [] }\n }\n })\n } catch {\n return []\n }\n}\n\n/**\n * Splits a multiPublish receipt into what each request created, in request order.\n *\n * None of the contract's events names the request it belongs to, but the contract handles the\n * requests one after another (SeedProtocolExecutor / SeedProtocolExtensionBase `multiPublish`), so\n * each kind of event appears in request order:\n * - CreatedAttestation: the request's seed (when its seedUid was zero), then its version (when its\n * versionUid was zero).\n * - EAS Attested: one per property attestation (EAS also emits one for each seed/version; those are\n * the CreatedAttestation uids and are skipped).\n * - SeedPublished: executor `(seedUid, versionUid)`, only for a request with property attestations;\n * extension `bytes32[]` of the property uids, for every request.\n * Each stream is consumed with its own cursor. When CreatedAttestation carries more events than\n * the seeds and versions created (an older contract that also reported property attestations\n * there), the properties are read from it instead of from EAS Attested.\n */\nexport function attributeMultiPublishReceipt(params: {\n receipt: ReceiptLike\n requests: MultiPublishRequestLike[]\n useModularExecutor: boolean\n easContractAddress: string\n contractAddressForEvents: string\n}): RequestAttestations[] {\n const { receipt, requests, useModularExecutor, easContractAddress, contractAddressForEvents } = params\n const created = listCreatedAttestationPairsFromReceipt(receipt, useModularExecutor)\n // EAS also reports the seeds and versions: drop them by uid, or by schema when the contract's\n // CreatedAttestation events are missing (a property schema is never a seed or version schema).\n const createdUids = new Set(created.map((c) => toHex32Normalized(c.attestationUid)))\n const seedVersionSchemas = new Set<string>()\n for (const r of requests) {\n if (isZero(r.seedUid) && r.seedSchemaUid) seedVersionSchemas.add(toHex32Normalized(r.seedSchemaUid))\n if (isZero(r.versionUid) && r.versionSchemaUid) {\n seedVersionSchemas.add(toHex32Normalized(r.versionSchemaUid))\n }\n }\n const attested = getAttestedUidsFromReceipt(receipt, easContractAddress)\n .filter(\n (a) =>\n !createdUids.has(toHex32Normalized(a.uid)) &&\n !seedVersionSchemas.has(toHex32Normalized(a.schemaUid)),\n )\n .map((a) => ({ schemaUid: a.schemaUid, attestationUid: a.uid }))\n const published = seedPublishedEvents(receipt, contractAddressForEvents, useModularExecutor)\n\n const slotsByRequest = requests.map(expandPropertySlots)\n const seedVersionCount = requests.reduce(\n (n, r) => n + (isZero(r.seedUid) ? 1 : 0) + (isZero(r.versionUid) ? 1 : 0),\n 0,\n )\n const propertyCount = slotsByRequest.reduce((n, s) => n + s.length, 0)\n const propertiesInCreated = propertyCount > 0 && created.length >= seedVersionCount + propertyCount\n\n let createdAt = 0\n let attestedAt = 0\n let publishedAt = 0\n const takeCreated = (schemaUid: string | undefined): string | undefined => {\n const next = created[createdAt]\n if (!next) return undefined\n createdAt += 1\n return sameSchema(next.schemaUid, schemaUid) ? next.attestationUid : undefined\n }\n\n return requests.map((req, i) => {\n const slots = slotsByRequest[i]!\n const out: RequestAttestations = { propertyPairs: [] }\n if (isZero(req.seedUid)) out.seedUid = takeCreated(req.seedSchemaUid)\n if (isZero(req.versionUid)) out.versionUid = takeCreated(req.versionSchemaUid)\n\n let propertySource: Array<{ schemaUid?: string; attestationUid: string } | undefined> = []\n if (propertiesInCreated) {\n propertySource = created.slice(createdAt, createdAt + slots.length)\n createdAt += slots.length\n } else if (attested.length) {\n propertySource = attested.slice(attestedAt, attestedAt + slots.length)\n attestedAt += slots.length\n }\n\n const emitsSeedPublished = !useModularExecutor || slots.length > 0\n const event = emitsSeedPublished ? published[publishedAt++] : undefined\n if (event) {\n if (useModularExecutor) {\n if (isZero(req.seedUid) && !out.seedUid) out.seedUid = event.seedUid\n if (isZero(req.versionUid) && !out.versionUid) out.versionUid = event.versionUid\n } else if (event.uids?.length) {\n // Property uids first; a legacy layout appended the seed and version uids after them.\n if (!propertySource.length && event.uids.length >= slots.length) {\n propertySource = event.uids.slice(0, slots.length).map((u) => ({ attestationUid: u }))\n }\n const legacySeed = event.uids[slots.length]\n const legacyVersion = event.uids[slots.length + 1]\n if (isZero(req.seedUid) && !out.seedUid && !isZero(legacySeed)) out.seedUid = legacySeed\n if (isZero(req.versionUid) && !out.versionUid && !isZero(legacyVersion)) {\n out.versionUid = legacyVersion\n }\n }\n }\n\n slots.forEach((slot, j) => {\n const got = propertySource[j]\n if (!got || isZero(got.attestationUid)) return\n // A uid from SeedPublished has no schema of its own; one from an event must match the slot.\n if (got.schemaUid && !sameSchema(got.schemaUid, slot.schema)) return\n const schemaUid = got.schemaUid ?? slot.schema\n if (!schemaUid) return\n out.propertyPairs.push({\n schemaUid,\n attestationUid: got.attestationUid,\n ...(slot.propertyName ? { propertyName: slot.propertyName } : {}),\n })\n })\n return out\n })\n}\n","import debug from 'debug'\n\nconst logger = debug('seedProtocol:services:publish:actors:persistSeedUid')\n\nconst ZERO_BYTES32 = '0x' + '0'.repeat(64)\n\n/** Timeout for persistSeedUid. Attestations are already on-chain; DB write is best-effort. */\nconst PERSIST_SEED_UID_TIMEOUT_MS = 15_000\n\nexport type RequestWithSeedUid = { seedUid?: string; localId?: string }\n\n/**\n * Assigns the published item's seedUid from the matching request (by item.seedLocalId).\n * Multi-publish payloads are ordered so the first request is not always the root item (e.g. Image before Post).\n */\nexport function persistSeedUidFromPublishResult(\n item: { seedUid?: string; seedLocalId?: string },\n normalizedRequests: RequestWithSeedUid[],\n): void {\n const seedLocalId = item.seedLocalId\n const match = seedLocalId\n ? normalizedRequests.find((r) => r?.localId === seedLocalId)\n : undefined\n // The first request is only a fallback when no request is the item's: in a batch it can be a\n // related item (e.g. an Image published before its Post), whose seed uid is not the item's.\n const uid = match ? match.seedUid : normalizedRequests[0]?.seedUid\n if (uid && uid !== ZERO_BYTES32) {\n item.seedUid = uid\n }\n}\n\n/**\n * Wraps item.persistSeedUid with timeout and error handling. Attestations are already\n * on-chain; if this fails or times out, we log and continue. Prevents the publish\n * flow from hanging when DB write is slow or fails.\n */\nexport async function persistSeedUidSafely(\n item: {\n persistSeedUid?: (publisher?: string, attestationCreatedAtMs?: number) => Promise<void>\n },\n address: string,\n attestationCreatedAtMs?: number,\n): Promise<void> {\n const persist = item.persistSeedUid\n if (typeof persist !== 'function') return\n\n const timeout = new Promise<never>((_, reject) =>\n setTimeout(() => reject(new Error('persistSeedUid timed out')), PERSIST_SEED_UID_TIMEOUT_MS),\n )\n\n try {\n await Promise.race([persist.call(item, address, attestationCreatedAtMs), timeout])\n } catch (err) {\n logger('persistSeedUid failed (attestations already on-chain):', err)\n // Don't throw - attestations are confirmed; DB write is best-effort\n }\n}\n","import { ZERO_ADDRESS } from '@ethereum-attestation-service/eas-sdk'\nimport { ZERO_BYTES32 } from './utils'\n\nconst BYTES32_LEN = 64\n\nexport const toHex32 = (v: unknown): string => {\n if (v == null) return '0x' + '0'.repeat(BYTES32_LEN)\n if (typeof v === 'string') {\n const raw = v.startsWith('0x') ? v.slice(2) : v\n const hex = raw.replace(/[^0-9a-fA-F]/g, '0').padStart(BYTES32_LEN, '0').slice(-BYTES32_LEN)\n return '0x' + hex\n }\n if (v instanceof Uint8Array || (typeof ArrayBuffer !== 'undefined' && v instanceof ArrayBuffer)) {\n const arr = v instanceof Uint8Array ? v : new Uint8Array(v)\n const hex = Array.from(arr).map((b) => b.toString(16).padStart(2, '0')).join('')\n return '0x' + hex.padStart(BYTES32_LEN, '0').slice(-BYTES32_LEN)\n }\n return '0x' + '0'.repeat(BYTES32_LEN)\n}\n\nexport const toBytesHex = (v: unknown): string => {\n if (v == null || (typeof v === 'string' && (v === '' || v === '0x'))) return '0x'\n if (typeof v === 'string') {\n const raw = v.startsWith('0x') ? v.slice(2) : v\n const hex = raw.replace(/[^0-9a-fA-F]/g, '0')\n return '0x' + (hex.length % 2 === 1 ? '0' + hex : hex)\n }\n if (v instanceof Uint8Array || (typeof ArrayBuffer !== 'undefined' && v instanceof ArrayBuffer)) {\n const arr = v instanceof Uint8Array ? v : new Uint8Array(v)\n return '0x' + Array.from(arr).map((b) => b.toString(16).padStart(2, '0')).join('')\n }\n return '0x'\n}\n\n/** True when an attestation still references another seed in this batch by localId (needs client-side resolution between txs). */\nexport function hasCrossPayloadUnresolved(reqs: unknown[]): boolean {\n const localIds = new Set(\n reqs.map((r) => (r as { localId?: string })?.localId).filter((id): id is string => !!id),\n )\n return reqs.some((req) =>\n ((req as { listOfAttestations?: unknown[] })?.listOfAttestations ?? []).some((a) => {\n const att = a as { _unresolvedValue?: string; _rawListIdsForResolve?: string[] }\n if (att._unresolvedValue && localIds.has(att._unresolvedValue)) return true\n if (Array.isArray(att._rawListIdsForResolve)) {\n return att._rawListIdsForResolve.some((id) => id && localIds.has(String(id).trim()))\n }\n return false\n }),\n )\n}\n\n/** Keep only propertiesToUpdate whose target is in the same multiPublish batch (same tx). */\nexport function filterPropertiesToUpdateForBatch<T extends { publishLocalId?: string }>(\n propertiesToUpdate: T[] | undefined,\n batchLocalIds: Set<string>,\n): T[] {\n return (propertiesToUpdate ?? []).filter(\n (pu) => pu.publishLocalId && batchLocalIds.has(pu.publishLocalId),\n )\n}\n\nconst placeholderData = {\n recipient: ZERO_ADDRESS,\n expirationTime: BigInt(0),\n revocable: true,\n refUID: ZERO_BYTES32,\n data: ZERO_BYTES32 as `0x${string}`,\n value: BigInt(0),\n}\n\n/** Normalize one publish request for SeedProtocol multiPublish (same rules as createAttestations). */\nexport function normalizePublishRequest(req: any): any {\n const listOfAttestations = (req?.listOfAttestations ?? []).map((att: any) => {\n const dataArr = Array.isArray(att?.data) ? att.data : []\n return {\n schema: toHex32(att?.schema),\n data: dataArr.map((d: any) => ({\n ...d,\n refUID: toHex32(d?.refUID),\n data: toBytesHex(d?.data),\n expirationTime: d?.expirationTime != null ? BigInt(d.expirationTime) : BigInt(0),\n value: d?.value != null ? BigInt(d.value) : BigInt(0),\n })),\n ...(typeof att?._propertyName === 'string' && att._propertyName !== ''\n ? { _propertyName: att._propertyName }\n : {}),\n ...(typeof att?._propertyNameForSchema === 'string' && att._propertyNameForSchema !== ''\n ? { _propertyNameForSchema: att._propertyNameForSchema }\n : {}),\n }\n })\n const propertiesToUpdate = (req?.propertiesToUpdate ?? []).map((p: any) => ({\n ...p,\n propertySchemaUid: toHex32(p?.propertySchemaUid),\n }))\n return {\n ...req,\n seedUid: toHex32(req?.seedUid),\n seedSchemaUid: toHex32(req?.seedSchemaUid),\n versionUid: toHex32(req?.versionUid),\n versionSchemaUid: toHex32(req?.versionSchemaUid),\n listOfAttestations,\n propertiesToUpdate,\n }\n}\n\n/** Ensure placeholder attestation data for contract injection targets (full batch). */\nexport function applyPropertiesToUpdatePlaceholders(\n normalizedRequests: any[],\n byLocalId: Map<string, any>,\n): void {\n for (const req of normalizedRequests) {\n for (const pu of req?.propertiesToUpdate ?? []) {\n const targetId = pu?.publishLocalId\n const schemaUid = toHex32(pu?.propertySchemaUid)\n if (!targetId || !schemaUid) continue\n const targetReq = byLocalId.get(targetId)\n if (!targetReq?.listOfAttestations) continue\n const att = targetReq.listOfAttestations.find(\n (a: any) => toHex32(a?.schema)?.toLowerCase() === schemaUid?.toLowerCase(),\n )\n if (!att) continue\n if (!Array.isArray(att.data) || att.data.length === 0) {\n att.data = [{ ...placeholderData, refUID: ZERO_BYTES32 }]\n }\n }\n }\n}\n","import { applyPropertyAttestationUidsFromPublish, Item, updateVersionUid } from '@seedprotocol/sdk'\nimport debug from 'debug'\nimport { getPublishConfig } from '~/config'\nimport { attestationMsFromReceipt } from '../helpers/receiptAttestationMs'\nimport {\n attributeMultiPublishReceipt,\n type MultiPublishRequestLike,\n type RequestAttestations,\n} from './multiPublishReceipt'\nimport { persistSeedUidSafely } from './persistSeedUid'\nimport { toHex32 } from './publishRequestNormalize'\nimport { ZERO_BYTES32 } from './utils'\n\nconst logger = debug('seedProtocol:services:publish:actors:recordMultiPublishReceipt')\n\ntype ReceiptLike = {\n blockNumber?: bigint\n logs?: Array<{ address?: string; data?: string; topics?: unknown[] }>\n}\n\nconst isZero = (uid: string | undefined): boolean => !uid || toHex32(uid) === ZERO_BYTES32\nconst nonZero = (uid: string | undefined): string | undefined => (isZero(uid) ? undefined : toHex32(uid))\n\n/**\n * Records locally what one multiPublish transaction attested, for every request in it (the item\n * being published and the related items published with it), each matched to its own events:\n * - the Version attestation it created (updateVersionUid). A request that carried a version uid (a\n * patch publish) created none: the executor's SeedPublished still reports that existing version,\n * which must not be recorded as a new one.\n * - its property attestation uids, on that version (applyPropertyAttestationUidsFromPublish).\n * - the Seed attestation it created, for related items (the item being published, `rootSeedLocalId`,\n * is left to the caller: createAttestations assigns it to the publishing item and persists it).\n *\n * Returns the requests with the seed and version uids this transaction created filled in.\n */\nexport async function recordMultiPublishReceipt<R extends MultiPublishRequestLike>(params: {\n receipt: ReceiptLike\n /** The normalized requests, in the order they were sent. */\n requests: R[]\n rootSeedLocalId: string | undefined\n useModularExecutor: boolean\n contractAddressForEvents: string\n publisherAddress: string\n}): Promise<{ requests: R[]; attributed: RequestAttestations[] }> {\n const { receipt, requests, rootSeedLocalId, useModularExecutor, contractAddressForEvents, publisherAddress } =\n params\n const { easContractAddress } = getPublishConfig()\n const attributed = attributeMultiPublishReceipt({\n receipt,\n requests,\n useModularExecutor,\n easContractAddress,\n contractAddressForEvents,\n })\n const attMs = await attestationMsFromReceipt(receipt)\n\n for (let i = 0; i < requests.length; i++) {\n const req = requests[i]!\n const versionUid = attributed[i]!.versionUid\n if (!req.localId || !isZero(req.versionUid) || isZero(versionUid)) continue\n await updateVersionUid({\n seedLocalId: req.localId,\n versionUid: toHex32(versionUid),\n publisher: publisherAddress,\n attestationCreatedAt: attMs,\n })\n }\n\n // Each request's property uids, against the version it attested under: its own version uid (a\n // patch publish), or the version this transaction created for it.\n for (let i = 0; i < requests.length; i++) {\n const req = requests[i]!\n const { propertyPairs, versionUid } = attributed[i]!\n if (!req.localId || !propertyPairs.length) continue\n await applyPropertyAttestationUidsFromPublish({\n seedLocalId: req.localId,\n attestationCreatedAtMs: attMs ?? null,\n versionUid: nonZero(req.versionUid) ?? nonZero(versionUid) ?? null,\n pairs: propertyPairs,\n })\n }\n\n for (let i = 0; i < requests.length; i++) {\n const req = requests[i]!\n const seedUid = attributed[i]!.seedUid\n if (!req.localId || req.localId === rootSeedLocalId || !isZero(req.seedUid) || isZero(seedUid)) {\n continue\n }\n await recordRelatedSeedUid({\n seedLocalId: req.localId,\n seedUid: seedUid!,\n publisherAddress,\n attestationCreatedAtMs: attMs,\n })\n }\n\n return {\n attributed,\n requests: requests.map((req, i) => {\n const { seedUid, versionUid } = attributed[i]!\n return {\n ...req,\n ...(isZero(req.seedUid) && !isZero(seedUid) ? { seedUid } : {}),\n ...(isZero(req.versionUid) && !isZero(versionUid) ? { versionUid } : {}),\n }\n }),\n }\n}\n\n/**\n * Records the Seed attestation a publish created for a related item (one published together with the\n * item being published) on that item. Best-effort: the attestation is already on-chain.\n */\nexport async function recordRelatedSeedUid(params: {\n seedLocalId: string\n seedUid: string\n publisherAddress: string\n attestationCreatedAtMs?: number\n}): Promise<void> {\n const { seedLocalId, seedUid, publisherAddress, attestationCreatedAtMs } = params\n try {\n const related = await Item.find({ seedLocalId } as Parameters<typeof Item.find>[0])\n if (!related) {\n logger('related item %s not found; its seed uid is not recorded', seedLocalId)\n return\n }\n ;(related as { seedUid?: string }).seedUid = seedUid\n await persistSeedUidSafely(related, publisherAddress, attestationCreatedAtMs)\n } catch (err) {\n logger('recording seed uid of related item %s failed: %O', seedLocalId, err)\n }\n}\n","import { createThirdwebClient, type ThirdwebClient } from 'thirdweb'\nimport { getPublishConfig } from '../config'\n\nlet _client: ThirdwebClient | null = null\nlet _clientKey: string | null = null\n\n/**\n * Thirdweb client for publish sends and contract calls.\n * Uses `thirdwebSecretKey` when set so server-side RPC is not limited to browser origins.\n * Recreates the client when the client id or secret key changes.\n */\nexport function getClient(): ThirdwebClient {\n const { thirdwebClientId, thirdwebSecretKey } = getPublishConfig()\n if (!thirdwebClientId && !thirdwebSecretKey) {\n throw new Error(\n '@seedprotocol/publish/thirdweb: thirdwebClientId or thirdwebSecretKey is required. Pass one in initPublish / PublishProvider config.',\n )\n }\n const key = `${thirdwebClientId ?? ''}\\0${thirdwebSecretKey ?? ''}`\n if (!_client || _clientKey !== key) {\n _clientKey = key\n _client = thirdwebClientId\n ? createThirdwebClient({\n clientId: thirdwebClientId,\n ...(thirdwebSecretKey ? { secretKey: thirdwebSecretKey } : {}),\n })\n : createThirdwebClient({ secretKey: thirdwebSecretKey! })\n }\n return _client\n}\n\n/** Drop the cached client (tests). */\nexport function resetPublishThirdwebClient(): void {\n _client = null\n _clientKey = null\n}\n","import type { ThirdwebClient } from 'thirdweb'\nimport type { Chain } from 'thirdweb/chains'\nimport { estimateUserOpGas, getPaymasterAndData, type UserOperation } from 'thirdweb/wallets/smart'\nimport { gasFields, logGas } from './gasLog'\n\n/**\n * Headroom on the bundler's callGasLimit, in basis points (1.2x). The bundler's estimate tracks\n * gas used, but the call needs more than that while it runs: refunds are only credited when the\n * transaction ends, and each nested call (EntryPoint → account → executor → EAS) holds back 1/64.\n * EntryPoint v0.6 charges only for gas used, so unused headroom costs nothing.\n */\nexport const CALL_GAS_HEADROOM_BPS = 12_000n\n\ntype PaymasterResult = Awaited<ReturnType<typeof getPaymasterAndData>>\n\nfunction paymasterAndDataOf(result: PaymasterResult): `0x${string}` {\n return ('paymasterAndData' in result && result.paymasterAndData ? result.paymasterAndData : '0x') as `0x${string}`\n}\n\n/**\n * `overrides.paymaster` for the sponsored managed account. Does what thirdweb's sponsored\n * EntryPoint v0.6 flow does (sponsor, estimate, re-sign), except that it raises callGasLimit by\n * {@link CALL_GAS_HEADROOM_BPS} before the paymaster signs. thirdweb uses gas limits returned\n * from this hook as they are; without it, it replaces `tx.gas` with the bundler's estimate.\n *\n * A `tx.gas` larger than the raised estimate wins. `client` may be a function, called per UserOp,\n * so a wallet can be built before publish config has a client id.\n *\n * Install it on any sponsored EntryPoint v0.6 smart wallet that sends Seed publishes, e.g. one\n * built with thirdweb's `smartWallet()` on a server:\n * `overrides: { paymaster: seedPaymaster(client, chain) }`.\n */\nexport function seedPaymaster(\n client: ThirdwebClient | (() => ThirdwebClient),\n chain: Chain,\n bundlerUrl?: string,\n) {\n return async (userOp: Parameters<typeof getPaymasterAndData>[0]['userOp']): Promise<PaymasterResult> => {\n logGas('paymaster hook called (userOp from thirdweb; callGasLimit is tx.gas or 0)', {\n sender: userOp.sender,\n chainId: chain.id,\n bundlerUrl: bundlerUrl ?? '(thirdweb default)',\n entryPoint: 'initCode' in userOp ? 'v0.6' : 'v0.7',\n ...gasFields(userOp),\n })\n if (!('initCode' in userOp)) {\n throw new Error(\n '@seedprotocol/publish: the managed account sent an EntryPoint v0.7 UserOp; its sponsored gas handling only supports EntryPoint v0.6.',\n )\n }\n const thirdwebClient = typeof client === 'function' ? client() : client\n // Don't pass paymasterOverride to getPaymasterAndData, or it calls this hook again.\n const first = await getPaymasterAndData({ userOp, client: thirdwebClient, chain })\n logGas('1/3 paymaster sponsored (limits here are ignored)', gasFields(first))\n const op: UserOperation = { ...userOp, paymasterAndData: paymasterAndDataOf(first) }\n const est = await estimateUserOpGas({ userOp: op, options: { client: thirdwebClient, chain, bundlerUrl } })\n logGas('2/3 bundler estimate (callGasLimit includes thirdweb\\'s +50k)', gasFields(est))\n const raised = (est.callGasLimit * CALL_GAS_HEADROOM_BPS) / 10_000n\n op.callGasLimit = userOp.callGasLimit > raised ? userOp.callGasLimit : raised\n op.verificationGasLimit = est.verificationGasLimit\n op.preVerificationGas = est.preVerificationGas\n\n // The paymaster's signature covers the gas limits, so it signs again after they change.\n logGas('raised limits sent to the paymaster for signing', {\n ...gasFields(op),\n headroomBps: CALL_GAS_HEADROOM_BPS,\n raisedEstimate: raised,\n txGas: userOp.callGasLimit,\n })\n const signed = await getPaymasterAndData({ userOp: op, client: thirdwebClient, chain })\n logGas('3/3 paymaster signed', gasFields(signed))\n if (signed.callGasLimit && signed.verificationGasLimit && signed.preVerificationGas) {\n // The paymaster signed its own limits; returning ours would fail validation.\n logGas('returning to thirdweb: the PAYMASTER\\'s own limits (its signature covers them)', {\n ...gasFields(signed),\n requestedCallGasLimit: op.callGasLimit,\n })\n return signed\n }\n const result = {\n paymasterAndData: paymasterAndDataOf(signed),\n callGasLimit: op.callGasLimit,\n verificationGasLimit: op.verificationGasLimit,\n preVerificationGas: op.preVerificationGas,\n }\n logGas('returning to thirdweb: our raised limits (thirdweb should send exactly these)', gasFields(result))\n return result\n }\n}\n","import { deploySmartAccount, getContract, } from 'thirdweb'\nimport { getClient } from './publishThirdwebClient'\nimport { createWallet, Account, inAppWallet, type Wallet, } from 'thirdweb/wallets'\nimport { useActiveAccount } from 'thirdweb/react'\nimport { ThirdwebContract, } from 'thirdweb/contract'\nimport { useEffect, useRef, useState, } from 'react'\nimport type { Chain } from 'thirdweb/chains'\nimport type { Address, Hex } from 'viem'\nimport debug from 'debug'\nimport {\n getConfigRef,\n getPublishConfig,\n requireManagedAccountFactoryAddress,\n resolveThirdwebWalletOptions,\n type PublishConfig,\n} from '../config'\nimport { MANAGED_ACCOUNT_FACTORY_ADDRESSES } from './constants'\nimport {\n isContractDeployed,\n pollSmartWalletDeployed as pollDeployed,\n} from './chainClient'\nimport { encodeCreateAccount, readFactoryGetAddress } from './contracts'\nimport type { PublishWallet } from './seedSigner'\nimport { getPublishThirdwebChain, isLocalThirdwebChain } from './thirdwebChain'\nimport { seedPaymaster } from './seedPaymaster'\nimport { logGas } from './gasLog'\n\nconst logger = debug('permaPress:helpers:thirdweb')\n\n/**\n * Custom storage for publish in-app wallets: same prefix for modular (EIP-7702) and managed (EIP-4337).\n * Uses `localStorage` so embedded-wallet session material survives app/tab restarts.\n */\nconst SEED_IN_APP_SESSION_PREFIX = 'seedProtocol:inAppPublish:'\n\nlet _publishInAppWalletStorage: {\n getItem: (key: string) => Promise<string | null>\n setItem: (key: string, value: string) => Promise<void>\n removeItem: (key: string) => Promise<void>\n} | null = null\n\nexport function getSharedPublishInAppWalletStorage() {\n if (!_publishInAppWalletStorage) {\n _publishInAppWalletStorage = {\n getItem: async (key) => {\n if (typeof window === 'undefined') return null\n return localStorage.getItem(SEED_IN_APP_SESSION_PREFIX + key)\n },\n setItem: async (key, value) => {\n if (typeof window === 'undefined') return\n localStorage.setItem(SEED_IN_APP_SESSION_PREFIX + key, value)\n },\n removeItem: async (key) => {\n if (typeof window === 'undefined') return\n localStorage.removeItem(SEED_IN_APP_SESSION_PREFIX + key)\n },\n }\n }\n return _publishInAppWalletStorage\n}\n\n/**\n * Copies Thirdweb in-app auth tokens between default localStorage keys and the\n * prefixed keys used by publish in-app wallets (`seedProtocol:inAppPublish:`).\n *\n * Modular ConnectButton writes the fresh session to prefixed storage; bare may be\n * stale. Prefer prefixed when both exist so managed-wallet autoConnect does not\n * overwrite a valid JWT with an old bare token.\n */\nexport function syncPublishInAppAuthToken(): {\n syncedBareToPrefixed: boolean\n syncedPrefixedToBare: boolean\n} {\n if (typeof window === 'undefined') {\n return { syncedBareToPrefixed: false, syncedPrefixedToBare: false }\n }\n const { thirdwebClientId } = getPublishConfig()\n if (!thirdwebClientId) {\n return { syncedBareToPrefixed: false, syncedPrefixedToBare: false }\n }\n try {\n const bareKey = `walletToken-${thirdwebClientId}`\n const prefixedKey = `${SEED_IN_APP_SESSION_PREFIX}${bareKey}`\n const bare = localStorage.getItem(bareKey)\n const prefixed = localStorage.getItem(prefixedKey)\n\n let syncedBareToPrefixed = false\n let syncedPrefixedToBare = false\n\n // Only copy bare → prefixed when prefixed is missing (cold-start / refresh recovery).\n if (bare && !prefixed) {\n localStorage.setItem(prefixedKey, bare)\n syncedBareToPrefixed = true\n }\n if (prefixed && !bare) {\n localStorage.setItem(bareKey, prefixed)\n syncedPrefixedToBare = true\n }\n if (prefixed && bare && bare !== prefixed) {\n localStorage.setItem(bareKey, prefixed)\n syncedPrefixedToBare = true\n }\n\n return { syncedBareToPrefixed, syncedPrefixedToBare }\n } catch {\n return { syncedBareToPrefixed: false, syncedPrefixedToBare: false }\n }\n}\n\nasync function connectManagedAccountWallet(chain: Chain = getPublishThirdwebChain()) {\n syncPublishInAppAuthToken()\n const managedAccountWallet = getManagedAccountWallet()\n await managedAccountWallet.autoConnect({ client: getClient(), chain })\n return managedAccountWallet\n}\n\nexport { getClient } from './publishThirdwebClient'\n\nexport const wallets = [\n // embeddedWallet(),\n createWallet('io.metamask',),\n // createWallet(\"com.coinbase.wallet\"),\n // createWallet(\"me.rainbow\"),\n]\n\nexport const useLocalWalletAccount = () => {\n\n const [ localWalletAccount, setLocalWalletAccount, ] = useState<Account | null>(null,)\n const personalWallet = createWallet('io.metamask',)\n\n const isConnecting = useRef(false)\n\n useEffect(() => {\n const _getAccount = async (): Promise<void> => {\n // if ( isConnecting.current ) {\n // return\n // }\n // isConnecting.current = true\n\n // const personalAccount = await personalWallet.connect({ client, },)\n // if ( !personalAccount ) {\n // throw new Error('Failed to connect to personal account',)\n // }\n\n // setLocalWalletAccount(personalAccount,)\n // isConnecting.current = false\n }\n\n _getAccount()\n\n }, [],)\n\n return localWalletAccount\n\n}\n\nexport const useActiveSmartWalletContract = () => {\n const account = useActiveAccount()\n\n const [ contract, setContract, ] = useState<ThirdwebContract | null>(null,)\n\n useEffect(() => {\n if ( !account || !account.address ) {\n return\n }\n\n setContract(getContract({\n client: getClient(),\n chain : getPublishThirdwebChain(),\n address : account.address,\n },),)\n\n }, [ account, ],)\n\n return contract\n}\n\n/**\n * Returns the deterministic smart wallet address for an admin signer and optional data.\n */\nexport async function getSmartWalletAddressForAdmin (\n adminAddress: string,\n data: string = '0x',\n): Promise<string> {\n return readFactoryGetAddress(adminAddress as Address, data as Hex)\n}\n\n/**\n * Returns true if the given address has contract bytecode deployed (e.g. a ManagedAccount).\n */\nexport async function isSmartWalletDeployed ( smartWalletAddress: string, ): Promise<boolean> {\n return isContractDeployed(smartWalletAddress)\n}\n\n/** Polls chain bytecode until the smart account is deployed or attempts are exhausted. */\nexport async function pollSmartWalletDeployed(\n smartWalletAddress: string,\n attempts?: number,\n intervalMs?: number,\n): Promise<boolean> {\n return pollDeployed(smartWalletAddress, attempts, intervalMs)\n}\n\n/**\n * Resolves the smart wallet address and account to use for publish.\n * If the user has no connected account or no deployed ManagedAccount, returns needsDeploy.\n *\n * When using EIP4337 (in-app wallet with account abstraction), account.address is already\n * the smart wallet address. We detect that case and use it directly instead of deriving\n * via getSmartWalletAddressForAdmin (which assumes account.address is the EOA admin).\n */\nexport async function resolveSmartWalletForPublish (\n account: Account | null,\n): Promise<{ address: string; account: Account } | { needsDeploy: true }> {\n if ( !account ) {\n return { needsDeploy: true }\n }\n // If account.address is already a deployed smart wallet (e.g. from EIP4337), use it directly\n const accountIsDeployedSmartWallet = await isSmartWalletDeployed(account.address,)\n if ( accountIsDeployedSmartWallet ) {\n return { address: account.address, account }\n }\n // Otherwise derive smart wallet from EOA admin (e.g. MetaMask)\n const smartWalletAddress = await getSmartWalletAddressForAdmin(account.address,)\n const deployed = await isSmartWalletDeployed(smartWalletAddress,)\n if ( deployed ) {\n return { address: smartWalletAddress, account }\n }\n return { needsDeploy: true }\n}\n\n/** External wallets (MetaMask, Rainbow) for the deploy flow only; no account abstraction. */\nexport const ExternalWalletsForDeploy = [\n createWallet('io.metamask',),\n createWallet('me.rainbow',),\n]\n\nexport const deploySmartWalletContract = async ( localAccount: Account, ) => {\n const accountContract = getContract({\n client: getClient(),\n chain : getPublishThirdwebChain(),\n address : localAccount.address,\n },)\n const result = await deploySmartAccount({\n smartAccount : localAccount,\n chain : getPublishThirdwebChain(),\n client : getClient(),\n accountContract,\n },)\n logger('deploySmartAccount result:', result,)\n return result\n}\n\n/**\n * Deploys a ManagedAccount by calling the Thirdweb factory `createAccount`.\n * Prefer the modular EIP-7702 in-app wallet as `signingAccount` (sponsorGas); it is more reliable\n * than `deploySmartAccount` on the counterfactual EIP-4337 managed wallet (UserOp factory deploy).\n */\nexport async function deployManagedAccountViaFactory(params: {\n adminAddress: string\n signingAccount: Account | PublishWallet\n data?: `0x${string}`\n}): Promise<void> {\n const { asThirdwebPublishWallet } = await import('./adapters/thirdwebAccount')\n const wallet = asThirdwebPublishWallet(params.signingAccount as Account | PublishWallet)\n const tx = encodeCreateAccount(\n params.adminAddress as Address,\n (params.data ?? '0x') as Hex,\n )\n await wallet.txSender.sendTransaction(tx)\n}\n\nexport const appMetadata = {\n name: \"Seed Protocol\",\n description: \"Seed Protocol\",\n url: \"https://seedprotocol.io\",\n}\n\n/**\n * Connects the managed account wallet (EIP4337 in-app wallet) and returns its address.\n * Use this when you need the connected managed account address for publish flows.\n *\n * @param chain - The chain to connect to (defaults to the publish chain)\n * @returns The connected managed account's address\n * @throws Error if the managed account cannot be connected or retrieved\n */\nexport async function getConnectedManagedAccountAddress(\n chain: Chain = getPublishThirdwebChain()\n): Promise<string> {\n const managedAccountWallet = await connectManagedAccountWallet(chain)\n const managedAccount = managedAccountWallet.getAccount()\n if (!managedAccount) {\n throw new Error('Failed to get managed account')\n }\n return managedAccount.address\n}\n\n/**\n * Returns the connected account for transaction signing (e.g. revoke).\n * Uses the modular account wallet. Returns null if not connected.\n */\nexport async function getConnectedAccount(): Promise<Account | null> {\n try {\n const wallet = getModularAccountWallet()\n await wallet.autoConnect({ client: getClient(), chain: getPublishThirdwebChain() })\n const account = wallet.getAccount()\n return account ?? null\n } catch {\n return null\n }\n}\n\n/**\n * Same as {@link getConnectedAccount}: the in-app modular wallet (EIP-7702) on the publish chain.\n * Prefer this name at modular publish entry points for clarity.\n */\nexport async function getConnectedModularAccount(): Promise<Account | null> {\n return getConnectedAccount()\n}\n\nfunction managedAccountFactoryFor(config: PublishConfig): string {\n const chainId = getPublishThirdwebChain(config).id\n const factory = config.managedAccountFactoryAddress ?? MANAGED_ACCOUNT_FACTORY_ADDRESSES[chainId]\n if (!factory) {\n throw new Error(\n `@seedprotocol/publish: no ManagedAccount factory is known for chain ${chainId}. Pass managedAccountFactoryAddress in publish config, or use the EOA / direct EAS path.`,\n )\n }\n return factory\n}\n\nconst IN_APP_AUTH_OPTIONS = ['farcaster', 'email', 'passkey', 'phone'] as const\n\n/**\n * One instance per settings so Thirdweb session, Connect UI and `autoConnect` share a wallet\n * object. Rebuilt when the chain, RPC, factory or `PublishConfig.thirdweb` change\n * (e.g. `PublishProvider` applies config after first render).\n */\nlet _managedInAppWallet: { key: string; wallet: Wallet } | null = null\n\n/**\n * Managed (EIP-4337) in-app wallet: the user's ManagedAccount smart account, admin = the\n * user's in-app EOA. Publishes are UserOps from this account.\n */\nexport const getManagedAccountWallet = (config?: PublishConfig) => {\n const cfg = config ?? getConfigRef()\n const chain = getPublishThirdwebChain(cfg ?? undefined)\n const factoryAddress = cfg ? managedAccountFactoryFor(cfg) : requireManagedAccountFactoryAddress()\n const { bundlerUrl, sponsorGas } = resolveThirdwebWalletOptions(cfg)\n if (!bundlerUrl && isLocalThirdwebChain(chain)) {\n throw new Error(\n `@seedprotocol/publish: chain ${chain.id} is local, so Thirdweb's hosted bundler cannot reach it. Set PublishConfig.thirdweb.bundlerUrl to the chain's bundler (seedTwinConfig does this for the twin).`,\n )\n }\n const key = [chain.id, chain.rpc, factoryAddress, bundlerUrl ?? '', sponsorGas].join('|').toLowerCase()\n if (_managedInAppWallet?.key !== key) {\n logGas('managed wallet built', {\n chainId: chain.id,\n sponsorGas,\n bundlerUrl: bundlerUrl ?? '(thirdweb default)',\n paymasterHook: sponsorGas ? 'installed' : 'none (thirdweb estimates callGasLimit itself)',\n })\n _managedInAppWallet = {\n key,\n wallet: inAppWallet({\n storage: getSharedPublishInAppWalletStorage(),\n auth: { options: [...IN_APP_AUTH_OPTIONS] },\n executionMode: {\n mode: 'EIP4337',\n smartAccount: {\n chain,\n factoryAddress,\n sponsorGas,\n ...(bundlerUrl || sponsorGas\n ? {\n overrides: {\n ...(bundlerUrl ? { bundlerUrl } : {}),\n // Adds headroom to callGasLimit; see seedPaymaster.\n ...(sponsorGas ? { paymaster: seedPaymaster(getClient, chain, bundlerUrl) } : {}),\n },\n }\n : {}),\n },\n },\n }),\n }\n }\n return _managedInAppWallet.wallet\n}\n\nlet _modularInAppWallet: { key: string; wallet: Wallet } | null = null\n\n/**\n * The user's in-app EOA (same login and storage as {@link getManagedAccountWallet}), which is\n * the ManagedAccount's admin. Sends admin-only transactions such as `installSeedExecutor`.\n * `PublishConfig.thirdweb.modularWalletMode` picks EIP-7702 (default; gas-sponsored unless\n * `thirdweb.sponsorGas` is false) or a plain EOA.\n *\n * @throws for EIP-7702 on a local chain: Thirdweb runs 7702 through its hosted bundler, which\n * cannot reach it, sponsored or not.\n */\nexport const getModularAccountWallet = (config?: PublishConfig) => {\n const cfg = config ?? getConfigRef()\n const { modularWalletMode, sponsorGas } = resolveThirdwebWalletOptions(cfg)\n if (modularWalletMode === 'EIP7702') {\n const chain = getPublishThirdwebChain(cfg ?? undefined)\n if (isLocalThirdwebChain(chain)) {\n throw new Error(\n `@seedprotocol/publish: chain ${chain.id} is local, and Thirdweb's EIP-7702 mode needs its hosted bundler, which cannot reach it. Set PublishConfig.thirdweb.modularWalletMode to 'EOA' and fund the in-app EOA (seedTwinConfig does this for the twin).`,\n )\n }\n }\n const key = `${modularWalletMode}|${sponsorGas}`\n if (_modularInAppWallet?.key !== key) {\n _modularInAppWallet = {\n key,\n wallet: inAppWallet({\n storage: getSharedPublishInAppWalletStorage(),\n auth: { options: [...IN_APP_AUTH_OPTIONS] },\n executionMode:\n modularWalletMode === 'EOA' ? { mode: 'EOA' } : { mode: 'EIP7702', sponsorGas },\n }),\n }\n }\n return _modularInAppWallet.wallet\n}\n\n/** Wallets for `ConnectButton`; pass the context config so the first render uses it. */\nexport const getWalletsForConnectButton = (config?: PublishConfig) => {\n const cfg = config ?? getConfigRef() ?? undefined\n return cfg?.useModularExecutor ? [getModularAccountWallet(cfg)] : [getManagedAccountWallet(cfg)]\n}\n","import { BaseError, parseEther, zeroAddress, type Address } from 'viem'\nimport { getPublishConfig } from '../config'\nimport { ManagedAccountPublishError, type ManagedAccountPublishErrorCode } from '../errors'\nimport { getPublishPublicClient, readUntil } from './chainClient'\nimport {\n readExecutorModuleEas,\n readExecutorModuleIsInitialized,\n readSeedExecutorRouter,\n} from './contracts'\nimport { describeRevert, findRevertData, isRevert } from './describeRevert'\nimport type { SeedTxRequest } from './seedSigner'\n\nconst MSG_LEGACY_ROUTER =\n 'This ManagedAccount predates the Seed executor router extension, so the Seed executor cannot act for it and publish automation is not available for this account.'\nconst MSG_NOT_INITIALIZED =\n 'The Seed executor is not installed for this ManagedAccount, so automation session keys cannot publish through it. The account admin installs it (installSeedExecutor), which enrollPublishAutomation does.'\nconst MSG_EAS_MISMATCH =\n 'The Seed executor module is configured with a different EAS contract for this ManagedAccount than publish config. Automation session keys cannot change it.'\nconst MSG_READ_FAILED = 'Could not read the Seed executor module state for this ManagedAccount.'\n\nfunction requireModuleAddress(): Address {\n const module = getPublishConfig().modularAccountModuleContract?.trim()\n if (!module || !/^0x[0-9a-fA-F]{40}$/.test(module)) {\n throw new Error(\n '@seedprotocol/publish: publish automation requires PublishConfig.modularAccountModuleContract (executor module).',\n )\n }\n return module as Address\n}\n\n/**\n * True for a Router account without the `SeedExecutorRouterExtension`: it cannot run the\n * executor at all, as opposed to an account where the executor is just not installed yet.\n */\nasync function lacksExecutorRouterExtension(managedAddress: Address): Promise<boolean> {\n return (await readSeedExecutorRouter(managedAddress)) === null\n}\n\nexport type ExecutorModuleReadinessOptions = {\n /**\n * The EAS the executor was just initialized with for the account, confirmed from the install\n * receipt (`ensureExecutorModuleInstalled`). When set, the module state is not re-read: right\n * after the install, a lagging RPC node can still report it uninitialized.\n */\n installedEas?: Address\n /**\n * Times to read `isInitialized` before reporting the module uninitialized, 2s apart. Default 1.\n * Use more right after an install that a lagging RPC node may not have seen yet.\n */\n readAttempts?: number\n}\n\n/**\n * Checks that the executor module can act for `managedAddress`: the module is initialized for\n * the account and points at the configured EAS. Checks what the module reports rather than the\n * account type, so any account the module has been set up for passes.\n *\n * @throws ManagedAccountPublishError `AUTOMATION_UNSUPPORTED_ACCOUNT` when it cannot\n */\nexport async function assertExecutorModuleReadyForAccount(\n managedAddress: string,\n options: ExecutorModuleReadinessOptions = {},\n): Promise<void> {\n const module = requireModuleAddress()\n const account = managedAddress as Address\n\n let initialized: boolean\n let moduleEas: Address\n if (options.installedEas) {\n initialized = true\n moduleEas = options.installedEas\n } else {\n try {\n initialized = await readUntil(\n () => readExecutorModuleIsInitialized(module, account),\n Boolean,\n { attempts: options.readAttempts ?? 1 },\n )\n moduleEas = initialized ? await readExecutorModuleEas(module, account) : zeroAddress\n } catch (cause) {\n throw new ManagedAccountPublishError(\n MSG_READ_FAILED,\n 'AUTOMATION_UNSUPPORTED_ACCOUNT',\n managedAddress,\n cause,\n )\n }\n }\n\n if (!initialized) {\n const message = (await lacksExecutorRouterExtension(account)) ? MSG_LEGACY_ROUTER : MSG_NOT_INITIALIZED\n throw new ManagedAccountPublishError(message, 'AUTOMATION_UNSUPPORTED_ACCOUNT', managedAddress)\n }\n\n const expected = getPublishConfig().easContractAddress?.toLowerCase()\n if (expected && moduleEas.toLowerCase() !== expected) {\n throw new ManagedAccountPublishError(MSG_EAS_MISMATCH, 'AUTOMATION_UNSUPPORTED_ACCOUNT', managedAddress)\n }\n}\n\n/** True when a call failed because the caller can't cover gas fees, not because it reverted. */\nfunction isInsufficientFunds(err: unknown): boolean {\n const msg = err instanceof BaseError ? `${err.shortMessage} ${err.details} ${err.message}` : String(err)\n return /insufficient funds|insufficient balance/i.test(msg)\n}\n\n/**\n * Simulates `tx` as a call from `managedAddress` (the call the account makes when it executes a\n * UserOp) and throws before anything is sent if it would revert. By default also throws when\n * the simulation itself cannot run, so automation never submits a UserOp it could not check.\n *\n * @throws ManagedAccountPublishError `code` (default `AUTOMATION_PREFLIGHT_FAILED`)\n */\nexport async function simulateCallFromAccount(params: {\n /** The account that sends `tx`. */\n managedAddress: string\n tx: SeedTxRequest\n /** Short description for the error message, e.g. \"multiPublish via the executor module\". */\n action: string\n code?: ManagedAccountPublishErrorCode\n /** False to let the send go ahead when the simulation cannot run (only a revert throws). */\n requireSimulation?: boolean\n}): Promise<void> {\n const { managedAddress, tx, action, code = 'AUTOMATION_PREFLIGHT_FAILED', requireSimulation = true } = params\n const call = (withBalance: boolean) =>\n getPublishPublicClient().call({\n account: managedAddress as Address,\n to: tx.to,\n data: tx.data,\n value: tx.value,\n // OP chains charge the L1 data fee up front, so an eth_call from an unfunded account\n // fails before running. A balance override lets the simulation reach the contract.\n ...(withBalance\n ? { stateOverride: [{ address: managedAddress as Address, balance: parseEther('1000') }] }\n : {}),\n })\n try {\n try {\n await call(false)\n } catch (err) {\n if (!isInsufficientFunds(err)) throw err\n await call(true)\n }\n } catch (cause) {\n const reverted = isRevert(cause)\n if (!reverted && !requireSimulation) return\n const reason = reverted ? describeRevert(findRevertData(cause)) : 'could not be simulated'\n throw new ManagedAccountPublishError(\n `Simulated ${action} from ${managedAddress} ${reason}; nothing was sent.`,\n code,\n managedAddress,\n cause,\n )\n }\n}\n","import type { Account } from 'thirdweb/wallets'\nimport { isAddressEqual, parseEventLogs, type Address, type TransactionReceipt } from 'viem'\nimport { waitForPublishReceipt, isContractDeployed } from './chainClient'\nimport type { PublishConfig } from '../config'\nimport { ManagedAccountPublishError, PublishTransactionRevertedError } from '../errors'\nimport { getPublishChainName } from './chainConfig'\nimport {\n encodeInstallSeedExecutor,\n readSeedExecutorInstalled,\n readSeedExecutorRouter,\n} from './contracts'\nimport { executorModuleAbi } from './abi/executor'\nimport { seedExecutorRouterAbi } from './abi/seedExecutorRouter'\nimport { describeRevert, findRevertData } from './describeRevert'\nimport { simulateCallFromAccount } from './executorModuleReadiness'\nimport { fromThirdwebAccount } from './adapters/thirdwebAccount'\n\nconst MODULE_INSTALL_MSG = () =>\n `The executor module could not be installed on your publishing account on ${getPublishChainName()}. Reconnect and try again, or contact support if this persists.`\n\nexport type EnsureExecutorModuleResult =\n /** Nothing to do: no module configured, account not deployed, or account without the extension. */\n | { status: 'skipped' }\n | { status: 'already-installed' }\n /** Installed by this call, confirmed from the receipt's logs. `eas` is what the executor was initialized with. */\n | { status: 'installed'; eas: Address; transactionHash: string }\n\n/**\n * Ensures `modularAccountModuleContract` is installed on `contractAddress`:\n * - Router accounts with the `SeedExecutorRouterExtension`: `installSeedExecutor()`, sent by the\n * account's admin EOA (the extension rejects self-calls). The install is confirmed from the\n * receipt's logs, not a follow-up read, so a lagging RPC node cannot make it look missing.\n * - Any other account: nothing to install; skipped. `assertExecutorModuleReadyForAccount` reports\n * why the executor cannot act for it.\n *\n * @param _account unused; kept for compatibility\n * @throws ManagedAccountPublishError `EXECUTOR_MODULE_NOT_INSTALLED` when the install fails\n */\nexport async function ensureExecutorModuleInstalled(\n contractAddress: string,\n _account: Account,\n config: Pick<PublishConfig, 'modularAccountModuleContract'>,\n): Promise<EnsureExecutorModuleResult> {\n const { modularAccountModuleContract } = config\n if (!modularAccountModuleContract) return { status: 'skipped' }\n\n if (!(await isContractDeployed(contractAddress))) {\n return { status: 'skipped' }\n }\n\n const router = await readSeedExecutorRouter(contractAddress as Address)\n if (!router) return { status: 'skipped' }\n return installViaRouterExtension(contractAddress, router.executor, modularAccountModuleContract)\n}\n\nasync function installViaRouterExtension(\n contractAddress: string,\n pinnedExecutor: Address,\n configuredModule: string,\n): Promise<EnsureExecutorModuleResult> {\n if (pinnedExecutor.toLowerCase() !== configuredModule.trim().toLowerCase()) {\n throw new ManagedAccountPublishError(\n `Your publishing account's Seed executor is ${pinnedExecutor}, but publish config sets modularAccountModuleContract to ${configuredModule}. Point modularAccountModuleContract at the account's executor.`,\n 'EXECUTOR_MODULE_NOT_INSTALLED',\n contractAddress,\n )\n }\n const account = contractAddress as Address\n let admin: Address\n let receipt: TransactionReceipt | undefined\n let transactionHash: string\n try {\n if (await readSeedExecutorInstalled(account, pinnedExecutor)) return { status: 'already-installed' }\n const { getManagedAccountAdmin } = await import('./managedAccountAdmin')\n const wallet = fromThirdwebAccount(await getManagedAccountAdmin(contractAddress))\n admin = wallet.txSender.address as Address\n const result = await wallet.txSender.sendTransaction(encodeInstallSeedExecutor(account))\n transactionHash = result.transactionHash\n try {\n receipt = await waitForPublishReceipt(result.transactionHash)\n } catch (err) {\n if (!(err instanceof PublishTransactionRevertedError)) throw err\n }\n } catch (cause) {\n if (cause instanceof ManagedAccountPublishError) throw cause\n throw new ManagedAccountPublishError(\n MODULE_INSTALL_MSG(),\n 'EXECUTOR_MODULE_NOT_INSTALLED',\n contractAddress,\n cause,\n )\n }\n\n const eas = receipt && installedEasFromReceipt(receipt, account, pinnedExecutor)\n if (eas) return { status: 'installed', eas, transactionHash }\n\n // No install in the receipt: the transaction reverted, or (sponsored sends) the relayer's\n // transaction succeeded but the inner call did not. Re-run the call to find out why.\n const reason = await simulateInstallSeedExecutor(account, admin)\n if (reason === 'already-installed') return { status: 'already-installed' }\n throw new ManagedAccountPublishError(\n `installSeedExecutor in transaction ${transactionHash} did not install the Seed executor on ${contractAddress}${reason ? `: ${reason}` : ''}.`,\n 'EXECUTOR_MODULE_NOT_INSTALLED',\n contractAddress,\n )\n}\n\n/**\n * The EAS the executor was initialized with for `account`, when `receipt` shows the install:\n * the account's `SeedExecutorInstalled(executor)` and the executor's `ModuleInitialized(account, eas)`.\n */\nexport function installedEasFromReceipt(\n receipt: Pick<TransactionReceipt, 'logs'>,\n account: Address,\n executor: Address,\n): Address | undefined {\n const installed = parseEventLogs({\n abi: seedExecutorRouterAbi,\n eventName: 'SeedExecutorInstalled',\n logs: receipt.logs,\n strict: false,\n }).some((log) => isAddressEqual(log.address, account) && log.args.executor && isAddressEqual(log.args.executor, executor))\n if (!installed) return undefined\n const initialized = parseEventLogs({\n abi: executorModuleAbi,\n eventName: 'ModuleInitialized',\n logs: receipt.logs,\n strict: false,\n }).find((log) => isAddressEqual(log.address, executor) && log.args.account && isAddressEqual(log.args.account, account))\n return initialized?.args.eas\n}\n\n/**\n * Simulates `installSeedExecutor` from `admin`. Returns 'already-installed' when it reverts with\n * `SeedExecutorAlreadyInstalled`, else the revert description, or undefined when the call would\n * succeed or cannot be simulated.\n */\nasync function simulateInstallSeedExecutor(\n account: Address,\n admin: Address,\n): Promise<'already-installed' | string | undefined> {\n try {\n await simulateCallFromAccount({\n managedAddress: admin,\n tx: encodeInstallSeedExecutor(account),\n action: 'installSeedExecutor',\n requireSimulation: false,\n })\n return undefined\n } catch (err) {\n const cause = err instanceof ManagedAccountPublishError ? err.underlyingCause : err\n const reason = describeRevert(findRevertData(cause))\n return reason === 'reverted with SeedExecutorAlreadyInstalled' ? 'already-installed' : reason\n }\n}\n","import {\n deploySmartWalletContract,\n getClient,\n getConnectedModularAccount,\n getConnectedManagedAccountAddress,\n getManagedAccountWallet,\n getModularAccountWallet,\n deployManagedAccountViaFactory,\n isSmartWalletDeployed,\n pollSmartWalletDeployed,\n syncPublishInAppAuthToken,\n} from './thirdweb'\nimport { getPublishConfig } from '../config'\nimport { isManagedAccountPublishError, ManagedAccountPublishError, stringifyUnderlyingCause } from '../errors'\nimport { ensureExecutorModuleInstalled } from './ensureExecutorModule'\nimport { getPublishThirdwebChain } from './thirdwebChain'\nimport { getPublishChainName } from './chainConfig'\n\nconst MSG_UNAVAILABLE = () =>\n `Could not connect the managed publishing account on ${getPublishChainName()}. Reconnect with the same sign-in method and try again.`\n\nconst MSG_NOT_DEPLOYED = () =>\n `Your publishing smart account is not deployed on ${getPublishChainName()} yet. Complete wallet setup, enable autoDeployManagedAccount in config if appropriate, then try again.`\n\nconst MSG_NOT_DEPLOYED_AFTER_ATTEMPT = () =>\n `The managed account could not be confirmed on ${getPublishChainName()} after deployment. Wait a moment and retry, or check your network connection.`\n\nconst MSG_FAILED_DEPLOY = () =>\n `Automatic deployment of the managed publishing account failed on ${getPublishChainName()}. Retry or deploy the account through your wallet provider.`\n\nexport type EnsureManagedAccountReadyResult =\n | { kind: 'skip' }\n | { kind: 'unavailable'; cause: unknown }\n | { kind: 'not_deployed'; managedAddress: string }\n | { kind: 'ready'; managedAddress: string }\n\n/**\n * Checks managed account deployment for the modular executor path.\n * Returns `{ kind: 'skip' }` when `useModularExecutor` is false.\n */\nexport async function ensureManagedAccountReady(): Promise<EnsureManagedAccountReadyResult> {\n const { useModularExecutor } = getPublishConfig()\n if (!useModularExecutor) {\n return { kind: 'skip' }\n }\n\n let managedAddress: string\n try {\n managedAddress = await getConnectedManagedAccountAddress(getPublishThirdwebChain())\n } catch (cause) {\n return { kind: 'unavailable', cause }\n }\n\n const deployed = await isSmartWalletDeployed(managedAddress)\n if (deployed) {\n return { kind: 'ready', managedAddress }\n }\n return { kind: 'not_deployed', managedAddress }\n}\n\nasync function getManagedAccountSigningAccount() {\n syncPublishInAppAuthToken()\n const managedWallet = getManagedAccountWallet()\n await managedWallet.autoConnect({ client: getClient(), chain: getPublishThirdwebChain() })\n const acc = managedWallet.getAccount()\n if (!acc) {\n throw new ManagedAccountPublishError(MSG_UNAVAILABLE(), 'MANAGED_ACCOUNT_UNAVAILABLE')\n }\n return acc\n}\n\nconst DEPLOY_TIMEOUT_MS = 90_000\n\nasync function deploySmartWalletWithTimeout(account: import('thirdweb/wallets').Account): Promise<void> {\n let timeoutId: ReturnType<typeof setTimeout> | undefined\n try {\n await Promise.race([\n deploySmartWalletContract(account),\n new Promise<never>((_, reject) => {\n timeoutId = setTimeout(\n () => reject(new Error(`Managed account deploy timed out after ${DEPLOY_TIMEOUT_MS / 1000}s`)),\n DEPLOY_TIMEOUT_MS,\n )\n }),\n ])\n } finally {\n if (timeoutId != null) clearTimeout(timeoutId)\n }\n}\n\n/**\n * Deploys the ManagedAccount via the factory using the managed in-app wallet signer,\n * or {@link PublishConfig.deployManagedAccount} when the host app provides a custom deploy path.\n * @throws ManagedAccountPublishError on missing account or deploy failure\n */\nexport async function tryDeployManagedAccount(managedAddress: string): Promise<void> {\n const config = getPublishConfig()\n const account = await getManagedAccountSigningAccount()\n const { fromThirdwebAccount } = await import('./adapters/thirdwebAccount')\n const managedSigningAccount = fromThirdwebAccount(account)\n\n const deployParams = { managedAddress, managedSigningAccount }\n\n try {\n if (config.deployManagedAccount) {\n await config.deployManagedAccount(deployParams)\n } else {\n const modularAccount = await getConnectedModularAccount()\n if (modularAccount) {\n const modularWallet = getModularAccountWallet()\n await modularWallet.autoConnect({ client: getClient(), chain: getPublishThirdwebChain() })\n const adminAddress =\n modularWallet.getAdminAccount?.()?.address ?? modularAccount.address\n await deployManagedAccountViaFactory({\n adminAddress,\n signingAccount: modularAccount,\n })\n } else {\n await deploySmartWalletWithTimeout(account)\n }\n }\n } catch (cause) {\n const isUserOpTimeout = /UserOp|user operation/i.test(stringifyUnderlyingCause(cause))\n const pollAttempts = isUserOpTimeout ? 15 : 5\n if (await pollSmartWalletDeployed(managedAddress, pollAttempts)) {\n return\n }\n throw new ManagedAccountPublishError(MSG_FAILED_DEPLOY(), 'MANAGED_ACCOUNT_NOT_DEPLOYED', managedAddress, cause)\n }\n\n if (!(await pollSmartWalletDeployed(managedAddress))) {\n throw new ManagedAccountPublishError(\n MSG_NOT_DEPLOYED_AFTER_ATTEMPT(),\n 'MANAGED_ACCOUNT_NOT_DEPLOYED',\n managedAddress,\n )\n }\n}\n\nexport type ModularExecutorPublishPrepResult =\n | { ok: true; managedAddress: string }\n | { ok: false; error: ManagedAccountPublishError }\n\n/**\n * Full gate for modular executor publish: managed-account deployment check, optional factory deploy,\n * optional executor module on the managed contract. EIP-7702 modular wallet readiness is handled separately\n * in {@link ensureEip7702ModularAccountReady}.\n * Call only when `useModularExecutor` is true.\n */\nexport async function runModularExecutorPublishPrep(): Promise<ModularExecutorPublishPrepResult> {\n const config = getPublishConfig()\n if (!config.useModularExecutor) {\n throw new Error('runModularExecutorPublishPrep: useModularExecutor is false')\n }\n\n let state = await ensureManagedAccountReady()\n\n if (state.kind === 'unavailable') {\n return {\n ok: false,\n error: new ManagedAccountPublishError(MSG_UNAVAILABLE(), 'MANAGED_ACCOUNT_UNAVAILABLE', undefined, state.cause),\n }\n }\n\n if (state.kind === 'not_deployed') {\n if (config.autoDeployManagedAccount) {\n try {\n await tryDeployManagedAccount(state.managedAddress)\n } catch (e) {\n const err =\n isManagedAccountPublishError(e)\n ? e\n : new ManagedAccountPublishError(MSG_FAILED_DEPLOY(), 'MANAGED_ACCOUNT_NOT_DEPLOYED', state.managedAddress, e)\n return { ok: false, error: err }\n }\n state = await ensureManagedAccountReady()\n if (state.kind !== 'ready') {\n return {\n ok: false,\n error: new ManagedAccountPublishError(\n MSG_NOT_DEPLOYED_AFTER_ATTEMPT(),\n 'MANAGED_ACCOUNT_NOT_DEPLOYED',\n state.kind === 'not_deployed' ? state.managedAddress : undefined,\n ),\n }\n }\n } else {\n return {\n ok: false,\n error: new ManagedAccountPublishError(MSG_NOT_DEPLOYED(), 'MANAGED_ACCOUNT_NOT_DEPLOYED', state.managedAddress),\n }\n }\n }\n\n if (state.kind === 'ready') {\n // Interactive publishing is a UserOp from the account itself and does not use the executor,\n // so installing it here is best-effort; enrollPublishAutomation requires it.\n if (config.modularAccountModuleContract) {\n try {\n const signingAccount = await getManagedAccountSigningAccount()\n await ensureExecutorModuleInstalled(state.managedAddress, signingAccount, config)\n } catch (e) {\n console.warn(\n `[@seedprotocol/publish] Executor module setup failed on ${getPublishChainName()}; publishing continues, but publish automation needs it.`,\n e,\n )\n }\n }\n\n return { ok: true, managedAddress: state.managedAddress }\n }\n\n throw new Error('runModularExecutorPublishPrep: unexpected readiness state')\n}\n","import {\n isPublishWallet,\n type PublishWallet,\n} from './seedSigner'\nimport { getPublishWallet } from './publishWalletRegistry'\n\n/** Resolve PublishWallet from machine context or the session registry. */\nexport function resolvePublishWallet(source: {\n wallet?: unknown\n account?: unknown\n}): PublishWallet {\n if (isPublishWallet(source.wallet)) return source.wallet\n if (isPublishWallet(source.account)) return source.account\n const registered = getPublishWallet()\n if (registered) return registered\n throw new Error(\n '@seedprotocol/publish: no PublishWallet available. Pass fromEthersWallet / fromEip1193Provider / fromThirdwebAccount, or call setPublishWallet / useSeedWallet.',\n )\n}\n","import {\n readSchemaRecord,\n encodeRegisterSchema,\n type SchemaRecord,\n} from './contracts'\nimport type { SeedTxRequest } from './seedSigner'\n\nexport type { SchemaRecord }\n\nexport type RegisterSchemaParams = {\n schema: string\n resolverAddress: string\n revocable: boolean\n}\n\nexport async function getSchemaRecord(uid: string): Promise<SchemaRecord | null> {\n return readSchemaRecord(uid)\n}\n\nexport function registerSchema(params: RegisterSchemaParams): SeedTxRequest {\n return encodeRegisterSchema(params)\n}\n","import { SchemaEncoder, NO_EXPIRATION, ZERO_BYTES32 } from '@ethereum-attestation-service/eas-sdk'\nimport { EAS_SCHEMA_NAME_ATTESTATION_UID } from './constants'\nimport { encodeEasAttest } from './contracts'\nimport type { SeedTxRequest } from './seedSigner'\n\nconst ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'\n\nexport type NameSchemaAttestationParams = {\n schemaUid: string\n schemaName: string\n}\n\nexport function prepareNameSchemaAttestation(\n params: NameSchemaAttestationParams,\n): SeedTxRequest {\n const schemaEncoder = new SchemaEncoder('bytes32 schemaId,string name')\n const encodedData = schemaEncoder.encodeData([\n { name: 'schemaId', value: params.schemaUid as `0x${string}`, type: 'bytes32' },\n { name: 'name', value: params.schemaName, type: 'string' },\n ])\n\n return encodeEasAttest({\n schema: EAS_SCHEMA_NAME_ATTESTATION_UID as `0x${string}`,\n data: {\n recipient: ZERO_ADDRESS as `0x${string}`,\n expirationTime: BigInt(NO_EXPIRATION),\n revocable: true,\n refUID: ZERO_BYTES32 as `0x${string}`,\n data: encodedData as `0x${string}`,\n value: 0n,\n },\n })\n}\n","import {\n getSegmentedItemProperties,\n getRelatedItemsForPublish,\n INTERNAL_DATA_TYPES,\n ModelPropertyDataTypes,\n normalizeDataType,\n getEasSchemaForItemProperty,\n setSchemaUidForSchemaDefinition,\n setSchemaUidForModel,\n listRelationEasPropertyName,\n easName,\n easPropertyNameForPublish,\n} from '@seedprotocol/sdk'\nimport type { IItem } from '@seedprotocol/sdk'\nimport { SchemaRegistry } from '@ethereum-attestation-service/eas-sdk'\nimport { getSchemaRecord, registerSchema } from '~/helpers/schemaRegistry'\nimport { prepareNameSchemaAttestation } from '~/helpers/nameSchemaAttestation'\nimport { waitForPublishReceipt } from '~/helpers/chainClient'\nimport { getPublishViemChain } from '~/helpers/chainConfig'\nimport { EAS_SCHEMA_NAME_ATTESTATION_UID } from '~/helpers/constants'\nimport {\n isPublishWallet,\n isSeedTxSender,\n type PublishWallet,\n type SeedTxSender,\n} from '~/helpers/seedSigner'\n\nconst RESOLVER_ADDRESS = '0x0000000000000000000000000000000000000000'\nconst REVOCABLE = true\n\n/** \"Name a Schema\" (EAS schema #1); UID is {@link EAS_SCHEMA_NAME_ATTESTATION_UID}. */\nconst NAME_SCHEMA_DEF = 'bytes32 schemaId,string name'\n/** Version attestation schema; UID matches the SDK's `VERSION_SCHEMA_UID`. */\nconst VERSION_SCHEMA_DEF = 'bytes32 version'\n\n/** Chain ids where the base schemas were found (avoids re-reading every publish). */\nconst chainsWithBaseSchemas = new Set<number>()\n\n/** @internal Tests only. */\nexport function resetEnsuredBaseSchemas(): void {\n chainsWithBaseSchemas.clear()\n}\n\n\n/**\n * Collects all model names used by the item (item's model + relation refs + list refs + Image).\n */\nasync function getModelNamesForItem(item: IItem<any>): Promise<Set<string>> {\n const { itemRelationProperties, itemImageProperties, itemListProperties } =\n await getSegmentedItemProperties(item)\n const modelNames = new Set<string>()\n\n if (item.modelName) {\n modelNames.add(item.modelName)\n }\n\n for (const prop of itemRelationProperties) {\n const ref = prop.propertyDef?.ref as string | undefined\n if (ref) modelNames.add(ref)\n }\n\n for (const prop of itemImageProperties) {\n const dataType = normalizeDataType(prop.propertyDef?.dataType)\n if (dataType === ModelPropertyDataTypes.File) modelNames.add('File')\n else if (dataType === ModelPropertyDataTypes.Html) modelNames.add('Html')\n else modelNames.add('Image')\n }\n\n for (const prop of itemListProperties) {\n const ref = prop.propertyDef?.ref as string | undefined\n if (ref) modelNames.add(ref)\n }\n\n return modelNames\n}\n\nasync function sendAndWait(txSender: SeedTxSender, tx: Parameters<SeedTxSender['sendTransaction']>[0]) {\n const result = await txSender.sendTransaction(tx)\n await waitForPublishReceipt(result.transactionHash)\n}\n\nexport type EnsureEasSchemasOptions = {\n /**\n * ManagedAccount address. When `account` is an active automation session key on this\n * account, missing schemas throw instead of being registered (session keys cannot call\n * SchemaRegistry or EAS).\n */\n managedAddress?: string\n}\n\ntype EnsureEasSchemasRunOptions = EnsureEasSchemasOptions & {\n blockSchemaRegistration?: boolean\n}\n\nfunction easTypeForDataType(dataType: string | undefined): string {\n const key = normalizeDataType(dataType)\n return (\n (INTERNAL_DATA_TYPES as Record<string, { eas?: string }>)[key]?.eas ?? 'string'\n )\n}\n\nfunction throwIfAutomationCannotRegister(blockSchemaRegistration: boolean, schemaDef: string): void {\n if (!blockSchemaRegistration) return\n throw new Error(\n `schema \"${schemaDef}\" is not registered; automation keys can't register schemas. Call ensureEasSchemasForItem with the owner wallet first.`,\n )\n}\n\n/**\n * Checks the Seed-wide schemas every publish depends on: \"Name a Schema\" (used to name every other\n * schema) and Version. Their UIDs are the same on every chain. The protocol registers them on each\n * supported chain (seed-protocol `seed:ensure-schemas`); the SDK does not, so a missing one is a\n * chain setup problem and fails before anything is sent.\n */\nasync function assertBaseSchemas(): Promise<void> {\n const chainId = getPublishViemChain().id\n if (chainsWithBaseSchemas.has(chainId)) return\n\n const versionSchemaUid = SchemaRegistry.getSchemaUID(\n VERSION_SCHEMA_DEF,\n RESOLVER_ADDRESS as `0x${string}`,\n REVOCABLE,\n )\n const required: Array<[def: string, uid: string]> = [\n [NAME_SCHEMA_DEF, EAS_SCHEMA_NAME_ATTESTATION_UID],\n [VERSION_SCHEMA_DEF, versionSchemaUid],\n ]\n const missing: string[] = []\n for (const [def, uid] of required) {\n if (!(await getSchemaRecord(uid))) missing.push(`\"${def}\" (${uid})`)\n }\n if (missing.length > 0) {\n throw new Error(\n `Seed base schema${missing.length > 1 ? 's' : ''} ${missing.join(' and ')} not registered on chain ${chainId}. ` +\n 'The protocol registers base schemas for each supported chain (seed-protocol: bun run seed:ensure-schemas).',\n )\n }\n\n chainsWithBaseSchemas.add(chainId)\n}\n\nasync function resolveBlockSchemaRegistration(\n account: PublishWallet | SeedTxSender,\n options: EnsureEasSchemasRunOptions | undefined,\n): Promise<boolean> {\n if (typeof options?.blockSchemaRegistration === 'boolean') {\n return options.blockSchemaRegistration\n }\n const managedAddress = options?.managedAddress?.trim()\n if (!managedAddress || !isPublishWallet(account)) return false\n const { isAutomationSessionActive } = await import('~/helpers/ensureAutomationSessionKey')\n return isAutomationSessionActive(managedAddress, account.signer.address)\n}\n\n/**\n * Ensures EAS schemas exist for each item property and each model used by the item.\n * If a schema is not found on-chain or in the indexer, registers it via SchemaRegistry\n * and creates a name attestation (Schema #1) so EASSCAN displays it.\n * Automation session keys cannot register; a missing schema throws before any UserOp.\n */\nexport async function ensureEasSchemasForItem(\n item: IItem<any>,\n account: PublishWallet | SeedTxSender,\n options?: EnsureEasSchemasOptions,\n): Promise<void> {\n await ensureEasSchemasForItemResolved(item, account, options)\n}\n\nasync function ensureEasSchemasForItemResolved(\n item: IItem<any>,\n account: PublishWallet | SeedTxSender,\n options?: EnsureEasSchemasRunOptions,\n): Promise<void> {\n const blockSchemaRegistration = await resolveBlockSchemaRegistration(account, options)\n const sender: SeedTxSender = isPublishWallet(account)\n ? account.txSender\n : isSeedTxSender(account)\n ? account\n : (() => {\n throw new Error(\n '@seedprotocol/publish: ensureEasSchemasForItem requires a PublishWallet or SeedTxSender',\n )\n })()\n await assertBaseSchemas()\n\n const { itemBasicProperties, itemRelationProperties, itemImageProperties, itemListProperties } =\n await getSegmentedItemProperties(item)\n\n const allProperties = [\n ...itemBasicProperties,\n ...itemRelationProperties,\n ...itemImageProperties,\n ...itemListProperties,\n ]\n\n const registeredSchemaUids = new Set<string>()\n\n const modelNames = await getModelNamesForItem(item)\n const registeredModelSchemaUids = new Set<string>()\n\n for (const modelName of modelNames) {\n const schemaDef = `bytes32 ${easName(modelName)}`\n const schemaUid = SchemaRegistry.getSchemaUID(\n schemaDef,\n RESOLVER_ADDRESS as `0x${string}`,\n REVOCABLE,\n )\n\n const onChainRecord = await getSchemaRecord(schemaUid)\n if (onChainRecord) {\n setSchemaUidForModel({ modelName, schemaUid })\n continue\n }\n\n if (registeredModelSchemaUids.has(schemaUid)) {\n setSchemaUidForModel({ modelName, schemaUid })\n continue\n }\n\n throwIfAutomationCannotRegister(blockSchemaRegistration, schemaDef)\n\n try {\n await sendAndWait(\n sender,\n registerSchema({\n schema: schemaDef,\n resolverAddress: RESOLVER_ADDRESS,\n revocable: REVOCABLE,\n }),\n )\n } catch (err) {\n throw new Error(\n `Failed to register EAS schema for model ${modelName}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n try {\n await sendAndWait(\n sender,\n prepareNameSchemaAttestation({\n schemaUid,\n schemaName: easName(modelName),\n }),\n )\n } catch (err) {\n throw new Error(\n `Failed to name EAS schema for model ${modelName}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n registeredModelSchemaUids.add(schemaUid)\n setSchemaUidForModel({ modelName, schemaUid })\n }\n\n const storageSchemaDef = 'string storage_transaction_id'\n const storageSchemaUid = SchemaRegistry.getSchemaUID(\n storageSchemaDef,\n RESOLVER_ADDRESS as `0x${string}`,\n REVOCABLE,\n )\n const storageOnChain = await getSchemaRecord(storageSchemaUid)\n if (storageOnChain) {\n setSchemaUidForSchemaDefinition({ text: storageSchemaDef, schemaUid: storageSchemaUid })\n } else if (\n !registeredSchemaUids.has(storageSchemaUid) &&\n (modelNames.has('Image') || modelNames.has('File') || modelNames.has('Html'))\n ) {\n throwIfAutomationCannotRegister(blockSchemaRegistration, storageSchemaDef)\n try {\n await sendAndWait(\n sender,\n registerSchema({\n schema: storageSchemaDef,\n resolverAddress: RESOLVER_ADDRESS,\n revocable: REVOCABLE,\n }),\n )\n await sendAndWait(\n sender,\n prepareNameSchemaAttestation({\n schemaUid: storageSchemaUid,\n schemaName: 'storage_transaction_id',\n }),\n )\n } catch (err) {\n throw new Error(\n `Failed to register EAS schema for storageTransactionId: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n registeredSchemaUids.add(storageSchemaUid)\n setSchemaUidForSchemaDefinition({ text: storageSchemaDef, schemaUid: storageSchemaUid })\n }\n\n for (const property of allProperties) {\n if (!property.propertyDef) continue\n\n const easDataTypeRaw = easTypeForDataType(property.propertyDef.dataType)\n // ADR 0008: the same name getPublishPayload attests under (list relations: storage name;\n // single relations: schema key).\n const listRelationName = listRelationEasPropertyName(property.propertyName, property.propertyDef)\n const propertyNameSnakeCase = easPropertyNameForPublish(\n property.propertyName,\n property.propertyDef as Parameters<typeof easPropertyNameForPublish>[1],\n )\n const schemaDef = `${easDataTypeRaw} ${propertyNameSnakeCase}`\n if (listRelationName && !propertyNameSnakeCase.endsWith('_ids')) {\n throw new Error(\n `Refusing to register \"${schemaDef}\" for list-relation property ${property.propertyName}: list relations attest as <singular>_<ref>_ids.`,\n )\n }\n\n const validEasTypes = [\n 'string',\n 'address',\n 'bool',\n 'bytes',\n 'bytes32',\n 'uint8',\n 'uint16',\n 'uint32',\n 'uint64',\n 'uint128',\n 'uint256',\n ] as const\n const easDataTypeForLookup = validEasTypes.includes(\n easDataTypeRaw as (typeof validEasTypes)[number],\n )\n ? (easDataTypeRaw as (typeof validEasTypes)[number])\n : undefined\n\n const schema = await getEasSchemaForItemProperty({\n // A list relation's cached schemaUid may be for its schema-key name; don't look it up.\n schemaUid: listRelationName ? undefined : property.schemaUid,\n propertyName: propertyNameSnakeCase,\n easDataType: easDataTypeForLookup,\n })\n\n if (schema) {\n const onChainRecord = await getSchemaRecord(schema.id)\n const matches = onChainRecord && onChainRecord.schema === schemaDef\n if (matches) {\n setSchemaUidForSchemaDefinition({ text: schemaDef, schemaUid: schema.id })\n continue\n }\n }\n\n const schemaUid = SchemaRegistry.getSchemaUID(\n schemaDef,\n RESOLVER_ADDRESS as `0x${string}`,\n REVOCABLE,\n )\n const onChainRecord = await getSchemaRecord(schemaUid)\n\n if (onChainRecord) {\n setSchemaUidForSchemaDefinition({ text: schemaDef, schemaUid })\n continue\n }\n\n if (registeredSchemaUids.has(schemaUid)) {\n setSchemaUidForSchemaDefinition({ text: schemaDef, schemaUid })\n continue\n }\n\n throwIfAutomationCannotRegister(blockSchemaRegistration, schemaDef)\n\n try {\n await sendAndWait(\n sender,\n registerSchema({\n schema: schemaDef,\n resolverAddress: RESOLVER_ADDRESS,\n revocable: REVOCABLE,\n }),\n )\n } catch (err) {\n throw new Error(\n `Failed to register EAS schema for property ${property.propertyName}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n try {\n await sendAndWait(\n sender,\n prepareNameSchemaAttestation({\n schemaUid,\n schemaName: propertyNameSnakeCase,\n }),\n )\n } catch (err) {\n throw new Error(\n `Failed to name EAS schema for property ${property.propertyName}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n registeredSchemaUids.add(schemaUid)\n setSchemaUidForSchemaDefinition({ text: schemaDef, schemaUid })\n }\n\n const relatedItems = await getRelatedItemsForPublish(item)\n for (const relatedItem of relatedItems) {\n await ensureEasSchemasForItemResolved(relatedItem as IItem<any>, account, {\n managedAddress: options?.managedAddress,\n blockSchemaRegistration,\n })\n }\n}\n","import { getUploadPipelineTransactionStatus } from '@seedprotocol/sdk'\nimport { getPublishConfig } from '~/config'\nimport { resolvePublishPayment } from '~/payment'\nimport { getTurboDataItemStatus } from '~/helpers/turbo'\n\n/**\n * Verifies each id is available via the upload API (`/api/upload/arweave/data/:id`), or from\n * Turbo for user-paid storage,\n * before creating storageTransactionId attestations. Prevents attestations when\n * the upload pipeline has not indexed the transaction or data item yet.\n *\n * @param txIds - Arweave L1 transaction ids and/or bundler data item ids\n * @throws Error if any id is not found (404) or not yet available\n */\nexport async function verifyArweaveTransactionsExist(txIds: string[]): Promise<void> {\n if (txIds.length === 0) return\n\n const config = getPublishConfig()\n const { storage } = resolvePublishPayment(config)\n if (storage.uploadTo === 'turbo' && storage.turbo) {\n // User-paid uploads went to Turbo, not the upload API.\n const turbo = storage.turbo\n const statuses = await Promise.all(txIds.map((id) => getTurboDataItemStatus(turbo, id)))\n statuses.forEach((status, i) => {\n if (status === 404) {\n throw new Error(\n `Arweave data item ${txIds[i]} not found on Turbo. Upload may have failed. Delete this publish record and try again.`,\n )\n }\n if (status !== 200) {\n throw new Error(`Arweave data item ${txIds[i]} is not yet available from Turbo (status: ${status}). Wait and retry.`)\n }\n })\n return\n }\n\n const { arweaveUploadVerificationBaseUrl } = config\n\n const results = await Promise.all(\n txIds.map((txId) =>\n getUploadPipelineTransactionStatus(arweaveUploadVerificationBaseUrl, txId),\n ),\n )\n\n for (let i = 0; i < txIds.length; i++) {\n const txId = txIds[i]\n const status = results[i]\n if (!status) continue\n\n if (status.status === 404) {\n throw new Error(\n `Arweave transaction ${txId} not found. Upload may have failed. Delete this publish record and try again.`\n )\n }\n\n if (status.status !== 200) {\n const detail =\n status.status === 504\n ? 'request timed out (upload service did not respond in time)'\n : `status: ${status.status}`\n throw new Error(\n `Arweave transaction ${txId} is not yet available from the upload service (${detail}). Wait and retry.`\n )\n }\n }\n}\n","import { arweaveL1FinalizeJobs, BaseDb } from '@seedprotocol/sdk'\nimport type { ArweaveTransactionInfo, PublishMachineContext, PublishUpload } from '../../types'\nimport { getPublishConfig } from '~/config'\n\nconst PHASE_PENDING = 'pending_l1' as const\n\n/**\n * Inserts one row per bundler DataItem id so the L1 finalize worker can resolve the L1 tx\n * and wait for anchoring. Idempotent on `data_item_id`.\n */\nexport async function enqueueArweaveL1FinalizeJobsFromPublishContext(\n context: PublishMachineContext,\n): Promise<void> {\n const { useArweaveBundler } = getPublishConfig()\n if (!useArweaveBundler) return\n\n const txs = context.arweaveTransactions ?? []\n const uploads = (context.publishUploads ?? []) as PublishUpload[]\n if (txs.length === 0 || txs.length !== uploads.length) return\n\n const db = BaseDb.getAppDb()\n if (!db) return\n\n const now = Date.now()\n\n for (let i = 0; i < txs.length; i++) {\n const ar = txs[i] as ArweaveTransactionInfo\n const up = uploads[i]\n if (!up) continue\n const dataItemId = (ar.transaction as { id?: string })?.id\n if (!dataItemId || typeof dataItemId !== 'string') continue\n\n try {\n await db\n .insert(arweaveL1FinalizeJobs)\n .values({\n seedLocalId: up.seedLocalId,\n dataItemId,\n versionLocalId: up.versionLocalId ?? null,\n itemPropertyName: up.itemPropertyName ?? null,\n phase: PHASE_PENDING,\n createdAt: now,\n updatedAt: now,\n })\n .onConflictDoNothing()\n } catch {\n /* ignore duplicate or DB errors */\n }\n }\n}\n","import { zeroAddress, type Address } from 'viem'\nimport { getPublishConfig } from '../config'\nimport { ManagedAccountPublishError } from '../errors'\nimport { waitForPublishReceipt } from './chainClient'\nimport { encodeSetEas, readGetEas } from './contracts'\nimport {\n isPublishWallet,\n isSeedTxSender,\n type PublishWallet,\n type SeedTxSender,\n} from './seedSigner'\nimport { getPublishChainName } from './chainConfig'\n\nconst MSG_SET_EAS = () =>\n `Could not verify or set the EAS contract address on your publishing account on ${getPublishChainName()}.`\nconst MSG_EAS_MISMATCH =\n 'ManagedAccount EAS pointer does not match publish config. Configure EAS with the user’s ManagedAccount wallet before automation publish (session keys cannot call setEas).'\nconst MSG_FIXED_EAS_MISMATCH = (current: string) =>\n `Your publishing account's Seed extension uses EAS ${current}, but publish config sets easContractAddress to a different contract. The extension's EAS is fixed at deployment; fix easContractAddress.`\n\nfunction normAddr(a: string): string {\n return a.toLowerCase()\n}\n\nfunction expectedEasFromConfig(managedAddress: string): string {\n const { easContractAddress } = getPublishConfig()\n const expected = normAddr(easContractAddress)\n if (!expected || expected === normAddr(zeroAddress)) {\n throw new ManagedAccountPublishError(\n 'Publish config is missing a valid easContractAddress.',\n 'MANAGED_ACCOUNT_SET_EAS_FAILED',\n managedAddress,\n )\n }\n return expected\n}\n\nasync function readCurrentEas(managedAddress: string): Promise<string> {\n try {\n const raw = await readGetEas(managedAddress as Address)\n return normAddr(typeof raw === 'string' ? raw : String(raw))\n } catch (cause) {\n throw new ManagedAccountPublishError(MSG_SET_EAS(), 'MANAGED_ACCOUNT_SET_EAS_FAILED', managedAddress, cause)\n }\n}\n\n/**\n * Read-only: ManagedAccount `getEas` must already match config.\n * Use for automation session keys (module-only targets cannot `setEas`).\n */\nexport async function assertManagedAccountEasMatchesConfig(managedAddress: string): Promise<void> {\n const expected = expectedEasFromConfig(managedAddress)\n const current = await readCurrentEas(managedAddress)\n if (current === expected) return\n throw new ManagedAccountPublishError(MSG_EAS_MISMATCH, 'MANAGED_ACCOUNT_SET_EAS_FAILED', managedAddress)\n}\n\n/**\n * Ensures the ManagedAccount's `getEas()` matches {@link getPublishConfig}.easContractAddress.\n *\n * Current Seed extensions fix EAS at deployment and have no `setEas`, so a mismatch is a config\n * error and nothing is sent. Only accounts on the pre-rollout extension, which report the zero\n * address until configured, get `setEas` sent by `account` (an account admin).\n */\nexport async function ensureManagedAccountEasConfigured(\n managedAddress: string,\n /** Sender for the pre-rollout `setEas` fallback; a function is only called when it is needed. */\n account: PublishWallet | SeedTxSender | (() => Promise<PublishWallet | SeedTxSender>),\n): Promise<void> {\n const expected = expectedEasFromConfig(managedAddress)\n const current = await readCurrentEas(managedAddress)\n\n if (current === expected) {\n return\n }\n if (current !== normAddr(zeroAddress)) {\n throw new ManagedAccountPublishError(\n MSG_FIXED_EAS_MISMATCH(current),\n 'MANAGED_ACCOUNT_SET_EAS_FAILED',\n managedAddress,\n )\n }\n\n try {\n const sender = typeof account === 'function' ? await account() : account\n const txSender: SeedTxSender = isPublishWallet(sender)\n ? sender.txSender\n : isSeedTxSender(sender)\n ? sender\n : (() => {\n throw new Error(\n '@seedprotocol/publish: ensureManagedAccountEasConfigured requires PublishWallet or SeedTxSender',\n )\n })()\n const { easContractAddress } = getPublishConfig()\n const tx = encodeSetEas(managedAddress as Address, easContractAddress as Address)\n const result = await txSender.sendTransaction(tx)\n await waitForPublishReceipt(result.transactionHash)\n } catch (cause) {\n throw new ManagedAccountPublishError(MSG_SET_EAS(), 'MANAGED_ACCOUNT_SET_EAS_FAILED', managedAddress, cause)\n }\n}\n","import { fromPromise } from 'xstate'\nimport type { PublishMachineContext } from '../../../types'\nimport type { ArweaveTransactionInfo } from '../../../types'\nimport type { PublishUpload } from '../../../types'\nimport { resolvePublishPayloadValues } from '@seedprotocol/sdk'\nimport { recordMultiPublishReceipt } from './recordMultiPublishReceipt'\nimport {\n isContractDeployed,\n} from '~/helpers/chainClient'\nimport { runModularExecutorPublishPrep } from '~/helpers/ensureManagedAccountReady'\nimport { encodeExecutorMultiPublish, encodeMultiPublish } from '~/helpers/contracts'\nimport {\n assertExecutorModuleReadyForAccount,\n simulateCallFromAccount,\n} from '~/helpers/executorModuleReadiness'\nimport { explainUserOpError } from '~/helpers/describeRevert'\nimport { waitForPublishReceipt } from '~/helpers/chainClient'\nimport { resolvePublishWallet } from '~/helpers/resolvePublishWallet'\nimport type { PublishWallet } from '~/helpers/seedSigner'\nimport type { Address } from 'viem'\nimport { persistSeedUidFromPublishResult, persistSeedUidSafely } from './persistSeedUid'\nimport { ensureEasSchemasForItem } from '../helpers/ensureEasSchemas'\nimport { verifyArweaveTransactionsExist } from '../helpers/verifyArweaveTransactionsExist'\nimport { getPublishConfig } from '~/config'\nimport { waitForItem } from './utils'\nimport { ZERO_BYTES32 } from './utils'\nimport { listCreatedAttestationPairsFromReceipt } from './seedUidHelpers'\nimport { attestationMsFromReceipt } from '../helpers/receiptAttestationMs'\nimport {\n normalizePublishRequest,\n applyPropertiesToUpdatePlaceholders,\n hasCrossPayloadUnresolved,\n filterPropertiesToUpdateForBatch,\n toHex32,\n} from './publishRequestNormalize'\nimport { enqueueArweaveL1FinalizeJobsFromPublishContext } from '../../arweaveL1Finalize/enqueue'\nimport { ensureManagedAccountEasConfigured } from '~/helpers/ensureManagedAccountEasConfigured'\nimport debug from 'debug'\n\nconst logger = debug('seedProtocol:services:publish:actors')\n\ntype PublishInput = { input: { context: PublishMachineContext; event: unknown } }\n\ntype ReceiptLike = {\n blockNumber?: bigint\n logs?: Array<{ address?: string; data?: string; topics?: unknown[] }>\n}\n\ntype PublishRoutingInput = {\n useModularExecutor: boolean\n publisherAddress: string\n modularAccountModuleContract?: string\n managedAddress?: string\n /**\n * When true (automation session keys), send `multiPublish` to the executor module\n * so module-only `approvedTargets` can execute. Interactive modular publish keeps\n * the ManagedAccount as `txTargetAddress`.\n */\n routeToExecutorModule?: boolean\n}\n\ntype PublishRouting = {\n txTargetAddress: string\n contractAddressForEvents: string\n}\n\nfunction isExecutorModuleAddress(value: string | undefined): value is string {\n return !!value && /^0x[0-9a-fA-F]{40}$/.test(value.trim())\n}\n\nexport function resolvePublishRouting(input: PublishRoutingInput): PublishRouting {\n const {\n useModularExecutor,\n publisherAddress,\n modularAccountModuleContract,\n managedAddress,\n routeToExecutorModule,\n } = input\n if (useModularExecutor) {\n if (!managedAddress) {\n throw new Error('resolvePublishRouting: managedAddress is required when useModularExecutor is true')\n }\n const module = modularAccountModuleContract?.trim()\n if (routeToExecutorModule) {\n if (!isExecutorModuleAddress(module)) {\n throw new Error(\n 'resolvePublishRouting: modularAccountModuleContract is required when routeToExecutorModule is true',\n )\n }\n return {\n txTargetAddress: module,\n contractAddressForEvents: module,\n }\n }\n return {\n txTargetAddress: managedAddress,\n contractAddressForEvents: module || managedAddress,\n }\n }\n return {\n txTargetAddress: publisherAddress,\n contractAddressForEvents: publisherAddress,\n }\n}\n\nexport const createAttestations = fromPromise(\n async ({\n input: { context },\n }: PublishInput): Promise<{\n easPayload: unknown\n publishedBatch: PublishMachineContext['publishedBatch']\n }> => {\n const { address, account, wallet } = context\n const arweaveTransactions = context.arweaveTransactions ?? []\n const publishUploads = context.publishUploads ?? []\n let { item } = context\n\n const { modularAccountModuleContract, useModularExecutor } = getPublishConfig()\n\n if (!address || typeof address !== 'string' || !address.trim()) {\n throw new Error('No wallet address for publish. Connect a wallet and try again.')\n }\n\n if (!wallet && !account) {\n throw new Error('Wallet session is missing. Reconnect your wallet and retry the publish.')\n }\n\n if (!useModularExecutor && !(await isContractDeployed(address))) {\n throw new Error(\n 'EOA publishing must use the direct EAS path (multiPublish requires a deployed publisher contract). If you see this, attestation routing is misconfigured.',\n )\n }\n\n if (!item?.seedLocalId) {\n throw new Error(\n 'Attestation recovery failed: Item data is missing. Delete this publish record and try a full publish from the beginning.',\n )\n }\n const waitForItemUsed = typeof item.getPublishUploads !== 'function'\n if (waitForItemUsed) {\n item = await waitForItem(item.seedLocalId)\n }\n\n const txCount = arweaveTransactions.length\n const uploadCount = publishUploads.length\n if (txCount !== uploadCount) {\n throw new Error(\n 'Attestation recovery failed: Arweave transaction data is missing or incomplete. Delete this publish record and try a full publish from the beginning.',\n )\n }\n\n let routing = resolvePublishRouting({\n useModularExecutor: false,\n publisherAddress: address,\n })\n let activeWallet: PublishWallet = resolvePublishWallet(context)\n let routeToExecutorModule = false\n\n await ensureEasSchemasForItem(item, activeWallet, { managedAddress: address })\n\n const uploadDataWithTxIds: Array<PublishUpload & { txId: string }> = arweaveTransactions.map(\n (arweaveTransaction: ArweaveTransactionInfo, i: number) => {\n const tx = arweaveTransaction.transaction as { id?: string }\n const txId = tx?.id\n if (!txId || typeof txId !== 'string') {\n throw new Error(\n 'Attestation recovery failed: Arweave transaction data did not survive restore. Delete this publish record and try a full publish from the beginning.',\n )\n }\n const upload = publishUploads[i] as PublishUpload | undefined\n if (!upload) throw new Error('Publish upload index mismatch')\n return { ...upload, txId }\n },\n )\n\n await verifyArweaveTransactionsExist(uploadDataWithTxIds.map((u) => u.txId))\n\n const requestData = await (\n item.getPublishPayload as (\n uploads: typeof uploadDataWithTxIds,\n opts?: { publishMode?: 'patch' | 'new_version' },\n ) => ReturnType<typeof item.getPublishPayload>\n )(uploadDataWithTxIds, { publishMode: context.publishMode ?? 'patch' })\n\n const reqs = Array.isArray(requestData) ? requestData : [requestData]\n\n if (useModularExecutor) {\n // App-held automation session keys (PUBLISH_AUTOMATION.md): keep the provided\n // PublishWallet when it is an active session key on the ManagedAccount. Do not\n // require a connected modular in-app wallet on the server.\n const sessionKeyAddress = activeWallet?.signer?.address\n let automationActive = false\n if (address && sessionKeyAddress) {\n const { isAutomationSessionActive } = await import(\n '~/helpers/ensureAutomationSessionKey'\n )\n // Probe failures must not silently fall through to modular in-app bootstrap\n // (that path requires a browser wallet and hides the real RPC/error).\n automationActive = await isAutomationSessionActive(address, sessionKeyAddress)\n }\n\n if (automationActive) {\n const module = modularAccountModuleContract?.trim()\n if (!isExecutorModuleAddress(module)) {\n throw new Error(\n '@seedprotocol/publish: automation publish requires PublishConfig.modularAccountModuleContract ' +\n '(executor module). Session keys are module-only and cannot call the ManagedAccount directly.',\n )\n }\n routing = resolvePublishRouting({\n useModularExecutor,\n publisherAddress: address,\n modularAccountModuleContract: module,\n managedAddress: address,\n routeToExecutorModule: true,\n })\n routeToExecutorModule = true\n // Read-only: automation keys cannot set up the module or its EAS (not in approvedTargets).\n await assertExecutorModuleReadyForAccount(address)\n } else {\n const prep = await runModularExecutorPublishPrep()\n if (!prep.ok) {\n throw prep.error\n }\n routing = resolvePublishRouting({\n useModularExecutor,\n publisherAddress: address,\n modularAccountModuleContract,\n managedAddress: prep.managedAddress,\n })\n const { ensureModularPublishBootstrap } = await import(\n '~/helpers/ensureModularPublishBootstrap'\n )\n const { fromThirdwebAccount } = await import('~/helpers/adapters/thirdwebAccount')\n activeWallet = fromThirdwebAccount(\n await ensureModularPublishBootstrap(prep.managedAddress),\n )\n }\n } else {\n await ensureManagedAccountEasConfigured(address, activeWallet)\n }\n\n // The executor module takes a different multiPublish struct than the ManagedAccount\n // extension. Every publish is simulated from the sending account first, so a call that would\n // revert is never sent and its decoded reason is reported. Automation also refuses to send\n // when the simulation cannot run; other routes go ahead.\n const sendPublishTx = async (requests: any[]) => {\n const to = routing.txTargetAddress as Address\n const tx = routeToExecutorModule\n ? encodeExecutorMultiPublish(to, requests, 5_000_000n)\n : encodeMultiPublish(to, requests, 5_000_000n)\n await simulateCallFromAccount(\n routeToExecutorModule\n ? { managedAddress: address, tx, action: 'multiPublish via the executor module' }\n : {\n managedAddress: activeWallet.txSender.address,\n tx,\n action: 'multiPublish',\n code: 'PUBLISH_PREFLIGHT_FAILED',\n requireSimulation: false,\n },\n )\n try {\n return await activeWallet.txSender.sendTransaction(tx)\n } catch (err) {\n throw explainUserOpError(err, activeWallet.txSender.address)\n }\n }\n\n const needsSequential = reqs.length > 1 && hasCrossPayloadUnresolved(reqs)\n\n let effectiveRequests: any[]\n let lastAttestationReceipt: ReceiptLike | null = null\n const batchExtraUids: string[] = []\n\n if (needsSequential) {\n let workingPayload = structuredClone(reqs) as any[]\n const resolvedUids: Record<string, string> = {}\n const resolvedVersionUids: Record<string, string> = {}\n\n for (let i = 0; i < workingPayload.length; i++) {\n workingPayload = await resolvePublishPayloadValues(workingPayload as any, resolvedUids)\n const rawReq = workingPayload[i]\n const batchLocalIds = new Set([rawReq.localId])\n const reqForPublish = {\n ...rawReq,\n propertiesToUpdate: filterPropertiesToUpdateForBatch(rawReq.propertiesToUpdate, batchLocalIds),\n }\n const normalizedOne = normalizePublishRequest(reqForPublish)\n const byLocalIdSingle = new Map([[normalizedOne.localId, normalizedOne]])\n applyPropertiesToUpdatePlaceholders([normalizedOne], byLocalIdSingle)\n\n const result = await sendPublishTx([normalizedOne])\n\n const receipt = await waitForPublishReceipt(result.transactionHash)\n if (!receipt) {\n throw new Error('Failed to send transaction')\n }\n\n lastAttestationReceipt = receipt\n for (const pair of listCreatedAttestationPairsFromReceipt(receipt, useModularExecutor)) {\n if (pair.attestationUid) batchExtraUids.push(pair.attestationUid)\n }\n const {\n requests: [recorded],\n } = await recordMultiPublishReceipt({\n receipt,\n requests: [normalizedOne],\n rootSeedLocalId: item.seedLocalId,\n useModularExecutor,\n contractAddressForEvents: routing.contractAddressForEvents,\n publisherAddress: address,\n })\n\n if (recorded?.versionUid && toHex32(recorded.versionUid) !== ZERO_BYTES32) {\n resolvedVersionUids[rawReq.localId] = recorded.versionUid\n }\n const hadZeroSeedUid =\n !normalizedOne.seedUid || toHex32(normalizedOne.seedUid) === ZERO_BYTES32\n const seedUidFromTx = hadZeroSeedUid ? recorded?.seedUid : undefined\n if (seedUidFromTx && toHex32(seedUidFromTx) !== ZERO_BYTES32) {\n resolvedUids[rawReq.localId] = seedUidFromTx\n workingPayload[i] = { ...workingPayload[i], seedUid: seedUidFromTx }\n batchExtraUids.push(seedUidFromTx)\n }\n }\n\n for (const p of workingPayload) {\n const id = p?.localId\n const su = p?.seedUid\n if (id && su && toHex32(su) !== ZERO_BYTES32) {\n resolvedUids[id] = toHex32(su)\n }\n }\n\n const fullyResolved = await resolvePublishPayloadValues(structuredClone(reqs), resolvedUids)\n effectiveRequests = fullyResolved.map((r: any) =>\n normalizePublishRequest({\n ...r,\n seedUid: resolvedUids[r.localId] ?? r.seedUid,\n versionUid: resolvedVersionUids[r.localId] ?? r.versionUid,\n }),\n )\n } else {\n const normalizedRequests = reqs.map((req: any) => normalizePublishRequest(req))\n\n const byLocalId = new Map(normalizedRequests.map((r: any) => [r?.localId, r]))\n applyPropertiesToUpdatePlaceholders(normalizedRequests, byLocalId)\n\n const payloadForContract = Array.isArray(requestData) ? normalizedRequests : [normalizedRequests[0]]\n const result = await sendPublishTx(payloadForContract)\n\n const receipt = await waitForPublishReceipt(result.transactionHash)\n if (!receipt) {\n throw new Error('Failed to send transaction')\n }\n\n lastAttestationReceipt = receipt\n for (const pair of listCreatedAttestationPairsFromReceipt(receipt, useModularExecutor)) {\n if (pair.attestationUid) batchExtraUids.push(pair.attestationUid)\n }\n // Every request in the transaction (the item and the related items published with it)\n // records its own seed, version and property uids.\n const recorded = await recordMultiPublishReceipt({\n receipt,\n requests: payloadForContract,\n rootSeedLocalId: item.seedLocalId,\n useModularExecutor,\n contractAddressForEvents: routing.contractAddressForEvents,\n publisherAddress: address,\n })\n effectiveRequests = recorded.requests\n }\n\n persistSeedUidFromPublishResult(item as { seedUid?: string; seedLocalId?: string }, effectiveRequests)\n const itemWithPersist = item as {\n persistSeedUid?: (publisher?: string, attestationCreatedAtMs?: number) => Promise<void>\n }\n const rootRequest = effectiveRequests.find((r) => r?.localId === item.seedLocalId)\n const rootSeedUid = rootRequest?.seedUid\n if (rootSeedUid && rootSeedUid !== ZERO_BYTES32) {\n const seedAttMs = lastAttestationReceipt\n ? await attestationMsFromReceipt(lastAttestationReceipt)\n : undefined\n await persistSeedUidSafely(itemWithPersist, address, seedAttMs)\n }\n\n logger('requestData', requestData)\n\n void enqueueArweaveL1FinalizeJobsFromPublishContext(context)\n\n try {\n // The item's co-publish rows and those of the related drafts published with it.\n const { clearHtmlEmbeddedImageCoPublishRows } = await import('@seedprotocol/sdk')\n const published = new Set<string>([item.seedLocalId])\n for (const r of effectiveRequests) if (r?.localId) published.add(r.localId)\n for (const seedLocalId of published) await clearHtmlEmbeddedImageCoPublishRows(seedLocalId)\n } catch {\n /* best-effort cleanup */\n }\n\n const { collectPublishedBatch } = await import('../../publishedBy/collectBatchUids')\n const rootForBatch =\n effectiveRequests.find((r) => r?.localId === item.seedLocalId) ?? effectiveRequests[0]\n for (const r of effectiveRequests) {\n if (r?.seedUid) batchExtraUids.push(String(r.seedUid))\n if (r?.versionUid) batchExtraUids.push(String(r.versionUid))\n }\n const publishedBatch = rootForBatch?.seedUid\n ? collectPublishedBatch({\n seedUid: String(rootForBatch.seedUid),\n versionUid: rootForBatch.versionUid ? String(rootForBatch.versionUid) : undefined,\n extraUids: batchExtraUids,\n })\n : null\n\n return { easPayload: requestData, publishedBatch }\n },\n)\n","import { getItemPropertiesFromEas } from '@seedprotocol/sdk'\nimport { AttestationVerificationError } from '../../../errors'\nimport debug from 'debug'\n\nconst logger = debug('seedProtocol:services:publish:verifyAttestations')\n\nconst ZERO_BYTES32 = '0x' + '0'.repeat(64)\n\nconst BYTES32_LEN = 64\nconst toHex32 = (v: unknown): string => {\n if (v == null) return '0x' + '0'.repeat(BYTES32_LEN)\n if (typeof v === 'string') {\n const raw = v.startsWith('0x') ? v.slice(2) : v\n const hex = raw.replace(/[^0-9a-fA-F]/g, '0').padStart(BYTES32_LEN, '0').slice(-BYTES32_LEN)\n return '0x' + hex\n }\n return '0x' + '0'.repeat(BYTES32_LEN)\n}\n\n/** Delay between verification retries. EAS indexing can lag; longer delay improves success rate. */\nconst VERIFY_DELAY_MS = 5000\n/** Max retries before giving up. EAS indexing can take 10–30+ seconds in high load. */\nconst VERIFY_MAX_ATTEMPTS = 6\n\ntype NormalizedRequest = {\n localId: string\n versionUid: string\n listOfAttestations: Array<{ schema: string }>\n}\n\ntype VerifyAttestationsInput = {\n normalizedRequests: NormalizedRequest[]\n item: { seedLocalId: string }\n}\n\n/**\n * Verifies that property/metadata attestations created during publish exist on EAS.\n * Throws AttestationVerificationError if any expected attestations are missing.\n */\nexport async function verifyAttestations({\n normalizedRequests,\n item,\n}: VerifyAttestationsInput): Promise<void> {\n const seedLocalId = item.seedLocalId\n\n for (const request of normalizedRequests) {\n if (request.listOfAttestations.length === 0) continue\n if (request.versionUid === ZERO_BYTES32) continue\n\n const expectedSchemas = request.listOfAttestations.map((a) =>\n toHex32(a.schema).toLowerCase(),\n )\n\n let easProperties: { schemaId?: string }[] = []\n let lastError: unknown\n\n for (let attempt = 1; attempt <= VERIFY_MAX_ATTEMPTS; attempt++) {\n try {\n if (attempt > 1) {\n await new Promise((r) => setTimeout(r, VERIFY_DELAY_MS))\n }\n easProperties = await getItemPropertiesFromEas({\n versionUids: [request.versionUid],\n })\n break\n } catch (err) {\n lastError = err\n logger('verifyAttestations attempt %d failed:', attempt, err)\n if (attempt === VERIFY_MAX_ATTEMPTS) {\n logger('verifyAttestations: giving up after %d attempts', VERIFY_MAX_ATTEMPTS)\n throw lastError\n }\n }\n }\n\n const foundSchemas = easProperties\n .map((p) => (p.schemaId ? toHex32(p.schemaId).toLowerCase() : ''))\n .filter(Boolean)\n const foundSet = new Set(foundSchemas)\n\n const missing = expectedSchemas.filter((s) => !foundSet.has(s))\n if (missing.length > 0) {\n throw new AttestationVerificationError(\n `Publish verification failed: Seed and Version attestations were created, but ` +\n `property/metadata attestations are missing or incomplete. ` +\n `Expected ${expectedSchemas.length} property attestations for schema(s) ${expectedSchemas.join(', ')}; ` +\n `found ${foundSchemas.length}. ` +\n `Use PublishManager.retryAttestations('${seedLocalId}') to retry.`,\n seedLocalId,\n expectedSchemas,\n foundSchemas,\n 'METADATA_PROPERTIES_MISSING',\n )\n }\n }\n}\n","import { fromPromise } from 'xstate'\nimport type { PublishMachineContext } from '../../../types'\nimport { ZERO_ADDRESS } from '@ethereum-attestation-service/eas-sdk'\nimport {\n Item,\n updateVersionUid,\n applyPropertyAttestationUidsFromPublish,\n resolvePublishPayloadValues,\n type IItem,\n} from '@seedprotocol/sdk'\nimport type { PublishUpload } from '../../../types'\nimport { persistSeedUidFromPublishResult, persistSeedUidSafely } from './persistSeedUid'\nimport { recordRelatedSeedUid } from './recordMultiPublishReceipt'\nimport { verifyAttestations } from '../helpers/verifyAttestations'\nimport { AttestationVerificationError } from '../../../errors'\nimport { ensureEasSchemasForItem } from '../helpers/ensureEasSchemas'\nimport { verifyArweaveTransactionsExist } from '../helpers/verifyArweaveTransactionsExist'\nimport { enqueueArweaveL1FinalizeJobsFromPublishContext } from '../../arweaveL1Finalize/enqueue'\nimport { getPublishConfig } from '~/config'\nimport { attestationMsFromReceipt } from '../helpers/receiptAttestationMs'\nimport { waitForPublishReceipt } from '~/helpers/chainClient'\nimport { resolvePublishWallet } from '~/helpers/resolvePublishWallet'\nimport {\n prepareEasAttest,\n prepareEasMultiAttest,\n encodeBytes32,\n ZERO_BYTES32,\n getAttestationUidFromReceipt,\n getAttestedUidsFromReceipt,\n type MultiAttestationRequest,\n} from '~/helpers/easDirect'\nimport type { ArweaveTransactionInfo } from '../../../types'\nimport debug from 'debug'\n\nconst logger = debug('seedProtocol:services:publish:createAttestationsDirectToEas')\n\nconst BYTES32_LEN = 64\nconst toHex32 = (v: unknown): string => {\n if (v == null) return '0x' + '0'.repeat(BYTES32_LEN)\n if (typeof v === 'string') {\n const raw = v.startsWith('0x') ? v.slice(2) : v\n const hex = raw.replace(/[^0-9a-fA-F]/g, '0').padStart(BYTES32_LEN, '0').slice(-BYTES32_LEN)\n return '0x' + hex\n }\n if (v instanceof Uint8Array || (typeof ArrayBuffer !== 'undefined' && v instanceof ArrayBuffer)) {\n const arr = v instanceof Uint8Array ? v : new Uint8Array(v)\n const hex = Array.from(arr).map((b) => b.toString(16).padStart(2, '0')).join('')\n return '0x' + hex.padStart(BYTES32_LEN, '0').slice(-BYTES32_LEN)\n }\n return '0x' + '0'.repeat(BYTES32_LEN)\n}\nconst toBytesHex = (v: unknown): string => {\n if (v == null || (typeof v === 'string' && (v === '' || v === '0x'))) return '0x'\n if (typeof v === 'string') {\n const raw = v.startsWith('0x') ? v.slice(2) : v\n const hex = raw.replace(/[^0-9a-fA-F]/g, '0')\n return '0x' + (hex.length % 2 === 1 ? '0' + hex : hex)\n }\n if (v instanceof Uint8Array || (typeof ArrayBuffer !== 'undefined' && v instanceof ArrayBuffer)) {\n const arr = v instanceof Uint8Array ? v : new Uint8Array(v)\n return '0x' + Array.from(arr).map((b) => b.toString(16).padStart(2, '0')).join('')\n }\n return '0x'\n}\n\nconst waitForItem = async (seedLocalId: string): Promise<IItem<any>> => {\n let item: IItem<any> | undefined\n try {\n item = await Item.find({ seedLocalId } as Parameters<typeof Item.find>[0])\n } catch {\n // No-op\n }\n if (item) return item\n return new Promise<IItem<any>>((resolve) => {\n const interval = setInterval(() => {\n try {\n Item.find({ seedLocalId } as Parameters<typeof Item.find>[0])\n .then((found: IItem<any> | undefined) => {\n if (found) {\n clearInterval(interval)\n resolve(found)\n }\n })\n } catch {\n // No-op\n }\n }, 200)\n })\n}\n\ntype RawAttestation = {\n data?: Array<{ data?: unknown }> | { data?: unknown }\n _rawListIdsForResolve?: string[]\n _unresolvedValue?: string\n _easDataType?: string\n _schemaDef?: string\n}\n\nconst isListAttestation = (att: RawAttestation | undefined): boolean =>\n Array.isArray(att?._rawListIdsForResolve) ||\n att?._easDataType === 'bytes32[]' ||\n (typeof att?._schemaDef === 'string' && att._schemaDef.startsWith('bytes32[]'))\n\nconst hasUnresolvedRef = (att: RawAttestation | undefined): boolean =>\n (Array.isArray(att?._rawListIdsForResolve) && att._rawListIdsForResolve.length > 0) ||\n !!att?._unresolvedValue\n\n/**\n * Re-encodes the attestations of `rawReq` (the getPublishPayload request) whose relation/list value\n * names seeds by localId once every one has a uid in `resolvedUids` (resolvePublishPayloadValues: a\n * list keeps its slot order, published members their uid), writing the result into `request`.\n */\nasync function applyResolvedRefs(\n rawReq: { listOfAttestations?: RawAttestation[] } | undefined,\n request: NormalizedRequest,\n resolvedUids: Record<string, string>,\n): Promise<void> {\n const rawAtts = rawReq?.listOfAttestations ?? []\n if (!rawAtts.some(hasUnresolvedRef)) return\n const [resolved] = (await resolvePublishPayloadValues([rawReq] as any, resolvedUids)) as unknown as Array<{\n listOfAttestations: RawAttestation[]\n }>\n rawAtts.forEach((raw, j) => {\n const out = resolved?.listOfAttestations?.[j]\n if (!hasUnresolvedRef(raw) || !out || hasUnresolvedRef(out)) return\n const outData = Array.isArray(out.data) ? out.data[0]?.data : out.data?.data\n const target = request.listOfAttestations[j]?.data?.[0]\n if (target && outData != null) target.data = toBytesHex(outData)\n })\n}\n\ntype PublishInput = { input: { context: PublishMachineContext; event: unknown } }\n\ntype NormalizedRequest = {\n localId: string\n seedUid: string\n seedSchemaUid: string\n versionUid: string\n versionSchemaUid: string\n seedIsRevocable: boolean\n listOfAttestations: Array<{\n schema: string\n data: Array<{\n recipient: string\n expirationTime: bigint\n revocable: boolean\n refUID: string\n data: string\n value: bigint\n }>\n _propertyName?: string\n _propertyNameForSchema?: string\n /** A List (bytes32[]) attestation: filled by resolving its slots, never by propertiesToUpdate. */\n _isList?: boolean\n }>\n propertiesToUpdate: Array<{ publishLocalId: string; propertySchemaUid: string }>\n}\n\nexport const createAttestationsDirectToEas = fromPromise(\n async ({\n input: { context, event },\n }: PublishInput): Promise<{\n easPayload: unknown\n publishedBatch: PublishMachineContext['publishedBatch']\n }> => {\n const { address, account, wallet } = context\n const arweaveTransactions = context.arweaveTransactions ?? []\n const publishUploads = context.publishUploads ?? []\n let { item } = context\n\n if (!address || typeof address !== 'string' || !address.trim()) {\n throw new Error('No wallet address for publish. Connect a wallet and try again.')\n }\n\n if (!wallet && !account) {\n throw new Error('Wallet session is missing. Reconnect your wallet and retry the publish.')\n }\n\n if (!item?.seedLocalId) {\n throw new Error(\n 'Attestation recovery failed: Item data is missing. Delete this publish record and try a full publish from the beginning.',\n )\n }\n const waitForItemUsed = typeof item.getPublishUploads !== 'function'\n if (waitForItemUsed) {\n item = await waitForItem(item.seedLocalId)\n }\n\n const txCount = arweaveTransactions.length\n const uploadCount = publishUploads.length\n if (txCount !== uploadCount) {\n throw new Error(\n 'Attestation recovery failed: Arweave transaction data is missing or incomplete. Delete this publish record and try a full publish from the beginning.',\n )\n }\n\n const publishWallet = resolvePublishWallet(context)\n const txSender = publishWallet.txSender\n\n await ensureEasSchemasForItem(item, publishWallet, { managedAddress: address })\n\n const uploadDataWithTxIds: Array<PublishUpload & { txId: string }> = arweaveTransactions.map(\n (arweaveTransaction: ArweaveTransactionInfo, i: number) => {\n const tx = arweaveTransaction.transaction as { id?: string }\n const txId = tx?.id\n if (!txId || typeof txId !== 'string') {\n throw new Error(\n 'Attestation recovery failed: Arweave transaction data did not survive restore. Delete this publish record and try a full publish from the beginning.',\n )\n }\n const upload = publishUploads[i] as PublishUpload | undefined\n if (!upload) throw new Error('Publish upload index mismatch')\n return { ...upload, txId }\n },\n )\n\n await verifyArweaveTransactionsExist(uploadDataWithTxIds.map((u) => u.txId))\n\n const requestData = await (\n item.getPublishPayload as (\n uploads: typeof uploadDataWithTxIds,\n opts?: { publishMode?: 'patch' | 'new_version' },\n ) => ReturnType<typeof item.getPublishPayload>\n )(uploadDataWithTxIds, { publishMode: context.publishMode ?? 'patch' })\n const reqs = Array.isArray(requestData) ? requestData : [requestData]\n\n const normalizedRequests: NormalizedRequest[] = reqs.map((req: any) => {\n const listOfAttestations = (req?.listOfAttestations ?? []).map((att: any) => {\n const dataArr = Array.isArray(att?.data) ? att.data : []\n return {\n schema: toHex32(att?.schema),\n data: dataArr.map((d: any) => ({\n ...d,\n refUID: toHex32(d?.refUID),\n data: toBytesHex(d?.data),\n })),\n ...(typeof att?._propertyName === 'string' && att._propertyName !== ''\n ? { _propertyName: att._propertyName }\n : {}),\n ...(typeof att?._propertyNameForSchema === 'string' && att._propertyNameForSchema !== ''\n ? { _propertyNameForSchema: att._propertyNameForSchema }\n : {}),\n ...(isListAttestation(att) ? { _isList: true } : {}),\n }\n })\n const propertiesToUpdate = (req?.propertiesToUpdate ?? []).map((p: any) => ({\n ...p,\n propertySchemaUid: toHex32(p?.propertySchemaUid),\n }))\n return {\n ...req,\n seedUid: toHex32(req?.seedUid),\n seedSchemaUid: toHex32(req?.seedSchemaUid),\n versionUid: toHex32(req?.versionUid),\n versionSchemaUid: toHex32(req?.versionSchemaUid),\n listOfAttestations,\n propertiesToUpdate,\n }\n })\n\n const byLocalId = new Map(normalizedRequests.map((r) => [r.localId, r]))\n const placeholderData = {\n recipient: ZERO_ADDRESS,\n expirationTime: BigInt(0),\n revocable: true,\n refUID: ZERO_BYTES32,\n data: ZERO_BYTES32 as `0x${string}`,\n value: BigInt(0),\n }\n for (const req of normalizedRequests) {\n for (const pu of req.propertiesToUpdate ?? []) {\n const targetId = pu.publishLocalId\n const schemaUid = toHex32(pu.propertySchemaUid)\n if (!targetId || !schemaUid) continue\n const targetReq = byLocalId.get(targetId)\n if (!targetReq?.listOfAttestations) continue\n const att = targetReq.listOfAttestations.find(\n (a) => toHex32(a?.schema)?.toLowerCase() === schemaUid?.toLowerCase(),\n )\n if (!att || att._isList) continue\n if (!Array.isArray(att.data) || att.data.length === 0) {\n att.data = [{ ...placeholderData, refUID: ZERO_BYTES32 }]\n }\n }\n }\n\n let lastAttestationMs = Date.now()\n const batchExtraUids: string[] = []\n /** Seed attestations this publish created, by request localId, with their attestation time. */\n const createdSeeds = new Map<string, { seedUid: string; attestationMs: number }>()\n /** Seed uid of every request with one so far, by localId: what relation/list refs resolve to. */\n const resolvedUids: Record<string, string> = {}\n for (const r of normalizedRequests) {\n if (r.localId && r.seedUid !== ZERO_BYTES32) resolvedUids[r.localId] = r.seedUid\n }\n\n const itemWithPersist = item as {\n seedUid?: string\n seedLocalId?: string\n persistSeedUid?: (publisher?: string, attestationCreatedAtMs?: number) => Promise<void>\n }\n const persistCreatedSeed = async (seedLocalId: string, seedUid: string, attestationMs: number) => {\n if (seedLocalId === item.seedLocalId) {\n itemWithPersist.seedUid = seedUid\n await persistSeedUidSafely(itemWithPersist, address, attestationMs)\n } else {\n await recordRelatedSeedUid({ seedLocalId, seedUid, publisherAddress: address, attestationCreatedAtMs: attestationMs })\n }\n }\n\n for (let i = 0; i < normalizedRequests.length; i++) {\n const request = normalizedRequests[i] as NormalizedRequest\n let newSeedUid = request.seedUid\n let newVersionUid = request.versionUid\n\n if (newSeedUid === ZERO_BYTES32) {\n const attestTx = prepareEasAttest({\n schema: request.seedSchemaUid as `0x${string}`,\n data: {\n refUID: ZERO_BYTES32,\n data: encodeBytes32(request.seedSchemaUid as `0x${string}`),\n revocable: request.seedIsRevocable,\n },\n })\n const result = await txSender.sendTransaction(attestTx)\n const receipt = await waitForPublishReceipt(result.transactionHash)\n if (!receipt) throw new Error('Failed to create Seed attestation')\n lastAttestationMs = await attestationMsFromReceipt(receipt)\n const { easContractAddress } = getPublishConfig()\n const seedUidFromReceipt = getAttestationUidFromReceipt(receipt, easContractAddress)\n if (!seedUidFromReceipt || seedUidFromReceipt === ZERO_BYTES32) {\n throw new Error('Failed to get Seed UID from attestation receipt')\n }\n newSeedUid = seedUidFromReceipt\n request.seedUid = seedUidFromReceipt\n if (request.localId) {\n createdSeeds.set(request.localId, { seedUid: seedUidFromReceipt, attestationMs: lastAttestationMs })\n resolvedUids[request.localId] = seedUidFromReceipt\n // Record the seed now: each attestation is its own transaction, so a later one failing\n // must not leave this seed on chain with no local row pointing at it (a retry would\n // attest a second seed for the same item).\n await persistCreatedSeed(request.localId, seedUidFromReceipt, lastAttestationMs)\n }\n batchExtraUids.push(seedUidFromReceipt)\n logger('created Seed attestation', newSeedUid)\n } else if (newSeedUid !== ZERO_BYTES32) {\n batchExtraUids.push(newSeedUid)\n }\n\n if (newSeedUid !== ZERO_BYTES32 && newVersionUid === ZERO_BYTES32) {\n const attestTx = prepareEasAttest({\n schema: request.versionSchemaUid as `0x${string}`,\n data: {\n refUID: newSeedUid as `0x${string}`,\n data: encodeBytes32(request.versionSchemaUid as `0x${string}`),\n revocable: true,\n },\n })\n const result = await txSender.sendTransaction(attestTx)\n const receipt = await waitForPublishReceipt(result.transactionHash)\n if (!receipt) throw new Error('Failed to create Version attestation')\n lastAttestationMs = await attestationMsFromReceipt(receipt)\n const { easContractAddress } = getPublishConfig()\n const versionUidFromReceipt = getAttestationUidFromReceipt(receipt, easContractAddress)\n if (!versionUidFromReceipt || versionUidFromReceipt === ZERO_BYTES32) {\n throw new Error('Failed to get Version UID from attestation receipt')\n }\n newVersionUid = versionUidFromReceipt\n request.versionUid = versionUidFromReceipt\n batchExtraUids.push(versionUidFromReceipt)\n await updateVersionUid({\n seedLocalId: request.localId,\n versionUid: versionUidFromReceipt,\n publisher: address,\n attestationCreatedAt: lastAttestationMs,\n })\n logger('created Version attestation', newVersionUid)\n } else if (newVersionUid !== ZERO_BYTES32) {\n batchExtraUids.push(newVersionUid)\n }\n\n for (const att of request.listOfAttestations) {\n for (const d of att.data) {\n d.refUID = newVersionUid\n }\n }\n\n // Relation and list values that name a seed of this publish by localId get its uid, as on the\n // contract path (createAttestations): requests come referenced-first, so those seeds exist.\n await applyResolvedRefs(reqs[i], request, resolvedUids)\n\n for (const pu of request.propertiesToUpdate ?? []) {\n const targetReq = byLocalId.get(pu.publishLocalId)\n if (!targetReq?.listOfAttestations) continue\n const schemaUid = toHex32(pu.propertySchemaUid)\n const att = targetReq.listOfAttestations.find(\n (a) => toHex32(a?.schema)?.toLowerCase() === schemaUid?.toLowerCase(),\n )\n // A list is re-encoded whole from its resolved slots (applyResolvedRefs), as the contract\n // leaves lists to the client (SeedPublishLib.setSeedReference fills single values only).\n if (!att?.data?.[0] || att._isList) continue\n att.data[0].data = encodeBytes32(newSeedUid as `0x${string}`)\n }\n\n const multiRequests: MultiAttestationRequest[] = request.listOfAttestations.map((att) => ({\n schema: att.schema as `0x${string}`,\n data: att.data.map((d) => ({\n recipient: (d.recipient ?? ZERO_ADDRESS) as `0x${string}`,\n expirationTime: d.expirationTime ?? 0n,\n revocable: d.revocable ?? true,\n refUID: (d.refUID ?? ZERO_BYTES32) as `0x${string}`,\n data: (d.data ?? '0x') as `0x${string}`,\n value: d.value ?? 0n,\n })),\n }))\n\n if (multiRequests.length > 0) {\n const multiTx = prepareEasMultiAttest(multiRequests)\n const result = await txSender.sendTransaction(multiTx)\n const receipt = await waitForPublishReceipt(result.transactionHash)\n if (!receipt) throw new Error('Failed to create property attestations')\n lastAttestationMs = await attestationMsFromReceipt(receipt)\n logger('created property attestations for request', i)\n const { easContractAddress } = getPublishConfig()\n const attested = getAttestedUidsFromReceipt(receipt, easContractAddress)\n for (const a of attested) {\n if (a.uid) batchExtraUids.push(a.uid)\n }\n const list = request.listOfAttestations\n const sameLen = attested.length === list.length\n await applyPropertyAttestationUidsFromPublish({\n seedLocalId: request.localId,\n attestationCreatedAtMs: lastAttestationMs ?? null,\n versionUid: newVersionUid !== ZERO_BYTES32 ? newVersionUid : null,\n pairs: attested.map((a, j) => ({\n schemaUid: a.schemaUid,\n attestationUid: a.uid,\n propertyName:\n sameLen && typeof list[j]?._propertyName === 'string' && list[j]!._propertyName !== ''\n ? list[j]!._propertyName\n : undefined,\n })),\n })\n }\n }\n\n // The publishing item gets its own request's seed (requests are not ordered root-first: a\n // related item can be request [0]); every related item records the seed created for it.\n // Seeds created above were recorded as they were attested. An item whose seed already existed\n // still gets its seed uid set and persisted here.\n persistSeedUidFromPublishResult(itemWithPersist, normalizedRequests)\n const rootRequest =\n normalizedRequests.find((r) => r.localId === item.seedLocalId) ?? normalizedRequests[0]\n if (\n rootRequest?.seedUid &&\n rootRequest.seedUid !== ZERO_BYTES32 &&\n !(item.seedLocalId && createdSeeds.has(item.seedLocalId))\n ) {\n const rootSeedMs = createdSeeds.get(rootRequest.localId)?.attestationMs ?? lastAttestationMs\n await persistSeedUidSafely(itemWithPersist, address, rootSeedMs)\n }\n\n try {\n await verifyAttestations({ normalizedRequests, item })\n } catch (err) {\n if (err instanceof AttestationVerificationError) {\n throw err\n }\n logger('verifyAttestations failed (non-verification error):', err)\n throw err\n }\n\n logger('direct EAS publish complete')\n\n void enqueueArweaveL1FinalizeJobsFromPublishContext(context)\n\n try {\n // The item's co-publish rows and those of the related drafts published with it.\n const { clearHtmlEmbeddedImageCoPublishRows } = await import('@seedprotocol/sdk')\n const published = new Set<string>([item.seedLocalId])\n for (const r of normalizedRequests) if (r?.localId) published.add(r.localId)\n for (const seedLocalId of published) await clearHtmlEmbeddedImageCoPublishRows(seedLocalId)\n } catch {\n /* best-effort cleanup */\n }\n\n const { collectPublishedBatch } = await import('../../publishedBy/collectBatchUids')\n const rootReq = rootRequest\n const publishedBatch = rootReq?.seedUid\n ? collectPublishedBatch({\n seedUid: String(rootReq.seedUid),\n versionUid: rootReq.versionUid ? String(rootReq.versionUid) : undefined,\n extraUids: batchExtraUids,\n })\n : null\n\n return { easPayload: requestData, publishedBatch }\n },\n)\n","import { Item, itemHasPublishUploadCandidates, type IItem } from '@seedprotocol/sdk'\n\n/**\n * Resolve a full Item (with getPublishUploads) by seedLocalId, polling until found.\n * Used when the input item might not have the data needed for the \"needs Arweave\" check.\n */\nconst resolveItem = async (seedLocalId: string): Promise<IItem<any>> => {\n let item: IItem<any> | undefined\n try {\n item = await Item.find({ seedLocalId } as Parameters<typeof Item.find>[0])\n } catch {\n // No-op: Error is intentionally ignored\n }\n if (item) return item\n\n return new Promise<IItem<any>>((resolve) => {\n const interval = setInterval(() => {\n Item.find({ seedLocalId } as Parameters<typeof Item.find>[0])\n .then((found: IItem<any> | undefined) => {\n if (found) {\n clearInterval(interval)\n resolve(found)\n }\n })\n .catch(() => {})\n }, 200)\n })\n}\n\n/**\n * Returns true if the item needs the Arweave upload path (reimbursement, poll, upload)\n * before creating attestations. Returns false when the item has no storage or no values\n * to upload, in which case the publish flow can skip straight to EAS.\n *\n * Uses {@link itemHasPublishUploadCandidates} (local paths / storage seeds only) so we do not\n * create Arweave transactions or call the network here — {@link getPublishUploads} builds txs\n * and can throw (e.g. gateway unreachable) even when uploads are required.\n */\nexport async function itemNeedsArweaveUpload(item: IItem<any>): Promise<boolean> {\n const usedPassedItem = typeof item.getPublishUploads === 'function'\n const resolved = usedPassedItem\n ? item\n : await resolveItem(item.seedLocalId)\n const needs = await itemHasPublishUploadCandidates(resolved)\n return needs\n}\n","import type { PublishMachineContext } from '../../../types'\n\ntype FromCallbackInput<T> = { context: T; event?: unknown }\nimport { EventObject, fromCallback } from 'xstate'\nimport { isContractDeployed } from '~/helpers/chainClient'\nimport { itemNeedsArweaveUpload } from '../helpers/itemNeedsArweave'\nimport { ensureEasSchemasForItem } from '../helpers/ensureEasSchemas'\nimport {\n assertLocalDbChain,\n getUnpublishedRelatedItems,\n isItemOwned,\n RelatedItemUnpublishedError,\n validateItemForPublish,\n} from '@seedprotocol/sdk'\nimport { getPublishConfig } from '~/config'\nimport { getPublishChainName } from '../../../helpers/chainConfig'\nimport { verifyPublishChain } from '../../../helpers/verifyPublishChain'\nimport { ManagedAccountPublishError } from '../../../errors'\n\nconst activePublishProcesses = new Set<string>()\n\nasync function resolveAttestationStrategy(publisherAddress: string): Promise<'multiPublish' | 'directEas'> {\n const cfg = getPublishConfig()\n if (cfg.useDirectEas) return 'directEas'\n if (cfg.useModularExecutor) return 'multiPublish'\n const deployed = await isContractDeployed(publisherAddress)\n return deployed ? 'multiPublish' : 'directEas'\n}\n\n/**\n * Direct EAS is for EOAs (and `useDirectEas`). A publisher with no bytecode that is really an\n * undeployed smart account, or that the wallet does not send as, is refused rather than attested\n * one transaction per Seed from the wrong path.\n */\nasync function refuseUndeployedSmartAccount(\n publisherAddress: string,\n wallet: Partial<import('~/helpers/seedSigner').PublishWallet> | undefined,\n): Promise<Error | null> {\n // Loaded on this branch only: it pulls in the factory contract helpers.\n const { undeployedPublisherProblem } = await import('../helpers/undeployedSmartAccount')\n const problem = await undeployedPublisherProblem(publisherAddress, wallet)\n if (problem === 'undeployed_smart_account') {\n return new ManagedAccountPublishError(\n `The publishing smart account ${publisherAddress} is not deployed on ${getPublishChainName()} yet. Deploy it first (your wallet's setup flow, or deploySmartWalletContract from @seedprotocol/publish/thirdweb), then publish again.`,\n 'MANAGED_ACCOUNT_NOT_DEPLOYED',\n publisherAddress,\n )\n }\n if (problem === 'sender_is_not_publisher') {\n return new Error(\n `The publish wallet sends as ${wallet?.txSender?.address}, not as the publisher ${publisherAddress}, which has no contract deployed on ${getPublishChainName()}. Attesting directly to EAS would record the wrong attester. Connect the publisher's wallet, or deploy the publisher's smart account first.`,\n )\n }\n return null\n}\n\nexport const checking = fromCallback<EventObject, FromCallbackInput<PublishMachineContext>>(\n ({ sendBack, input: { context } }) => {\n const { item, account, wallet, publishMode, address } = context\n\n const _check = async () => {\n const owned = await isItemOwned(item)\n if (!owned) {\n sendBack({ type: 'notOwner' })\n return\n }\n\n if (activePublishProcesses.has(item.seedLocalId)) {\n sendBack({\n type: 'redundantPublishProcess',\n })\n return\n }\n\n activePublishProcesses.add(item.seedLocalId)\n\n try {\n // The local DB must hold data from the chain we are about to attest on.\n await assertLocalDbChain()\n // RPC chain id and contract deployments; cached after the first success.\n await verifyPublishChain()\n\n // References to unpublished (revoked) items fail the publish before schemas are\n // registered or anything is uploaded; validateItemForPublish below reports the same.\n const unpublishedRelatedItems = await getUnpublishedRelatedItems(item, {\n publishMode: publishMode ?? 'patch',\n })\n if (unpublishedRelatedItems.length > 0) {\n activePublishProcesses.delete(item.seedLocalId)\n sendBack({\n type: 'validationFailed',\n errors: new RelatedItemUnpublishedError(unpublishedRelatedItems).validationErrors,\n })\n return\n }\n\n const publishWallet = wallet ?? account\n if (publishWallet) {\n await ensureEasSchemasForItem(\n item,\n publishWallet as import('~/helpers/seedSigner').PublishWallet,\n { managedAddress: typeof address === 'string' ? address : undefined },\n )\n }\n\n const validation = await (validateItemForPublish as any)(item, [], {\n publishMode: publishMode ?? 'patch',\n })\n if (!validation.isValid) {\n activePublishProcesses.delete(item.seedLocalId)\n sendBack({ type: 'validationFailed', errors: validation.errors })\n return\n }\n\n if (!address || typeof address !== 'string' || !address.trim()) {\n activePublishProcesses.delete(item.seedLocalId)\n sendBack({\n type: 'validationFailed',\n errors: [{ message: 'No publisher address for publish. Connect a wallet and try again.' }],\n })\n return\n }\n\n let attestationStrategy: 'multiPublish' | 'directEas'\n try {\n attestationStrategy = await resolveAttestationStrategy(address.trim())\n } catch (cause) {\n activePublishProcesses.delete(item.seedLocalId)\n sendBack({\n type: 'checkingFailed',\n error: new Error(\n `Could not verify whether the publisher is a deployed contract on ${getPublishChainName()}. Check your RPC connection and retry.`,\n { cause },\n ),\n })\n return\n }\n\n if (attestationStrategy === 'directEas' && !getPublishConfig().useDirectEas) {\n const refusal = await refuseUndeployedSmartAccount(\n address.trim(),\n (wallet ?? account) as Partial<import('~/helpers/seedSigner').PublishWallet> | undefined,\n )\n if (refusal) {\n activePublishProcesses.delete(item.seedLocalId)\n sendBack({ type: 'checkingFailed', error: refusal })\n return\n }\n }\n\n const needsArweave = await itemNeedsArweaveUpload(item)\n const useBundler = getPublishConfig().useArweaveBundler\n const payload = { attestationStrategy } as const\n if (needsArweave) {\n if (useBundler) {\n sendBack({ type: 'validPublishProcessBundler', ...payload })\n } else {\n sendBack({ type: 'validPublishProcess', ...payload })\n }\n } else {\n sendBack({ type: 'skipArweave', ...payload })\n }\n } catch (err) {\n activePublishProcesses.delete(item.seedLocalId)\n console.error('[checking] failed', err)\n sendBack({\n type: 'checkingFailed',\n error: err instanceof Error ? err : new Error(String(err)),\n })\n }\n }\n\n _check().catch((err) => {\n activePublishProcesses.delete(item.seedLocalId)\n console.error('[checking] unhandled rejection', err)\n sendBack({\n type: 'checkingFailed',\n error: err instanceof Error ? err : new Error(String(err)),\n })\n })\n\n return () => {\n activePublishProcesses.delete(item.seedLocalId)\n }\n },\n)\n","/**\n * Rough Optimism L2 gas for Seed `multiPublish` / EAS attestations.\n * These are heuristics for a USD quote, not `eth_estimateGas`.\n */\nexport const PUBLISH_GAS_HEURISTICS = {\n BASE: 80_000n,\n NEW_SEED: 120_000n,\n NEW_VERSION: 80_000n,\n ATTESTATION: 55_000n,\n} as const\n\nexport function heuristicPublishGas(work: {\n newSeedCount: number\n newVersionCount: number\n attestationCount: number\n}): bigint {\n return (\n PUBLISH_GAS_HEURISTICS.BASE +\n PUBLISH_GAS_HEURISTICS.NEW_SEED * BigInt(work.newSeedCount) +\n PUBLISH_GAS_HEURISTICS.NEW_VERSION * BigInt(work.newVersionCount) +\n PUBLISH_GAS_HEURISTICS.ATTESTATION * BigInt(work.attestationCount)\n )\n}\n","import { getPublishConfig } from '~/config'\n\nexport type TokenPrices = {\n ethUsd: number\n arUsd: number\n fetchedAt: number\n}\n\nconst TTL_MS = 60_000\n\nlet cache: TokenPrices | null = null\nlet inflight: Promise<TokenPrices> | null = null\n\nfunction readConfigGetter(): (() => Promise<{ ethUsd: number; arUsd: number }>) | undefined {\n try {\n return getPublishConfig().getTokenPrices\n } catch {\n return undefined\n }\n}\n\nexport async function fetchCoinbaseSpot(symbol: 'ETH' | 'AR'): Promise<number> {\n const res = await fetch(`https://api.coinbase.com/v2/prices/${symbol}-USD/spot`)\n if (!res.ok) {\n throw new Error(`Coinbase ${symbol}-USD spot failed: ${res.status}`)\n }\n const body = (await res.json()) as { data?: { amount?: string } }\n const n = Number(body.data?.amount)\n if (!Number.isFinite(n) || n <= 0) {\n throw new Error(`Invalid ${symbol} USD price`)\n }\n return n\n}\n\nasync function fetchDefaultTokenPrices(): Promise<{ ethUsd: number; arUsd: number }> {\n const [ethUsd, arUsd] = await Promise.all([\n fetchCoinbaseSpot('ETH'),\n fetchCoinbaseSpot('AR'),\n ])\n return { ethUsd, arUsd }\n}\n\n/** Process-wide ETH/USD + AR/USD cache (60s). Failed refresh keeps the last good values. */\nexport async function getCachedTokenPrices(options?: {\n forceRefresh?: boolean\n}): Promise<TokenPrices> {\n const now = Date.now()\n if (!options?.forceRefresh && cache && now - cache.fetchedAt < TTL_MS) {\n return cache\n }\n if (inflight && !options?.forceRefresh) {\n return inflight\n }\n\n inflight = (async () => {\n try {\n const getter = readConfigGetter()\n const prices = getter ? await getter() : await fetchDefaultTokenPrices()\n const next: TokenPrices = {\n ethUsd: prices.ethUsd,\n arUsd: prices.arUsd,\n fetchedAt: Date.now(),\n }\n cache = next\n return next\n } catch (err) {\n if (cache) return cache\n throw err\n } finally {\n inflight = null\n }\n })()\n\n return inflight\n}\n\nexport function resetTokenPriceCache(): void {\n cache = null\n inflight = null\n}\n","import { getArweave } from '~/helpers/blockchain'\nimport { getPublishPublicClient } from '~/helpers/chainClient'\nimport { getCachedTokenPrices, resetTokenPriceCache, type TokenPrices } from './tokenPrices'\n\nexport type MarketRates = TokenPrices & {\n gasPriceWei: bigint\n winstonPerByte: number\n}\n\nconst TTL_MS = 60_000\nconst ARWEAVE_PRICE_REF_BYTES = 1_000_000\n\nlet cache: MarketRates | null = null\nlet inflight: Promise<MarketRates> | null = null\n\nasync function fetchGasPriceWei(): Promise<bigint> {\n return getPublishPublicClient().getGasPrice()\n}\n\nasync function fetchWinstonPerByte(): Promise<number> {\n const winston = BigInt(\n await getArweave().transactions.getPrice(ARWEAVE_PRICE_REF_BYTES),\n )\n return Number(winston) / ARWEAVE_PRICE_REF_BYTES\n}\n\n/** Token prices + L2 gas + AR winston/byte, shared 60s TTL. */\nexport async function getCachedMarketRates(options?: {\n forceRefresh?: boolean\n}): Promise<MarketRates> {\n const now = Date.now()\n if (!options?.forceRefresh && cache && now - cache.fetchedAt < TTL_MS) {\n return cache\n }\n if (inflight && !options?.forceRefresh) {\n return inflight\n }\n\n inflight = (async () => {\n try {\n const [prices, gasPriceWei, winstonPerByte] = await Promise.all([\n getCachedTokenPrices({ forceRefresh: options?.forceRefresh }),\n fetchGasPriceWei(),\n fetchWinstonPerByte(),\n ])\n const next: MarketRates = {\n ...prices,\n gasPriceWei,\n winstonPerByte,\n fetchedAt: Date.now(),\n }\n cache = next\n return next\n } catch (err) {\n if (cache) return cache\n throw err\n } finally {\n inflight = null\n }\n })()\n\n return inflight\n}\n\nexport function resetMarketRateCache(): void {\n cache = null\n inflight = null\n resetTokenPriceCache()\n}\n\nexport { ARWEAVE_PRICE_REF_BYTES }\n","import type { IItem } from '@seedprotocol/sdk'\nimport { getPublishConfig } from '~/config'\nimport { resolvePublishPayment } from '~/payment'\nimport { heuristicPublishGas } from './gasHeuristics'\nimport { getCachedMarketRates, type MarketRates } from './marketRates'\nimport type { EstimatePublishCostOptions, PublishCostEstimate, PublishWorkSummary } from './types'\n\nconst WINSTON_PER_AR = 1e12\nconst WEI_PER_ETH = 1e18\n\n/** Who pays, from the same resolution the publish flow uses ({@link resolvePublishPayment}). */\nfunction readPublishFlags(): { evmUserPays: boolean; arweaveUserPays: boolean; arweavePath: 'l1' | 'bundler' } {\n try {\n const payment = resolvePublishPayment(getPublishConfig())\n return {\n evmUserPays: payment.gas.payer === 'user',\n arweaveUserPays: payment.storage.payer === 'user',\n arweavePath: payment.storage.path,\n }\n } catch {\n return { evmUserPays: true, arweaveUserPays: false, arweavePath: 'l1' }\n }\n}\n\nfunction roundUsd(n: number): number {\n return Math.round(n * 100) / 100\n}\n\nexport function combinePublishCostEstimate(\n work: PublishWorkSummary,\n rates: MarketRates,\n flags?: { evmUserPays?: boolean; arweaveUserPays?: boolean; arweavePath?: 'l1' | 'bundler' },\n): PublishCostEstimate {\n const evmUserPays = flags?.evmUserPays ?? true\n const arweaveUserPays = flags?.arweaveUserPays ?? false\n const arweavePath = flags?.arweavePath ?? 'l1'\n const gas = heuristicPublishGas(work)\n const evmWei = gas * rates.gasPriceWei\n const evmEth = Number(evmWei) / WEI_PER_ETH\n const evmUsd = evmEth * rates.ethUsd\n\n const winston = Math.max(0, Math.round(work.uploadBytes * rates.winstonPerByte))\n const ar = winston / WINSTON_PER_AR\n const arUsd = ar * rates.arUsd\n\n return {\n totalUsd: roundUsd(evmUsd + arUsd),\n evm: {\n eth: evmEth.toPrecision(6),\n usd: roundUsd(evmUsd),\n gas,\n userPays: evmUserPays,\n },\n arweave: {\n ar: ar.toPrecision(6),\n usd: roundUsd(arUsd),\n bytes: work.uploadBytes,\n uploadCount: work.uploadCount,\n path: arweavePath,\n userPays: arweaveUserPays,\n },\n prices: {\n ethUsd: rates.ethUsd,\n arUsd: rates.arUsd,\n fetchedAt: rates.fetchedAt,\n },\n work,\n estimatedAt: Date.now(),\n }\n}\n\nexport async function estimatePublishCost(\n item: IItem<any>,\n options?: EstimatePublishCostOptions,\n): Promise<PublishCostEstimate> {\n const flags = readPublishFlags()\n let work = options?.work\n if (!work) {\n const { summarizePublishWork } = await import('@seedprotocol/sdk')\n work = await summarizePublishWork(item, { publishMode: options?.publishMode })\n }\n const rates = options?.rates ?? (await getCachedMarketRates())\n return combinePublishCostEstimate(work, rates, flags)\n}\n","import { fromPromise } from 'xstate'\nimport type { PublishMachineContext } from '../../../types'\nimport { getPublishConfig } from '~/config'\nimport { resolvePublishPayment } from '~/payment'\nimport { runAuthorizePublish, type PublishAuthorization } from '~/authorization'\nimport { estimatePublishCost } from '~/services/publishCost/estimatePublishCost'\n\nfunction configAuthorizePublish() {\n try {\n return getPublishConfig().authorizePublish\n } catch {\n return undefined\n }\n}\n\n/**\n * First publish step: asks `authorizePublish` (per publish, else from config) to approve before\n * anything is spent. Resolves with the authorization (its token rides along in context).\n */\nexport const authorizing = fromPromise(\n async ({ input: { context } }: { input: { context: PublishMachineContext } }): Promise<PublishAuthorization> => {\n const { item } = context\n // A publish restored from the DB has no functions in its context; fall back to the config hook.\n const authorizePublish = context.authorizePublish ?? configAuthorizePublish()\n if (!authorizePublish) return {}\n const publishMode = context.publishMode ?? 'patch'\n return runAuthorizePublish(authorizePublish, {\n item,\n seedLocalId: item.seedLocalId,\n publishMode,\n payment: resolvePublishPayment(getPublishConfig()),\n getEstimate: () => estimatePublishCost(item, { publishMode }),\n })\n },\n)\n","import type { ActorRefFrom } from 'xstate'\nimport { setup, assign } from 'xstate'\nimport {\n ArweaveTransactionInfo,\n PublishMachineContext,\n ReimbursementResponse,\n PublishUpload,\n} from '../../types'\nimport {\n createArweaveTransactions,\n createArweaveTransactionsPhase2,\n createArweaveDataItems,\n createArweaveDataItemsPhase2,\n createAttestations,\n createAttestationsDirectToEas,\n sendReimbursementRequest,\n pollForConfirmation,\n uploadData,\n uploadViaBundler,\n checking,\n authorizing,\n preparingHtmlEmbedded,\n rewritingHtmlEmbedded,\n} from './actors'\nimport {\n PublishMachineStates,\n} from '~/helpers/constants'\nimport { getPublishConfig } from '~/config'\n\n\nconst {\n SUCCESS,\n FAILURE,\n} = PublishMachineStates\n\n/** Prefer context from `checking`; fall back to `useDirectEas` for restored snapshots without `attestationStrategy`. */\nfunction attestationUsesDirectEas(context: Partial<PublishMachineContext>): boolean {\n const s = context.attestationStrategy\n if (s === 'directEas') return true\n if (s === 'multiPublish') return false\n return getPublishConfig().useDirectEas\n}\n\nfunction attestationUsesMultiPublish(context: Partial<PublishMachineContext>): boolean {\n const s = context.attestationStrategy\n if (s === 'multiPublish') return true\n if (s === 'directEas') return false\n return !getPublishConfig().useDirectEas\n}\n\n/** Extract error from event. Supports event.error (custom events like uploadError) and event.data (XState fromPromise invoke errors). */\nfunction getErrorFromEvent(event: unknown): unknown {\n const e = event as { error?: unknown; data?: unknown }\n return e.error ?? e.data\n}\n\nexport const publishMachine = setup({\n types : {\n context : {} as Partial<PublishMachineContext>,\n input : {} as Partial<PublishMachineContext> | undefined,\n },\n actors : {\n createArweaveTransactions,\n createArweaveTransactionsPhase2,\n createArweaveDataItems,\n createArweaveDataItemsPhase2,\n sendReimbursementRequest,\n pollForConfirmation,\n uploadData,\n uploadViaBundler,\n createAttestations,\n createAttestationsDirectToEas,\n checking,\n authorizing,\n preparingHtmlEmbedded,\n rewritingHtmlEmbedded,\n },\n actions : {\n /** Log error; error/errorStep are assigned per transition. Supports both event.error (custom events) and event.data (XState fromPromise invoke errors). */\n handleError : ( { event, }, ) => {\n const err = getErrorFromEvent(event,)\n if (err != null) {\n console.error(err,)\n } else {\n console.error('Unknown error (full event):', event,)\n }\n },\n assignErrorCreatingArweaveTransactions : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'creatingArweaveTransactions',\n },),\n assignErrorCreatingArweaveDataItems : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'creatingArweaveDataItems',\n },),\n assignErrorSendingReimbursementRequest : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'sendingReimbursementRequest',\n },),\n assignErrorPollingForConfirmation : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'pollingForConfirmation',\n },),\n assignErrorUploadingData : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'uploadingData',\n },),\n assignErrorPreparingHtmlEmbedded : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'preparingHtmlEmbedded',\n },),\n assignErrorRewritingHtmlEmbedded : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'rewritingHtmlEmbedded',\n },),\n assignErrorCreatingArweaveTransactionsPhase2 : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'creatingArweaveTransactionsPhase2',\n },),\n assignErrorUploadingDataPhase2 : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'uploadingDataPhase2',\n },),\n assignErrorUploadingViaBundler : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'uploadingViaBundler',\n },),\n assignErrorCreatingArweaveDataItemsPhase2 : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'creatingArweaveDataItemsPhase2',\n },),\n assignErrorUploadingViaBundlerPhase2 : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'uploadingViaBundlerPhase2',\n },),\n assignErrorCreatingAttestations : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'creatingAttestations',\n },),\n assignErrorCreatingAttestationsDirectToEas : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'creatingAttestationsDirectToEas',\n },),\n assignAccountFromRetry : assign({\n wallet : ( { event, }, ) => {\n const ev = event as { wallet?: import('~/helpers/seedSigner').PublishWallet; account?: import('~/helpers/seedSigner').PublishWallet }\n return ev.wallet ?? ev.account\n },\n account : ( { event, }, ) => {\n const ev = event as { wallet?: import('~/helpers/seedSigner').PublishWallet; account?: import('~/helpers/seedSigner').PublishWallet }\n return ev.wallet ?? ev.account\n },\n },),\n assignErrorNotOwner : assign({\n error : () => new Error('Item is read-only: you do not own this item. Only the publisher can publish.'),\n errorStep : () => 'checking',\n },),\n assignErrorValidationFailed : assign({\n error : ( { event, }, ) => {\n const ev = event as { errors?: Array<{ field?: string; message: string }> }\n const errors = ev.errors ?? []\n const message = errors.length > 0\n ? `Validation failed (${errors.length} error${errors.length === 1 ? '' : 's'}):\\n${errors.map((e) => e.message).join('\\n')}`\n : 'Validation failed'\n const err = new Error(message) as Error & { validationErrors?: typeof errors }\n err.validationErrors = errors\n return err\n },\n errorStep : () => 'checking',\n },),\n assignErrorAuthorizing : assign({\n error : ( { event, }, ) => getErrorFromEvent(event,),\n errorStep : () => 'authorizing',\n },),\n assignErrorCheckingFailed : assign({\n error : ({ event }) => {\n const ev = event as { error?: unknown }\n const e = ev.error\n return e instanceof Error ? e : new Error(String(e ?? 'Publish check failed'))\n },\n errorStep : () => 'checking',\n },),\n },\n\n},).createMachine({\n id : 'publish',\n initial : 'authorizing',\n context : ( { input, }, ) => input as PublishMachineContext,\n states : {\n // Before checking: checking can already send transactions (EAS schema registration).\n authorizing : {\n invoke : {\n src : 'authorizing',\n input : ( { context } ) => ({ context } as { context: PublishMachineContext }),\n onDone : {\n target : 'checking',\n actions : assign({ publishAuthorization : ( { event } ) => event.output }),\n },\n onError : {\n target : FAILURE,\n actions : ['assignErrorAuthorizing', 'handleError'],\n },\n },\n },\n checking : {\n on: {\n notOwner: {\n target: FAILURE,\n actions: ['assignErrorNotOwner', 'handleError'],\n },\n validationFailed: {\n target: FAILURE,\n actions: ['assignErrorValidationFailed', 'handleError'],\n },\n redundantPublishProcess: {\n target: 'stopping',\n },\n checkingFailed: {\n target: FAILURE,\n actions: ['assignErrorCheckingFailed', 'handleError'],\n },\n validPublishProcess: {\n target: 'preparingHtmlEmbedded',\n actions: assign({\n attestationStrategy: ({ event }) =>\n (event as { attestationStrategy?: PublishMachineContext['attestationStrategy'] })\n .attestationStrategy,\n }),\n },\n validPublishProcessBundler: {\n target: 'preparingHtmlEmbedded',\n actions: assign({\n attestationStrategy: ({ event }) =>\n (event as { attestationStrategy?: PublishMachineContext['attestationStrategy'] })\n .attestationStrategy,\n }),\n },\n skipArweave: [\n {\n guard: ({ context }) => attestationUsesDirectEas(context),\n target: 'creatingAttestationsDirectToEas',\n actions: assign({\n arweaveTransactions: () => [],\n publishUploads: () => [],\n attestationStrategy: ({ event }) =>\n (event as { attestationStrategy?: PublishMachineContext['attestationStrategy'] })\n .attestationStrategy,\n }),\n },\n {\n guard: ({ context }) => attestationUsesMultiPublish(context),\n target: 'creatingAttestations',\n actions: assign({\n arweaveTransactions: () => [],\n publishUploads: () => [],\n attestationStrategy: ({ event }) =>\n (event as { attestationStrategy?: PublishMachineContext['attestationStrategy'] })\n .attestationStrategy,\n }),\n },\n ],\n },\n invoke : {\n src : 'checking',\n input : ( { context } ) => ({ context } as { context: PublishMachineContext }),\n },\n },\n preparingHtmlEmbedded: {\n invoke: {\n src: 'preparingHtmlEmbedded',\n input: ({ context }) => ({ context } as { context: PublishMachineContext }),\n onDone: [\n {\n guard: () => getPublishConfig().useArweaveBundler,\n target: 'creatingArweaveDataItems',\n actions: assign({\n htmlEmbeddedDeferredHtmlSeedLocalIds: ({ event }) =>\n (event.output as { deferredHtmlSeedLocalIds: string[] }).deferredHtmlSeedLocalIds,\n }),\n },\n {\n target: 'creatingArweaveTransactions',\n actions: assign({\n htmlEmbeddedDeferredHtmlSeedLocalIds: ({ event }) =>\n (event.output as { deferredHtmlSeedLocalIds: string[] }).deferredHtmlSeedLocalIds,\n }),\n },\n ],\n onError: {\n target: FAILURE,\n actions: ['assignErrorPreparingHtmlEmbedded', 'handleError'],\n },\n },\n },\n creatingArweaveTransactions : {\n invoke : {\n src : 'createArweaveTransactions',\n input : ( { context, event } ) => ({ context, event } as { context: PublishMachineContext; event: unknown }),\n onDone : {\n target : 'sendingReimbursementRequest',\n actions : assign({\n arweaveTransactions : ( { event, }, ) => event.output.arweaveTransactions as ArweaveTransactionInfo[],\n publishUploads : ( { event, }, ) => event.output.publishUploads as PublishUpload[],\n },),\n },\n onError : {\n target : 'failure',\n actions : [ 'assignErrorCreatingArweaveTransactions', 'handleError', ],\n },\n },\n },\n creatingArweaveDataItems : {\n invoke : {\n src : 'createArweaveDataItems',\n input : ( { context, event } ) => ({ context, event } as { context: PublishMachineContext; event: unknown }),\n onDone : {\n target : 'uploadingViaBundler',\n actions : assign({\n arweaveTransactions : ( { event, }, ) => event.output.arweaveTransactions as ArweaveTransactionInfo[],\n publishUploads : ( { event, }, ) => event.output.publishUploads as PublishUpload[],\n signedDataItems : ( { event, }, ) => (event.output as { signedDataItems?: { id: string; raw: Uint8Array }[] }).signedDataItems,\n },),\n },\n onError : {\n target : 'failure',\n actions : [ 'assignErrorCreatingArweaveDataItems', 'handleError', ],\n },\n },\n },\n sendingReimbursementRequest : {\n invoke : {\n src : 'sendReimbursementRequest',\n input : ( { context, event } ) => ({ context, event } as { context: PublishMachineContext; event: unknown }),\n onDone : {\n target : 'pollingForConfirmation',\n actions : assign({\n requestResponse : ( { event, }, ) => event.output as ReimbursementResponse,\n reimbursementTransactionId : ( { event, }, ) => (event.output as ReimbursementResponse).transactionId as string,\n },),\n },\n onError : {\n target : 'failure',\n actions : [ 'assignErrorSendingReimbursementRequest', 'handleError', ],\n },\n },\n },\n pollingForConfirmation : {\n invoke : {\n src : 'pollForConfirmation',\n input : ( { context, event } ) => ({ context, event } as { context: PublishMachineContext; event: unknown }),\n onDone : {\n target : 'uploadingData',\n actions : assign({\n reimbursementConfirmed : true,\n },),\n },\n onError : {\n target : 'failure',\n actions : [ 'assignErrorPollingForConfirmation', 'handleError', ],\n },\n }\n },\n uploadingViaBundler : {\n on : {\n uploadComplete : [\n {\n guard: ({ context }) => attestationUsesDirectEas(context),\n target: 'creatingAttestationsDirectToEas',\n actions: assign({\n completionPercentage: 100,\n signedDataItems: () => undefined,\n arweaveUploadData: () => undefined,\n }),\n },\n {\n guard: (args) =>\n ((args.context?.htmlEmbeddedDeferredHtmlSeedLocalIds?.length ?? 0) > 0),\n target: 'rewritingHtmlEmbedded',\n actions: assign({\n htmlEmbeddedPhase1PublishUploads: ({ context }) =>\n (context.publishUploads ?? []) as PublishUpload[],\n htmlEmbeddedPhase1ArweaveTransactions: ({ context }) =>\n (context.arweaveTransactions ?? []) as ArweaveTransactionInfo[],\n signedDataItems: () => undefined,\n arweaveUploadData: () => undefined,\n }),\n },\n {\n guard: ({ context }) => attestationUsesMultiPublish(context),\n target: 'creatingAttestations',\n actions: assign({\n completionPercentage: 100,\n signedDataItems: () => undefined,\n arweaveUploadData: () => undefined,\n }),\n },\n ],\n uploadError : {\n target : 'failure',\n actions : [ 'assignErrorUploadingViaBundler', 'handleError', ],\n },\n },\n invoke : {\n src : 'uploadViaBundler',\n input : ( { context } ) => ({ context }) as { context: PublishMachineContext },\n },\n },\n creatingArweaveDataItemsPhase2: {\n invoke: {\n src: 'createArweaveDataItemsPhase2',\n input: ({ context, event }) =>\n ({ context, event }) as { context: PublishMachineContext; event: unknown },\n onDone: {\n target: 'uploadingViaBundlerPhase2',\n actions: assign({\n arweaveTransactions: ({ event }) =>\n (event.output as { arweaveTransactions: ArweaveTransactionInfo[] }).arweaveTransactions,\n publishUploads: ({ event }) =>\n (event.output as { publishUploads: PublishUpload[] }).publishUploads,\n signedDataItems: ({ event }) =>\n (event.output as { signedDataItems?: PublishMachineContext['signedDataItems'] })\n .signedDataItems,\n uploaderState: () => undefined,\n currentTransactionIndex: () => undefined,\n }),\n },\n onError: {\n target: FAILURE,\n actions: ['assignErrorCreatingArweaveDataItemsPhase2', 'handleError'],\n },\n },\n },\n uploadingViaBundlerPhase2: {\n on: {\n uploadComplete: [\n {\n guard: ({ context }) => attestationUsesDirectEas(context),\n target: 'creatingAttestationsDirectToEas',\n actions: assign({\n completionPercentage: 100,\n signedDataItems: () => undefined,\n arweaveUploadData: () => undefined,\n }),\n },\n {\n guard: ({ context }) => attestationUsesMultiPublish(context),\n target: 'creatingAttestations',\n actions: assign({\n completionPercentage: 100,\n signedDataItems: () => undefined,\n arweaveUploadData: () => undefined,\n publishUploads: ({ context }) =>\n [\n ...((context.htmlEmbeddedPhase1PublishUploads ?? []) as PublishUpload[]),\n ...((context.publishUploads ?? []) as PublishUpload[]),\n ],\n arweaveTransactions: ({ context }) =>\n [\n ...((context.htmlEmbeddedPhase1ArweaveTransactions ?? []) as ArweaveTransactionInfo[]),\n ...((context.arweaveTransactions ?? []) as ArweaveTransactionInfo[]),\n ],\n }),\n },\n ],\n uploadError: {\n target: FAILURE,\n actions: ['assignErrorUploadingViaBundlerPhase2', 'handleError'],\n },\n },\n invoke: {\n src: 'uploadViaBundler',\n input: ({ context }) => ({ context }) as { context: PublishMachineContext },\n },\n },\n uploadingData : {\n on : {\n updatePercentage : {\n actions : assign({\n completionPercentage : ( { event, }, ) => {\n const ev = event as { completionPercentage?: number }\n return ev.completionPercentage as number\n },\n uploaderState : ( { event, }, ) =>\n (event as { uploaderState?: PublishMachineContext['uploaderState'] }).uploaderState,\n currentTransactionIndex : ( { event, }, ) =>\n (event as { currentTransactionIndex?: number }).currentTransactionIndex,\n },),\n },\n uploadComplete : [\n {\n guard: ({ context }) => attestationUsesDirectEas(context),\n target: 'creatingAttestationsDirectToEas',\n actions: assign({\n completionPercentage: 100,\n }),\n },\n {\n guard: (args) =>\n ((args.context?.htmlEmbeddedDeferredHtmlSeedLocalIds?.length ?? 0) > 0),\n target: 'rewritingHtmlEmbedded',\n actions: assign({\n htmlEmbeddedPhase1PublishUploads: ({ context }) =>\n (context.publishUploads ?? []) as PublishUpload[],\n htmlEmbeddedPhase1ArweaveTransactions: ({ context }) =>\n (context.arweaveTransactions ?? []) as ArweaveTransactionInfo[],\n }),\n },\n {\n guard: ({ context }) => attestationUsesMultiPublish(context),\n target: 'creatingAttestations',\n actions: assign({\n completionPercentage: 100,\n }),\n },\n ],\n uploadError : {\n target : 'failure',\n actions : [ 'assignErrorUploadingData', 'handleError', ],\n },\n },\n invoke : {\n src : 'uploadData',\n input : ( { context } ) => ({ context }) as { context: PublishMachineContext },\n },\n },\n rewritingHtmlEmbedded: {\n invoke: {\n src: 'rewritingHtmlEmbedded',\n input: ({ context }) => ({ context }) as { context: PublishMachineContext },\n onDone: [\n {\n guard: () => !getPublishConfig().useArweaveBundler,\n target: 'creatingArweaveTransactionsPhase2',\n },\n {\n guard: () => getPublishConfig().useArweaveBundler,\n target: 'creatingArweaveDataItemsPhase2',\n },\n ],\n onError: {\n target: FAILURE,\n actions: ['assignErrorRewritingHtmlEmbedded', 'handleError'],\n },\n },\n },\n creatingArweaveTransactionsPhase2: {\n invoke: {\n src: 'createArweaveTransactionsPhase2',\n input: ({ context, event }) =>\n ({ context, event }) as { context: PublishMachineContext; event: unknown },\n onDone: {\n target: 'uploadingDataPhase2',\n actions: assign({\n arweaveTransactions: ({ event }) =>\n (event.output as { arweaveTransactions: ArweaveTransactionInfo[] }).arweaveTransactions,\n publishUploads: ({ event }) =>\n (event.output as { publishUploads: PublishUpload[] }).publishUploads,\n uploaderState: () => undefined,\n currentTransactionIndex: () => undefined,\n }),\n },\n onError: {\n target: FAILURE,\n actions: ['assignErrorCreatingArweaveTransactionsPhase2', 'handleError'],\n },\n },\n },\n uploadingDataPhase2: {\n on: {\n updatePercentage: {\n actions: assign({\n completionPercentage: ({ event }) => {\n const ev = event as { completionPercentage?: number }\n return ev.completionPercentage as number\n },\n uploaderState: ({ event }) =>\n (event as { uploaderState?: PublishMachineContext['uploaderState'] }).uploaderState,\n currentTransactionIndex: ({ event }) =>\n (event as { currentTransactionIndex?: number }).currentTransactionIndex,\n }),\n },\n uploadComplete: [\n {\n guard: ({ context }) => attestationUsesDirectEas(context),\n target: 'creatingAttestationsDirectToEas',\n actions: assign({\n completionPercentage: 100,\n }),\n },\n {\n guard: ({ context }) => attestationUsesMultiPublish(context),\n target: 'creatingAttestations',\n actions: assign({\n completionPercentage: 100,\n publishUploads: ({ context }) =>\n [\n ...((context.htmlEmbeddedPhase1PublishUploads ?? []) as PublishUpload[]),\n ...((context.publishUploads ?? []) as PublishUpload[]),\n ],\n arweaveTransactions: ({ context }) =>\n [\n ...((context.htmlEmbeddedPhase1ArweaveTransactions ?? []) as ArweaveTransactionInfo[]),\n ...((context.arweaveTransactions ?? []) as ArweaveTransactionInfo[]),\n ],\n }),\n },\n ],\n uploadError: {\n target: FAILURE,\n actions: ['assignErrorUploadingDataPhase2', 'handleError'],\n },\n },\n invoke: {\n src: 'uploadData',\n input: ({ context }) => ({ context }) as { context: PublishMachineContext },\n },\n },\n creatingAttestations : {\n invoke : {\n src : 'createAttestations',\n input : ( { context, event } ) => ({ context, event } as { context: PublishMachineContext; event: unknown }),\n onDone : {\n target : SUCCESS,\n actions : assign({\n easPayload : ( { event, }, ) => (event.output as { easPayload?: unknown })?.easPayload,\n publishedBatch : ( { event, }, ) =>\n (event.output as { publishedBatch?: PublishMachineContext['publishedBatch'] })\n ?.publishedBatch ?? null,\n },),\n },\n onError : {\n target : 'attestationFailureRecoverable',\n actions : [ 'assignErrorCreatingAttestations', 'handleError', ],\n },\n },\n },\n attestationFailureRecoverable : {\n on : {\n retry : {\n target : 'creatingAttestations',\n actions : [ 'assignAccountFromRetry', ],\n },\n },\n },\n creatingAttestationsDirectToEas : {\n invoke : {\n src : 'createAttestationsDirectToEas',\n input : ( { context, event } ) => ({ context, event } as { context: PublishMachineContext; event: unknown }),\n onDone : {\n target : SUCCESS,\n actions : assign({\n easPayload : ( { event, }, ) => (event.output as { easPayload?: unknown })?.easPayload,\n publishedBatch : ( { event, }, ) =>\n (event.output as { publishedBatch?: PublishMachineContext['publishedBatch'] })\n ?.publishedBatch ?? null,\n },),\n },\n onError : {\n target : 'attestationFailureRecoverableDirectToEas',\n actions : [ 'assignErrorCreatingAttestationsDirectToEas', 'handleError', ],\n },\n },\n },\n attestationFailureRecoverableDirectToEas : {\n on : {\n retry : {\n target : 'creatingAttestationsDirectToEas',\n actions : [ 'assignAccountFromRetry', ],\n },\n },\n },\n stopping: {\n entry: ( { context }: { context: Partial<PublishMachineContext> } ) => {\n console.log(`Actor for ${context.item?.seedLocalId} stopped`,)\n },\n type: 'final',\n },\n [SUCCESS] : {\n entry: ({ context }: { context: Partial<PublishMachineContext> }) => {\n const batch = context.publishedBatch\n const onPublished = context.onPublished\n if (!onPublished || !batch?.seedUid) return\n const seedLocalId = context.item?.seedLocalId\n if (!seedLocalId) return\n void Promise.resolve(\n onPublished({\n seedLocalId,\n seedUid: batch.seedUid,\n versionUid: batch.versionUid,\n attestationUids: batch.attestationUids,\n }),\n ).catch((err) => {\n console.warn('[publish] onPublished callback failed:', err)\n })\n },\n type : 'final',\n },\n [FAILURE] : {\n entry: ({ context }: { context: Partial<PublishMachineContext> }) => {\n },\n type : 'final',\n },\n },\n})\n\nexport type PublishActor = ActorRefFrom<typeof publishMachine>\n","/**\n * Holds a reference to the PublishManager service to avoid circular imports.\n * Subscribe actor uses this to call savePublish and onPublishDone.\n */\nexport type PublishManagerRef = {\n savePublish: (\n seedLocalId: string,\n publishProcess: { getPersistedSnapshot?: () => unknown; getSnapshot: () => unknown },\n options?: { triggerPublishDone?: boolean }\n ) => void\n onPublishDone: (seedLocalId: string) => void\n removeSubscription: (seedLocalId: string) => void\n}\n\nlet ref: PublishManagerRef | null = null\n\nexport function setPublishManagerRef(r: PublishManagerRef) {\n ref = r\n}\n\nexport function getPublishManagerRef(): PublishManagerRef | null {\n return ref\n}\n","import { fromCallback, EventObject } from 'xstate'\nimport { getPublishManagerRef } from '../publishManagerRef'\nimport {\n LONG_RUNNING_PUBLISH_STATES,\n PERIODIC_SAVE_INTERVAL_MS,\n} from '~/helpers/constants'\nimport debug from 'debug'\n\nconst logger = debug('seedProtocol:services:PublishManager:actors:subscribe')\n\nfunction getStateValue(snapshot: { value?: unknown }): string {\n const v = snapshot.value\n if (typeof v === 'string') return v\n if (v && typeof v === 'object') {\n const keys = Object.keys(v)\n return (keys[0] ?? '') as string\n }\n return ''\n}\n\nfunction isLongRunningState(stateValue: string): boolean {\n return LONG_RUNNING_PUBLISH_STATES.includes(stateValue as (typeof LONG_RUNNING_PUBLISH_STATES)[number])\n}\n\nexport interface SubscribeInput {\n publishProcess: import('xstate').ActorRef<any, any>\n seedLocalId: string\n}\n\nexport const subscribe = fromCallback<EventObject, SubscribeInput>(\n ({ receive, input: { publishProcess, seedLocalId } }) => {\n const managerRef = getPublishManagerRef()\n let periodicSaveIntervalId: ReturnType<typeof setInterval> | null = null\n\n const clearPeriodicSave = () => {\n if (periodicSaveIntervalId != null) {\n clearInterval(periodicSaveIntervalId)\n periodicSaveIntervalId = null\n }\n }\n\n const startPeriodicSaveIfNeeded = (snapshot: { value?: unknown }) => {\n const stateValue = getStateValue(snapshot)\n if (isLongRunningState(stateValue) && periodicSaveIntervalId == null && managerRef) {\n periodicSaveIntervalId = setInterval(() => {\n // Timer callbacks can run after transition to a non-long-running state or after\n // completion (clearInterval does not remove an already-queued task). Never persist\n // in that case — matches ~30s regressions seen as \"Creating attestations\" again.\n try {\n const live = publishProcess.getSnapshot() as { status?: string; value?: unknown }\n if (live.status === 'done') {\n clearPeriodicSave()\n return\n }\n const liveValue = getStateValue(live)\n if (!isLongRunningState(liveValue)) {\n clearPeriodicSave()\n return\n }\n } catch {\n return\n }\n managerRef?.savePublish(seedLocalId, publishProcess)\n }, PERIODIC_SAVE_INTERVAL_MS)\n } else if (!isLongRunningState(stateValue)) {\n clearPeriodicSave()\n }\n }\n\n const subscription = publishProcess.subscribe(async (snapshot) => {\n logger('Publish state:', snapshot.value)\n if (managerRef) {\n if (snapshot.status === 'done') {\n clearPeriodicSave()\n // Save first, then onPublishDone is triggered only after save completes (via SAVE_PUBLISH_DONE)\n managerRef.savePublish(seedLocalId, publishProcess, { triggerPublishDone: true })\n } else {\n managerRef.savePublish(seedLocalId, publishProcess)\n startPeriodicSaveIfNeeded(snapshot)\n }\n }\n })\n\n receive(({ type }) => {\n if (type === 'UNSUBSCRIBE') {\n logger('Received UNSUBSCRIBE event')\n clearPeriodicSave()\n subscription.unsubscribe()\n managerRef?.removeSubscription(seedLocalId)\n }\n })\n }\n)\n","import type { ActorRef } from 'xstate'\n\nconst resolvers = new Map<number, (actor: ActorRef<any, any> | undefined) => void>()\nlet nextToken = 1\n\n/** Register a resolver for one CREATE_PUBLISH. The token travels on the event. */\nexport function registerCreatePublishResolver(\n resolve: (actor: ActorRef<any, any> | undefined) => void,\n): number {\n const token = nextToken++\n resolvers.set(token, resolve)\n return token\n}\n\n/** Resolve a CREATE_PUBLISH promise. `undefined` means the process was not spawned. */\nexport function settleCreatePublish(\n token: number | undefined,\n actor: ActorRef<any, any> | undefined,\n): void {\n if (token == null) return\n const resolve = resolvers.get(token)\n if (!resolve) return\n resolvers.delete(token)\n resolve(actor)\n}\n","import type { Item } from '@seedprotocol/sdk'\nimport { enqueueActions } from 'xstate'\nimport { getPublishConfig } from '~/config'\nimport {\n isPublishWallet,\n isSeedSigner,\n type PublishWallet,\n type SeedSigner,\n} from '~/helpers/seedSigner'\nimport { ethers } from 'ethers'\nimport { publishMachine } from '../../publish'\nimport { subscribe } from '../actors/subscribe'\nimport { getPublishWallet } from '~/helpers/publishWalletRegistry'\nimport { settleCreatePublish } from '../createPublishResult'\n\nfunction coerceWallet(account: unknown): PublishWallet | undefined {\n if (!account) return undefined\n if (isPublishWallet(account)) return account\n // Legacy: SeedSigner alone cannot send — try registry wallet\n if (isSeedSigner(account)) {\n const registered = getPublishWallet()\n if (registered && registered.signer.address.toLowerCase() === account.address.toLowerCase()) {\n return registered\n }\n throw new Error(\n '@seedprotocol/publish: createPublish requires a PublishWallet (signer + txSender). Use fromEthersWallet, fromEip1193Provider, or fromThirdwebAccount.',\n )\n }\n throw new Error(\n '@seedprotocol/publish: createPublish account must be a PublishWallet. Thirdweb Account must be wrapped with fromThirdwebAccount from @seedprotocol/publish/thirdweb.',\n )\n}\n\nfunction coerceDataItemSigner(\n signer: import('~/config').CreatePublishOptions['dataItemSigner'],\n): SeedSigner | ethers.Wallet | undefined {\n if (!signer) return undefined\n if (signer instanceof ethers.Wallet) return signer\n if (isPublishWallet(signer)) return signer.signer\n if (isSeedSigner(signer)) return signer\n return undefined\n}\n\nexport const createPublish = enqueueActions(({ event, enqueue }) => {\n const ev = event as unknown as {\n item: Item<any>\n address?: string\n account?: unknown\n options?: import('~/config').CreatePublishOptions\n createToken?: number\n }\n const { item, address, account, options, createToken } = ev\n\n const hasAddress = address != null && typeof address === 'string' && address.trim().length > 0\n if (!hasAddress) {\n console.warn('[createPublish] No valid wallet address; skipping spawn.')\n settleCreatePublish(createToken, undefined)\n return\n }\n\n enqueue.assign(({ context, spawn }) => {\n const { publishProcesses } = context\n if (publishProcesses && publishProcesses.has(item.seedLocalId)) {\n console.warn(`Publish process with seedLocalId \"${item.seedLocalId}\" already exists.`)\n settleCreatePublish(createToken, undefined)\n return context\n }\n const publishRunId =\n typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'\n ? crypto.randomUUID()\n : `run_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`\n\n const publishCfg = getPublishConfig()\n const arweaveUploadTags = [\n ...(publishCfg.arweaveUploadTags ?? []),\n ...(options?.arweaveUploadTags ?? []),\n ]\n\n const wallet = coerceWallet(account) ?? getPublishWallet() ?? undefined\n\n const publishProcess = spawn(publishMachine, {\n input: {\n item,\n address: address as string,\n wallet,\n account: wallet,\n modelName: item.modelName,\n schemaId: item.schemaUid,\n signDataItems: options?.signDataItems,\n dataItemSigner: coerceDataItemSigner(options?.dataItemSigner),\n signArweaveTransactions: options?.signArweaveTransactions,\n arweaveJwk: options?.arweaveJwk,\n publishMode: options?.publishMode ?? 'patch',\n publishRunId,\n arweaveUploadTags: arweaveUploadTags.length ? arweaveUploadTags : undefined,\n htmlEmbeddedDataUriPolicy:\n options?.htmlEmbeddedDataUriPolicy ??\n publishCfg.htmlEmbeddedDataUriPolicy ??\n 'materialize',\n onPublished: options?.onPublished ?? publishCfg.onPublished,\n authorizePublish: options?.authorizePublish ?? publishCfg.authorizePublish,\n },\n })\n\n publishProcesses.set(item.seedLocalId, publishProcess)\n const settledPublishes = new Map(context.settledPublishes)\n settledPublishes.delete(item.seedLocalId)\n settleCreatePublish(createToken, publishProcess)\n\n return {\n ...context,\n publishProcesses,\n settledPublishes,\n }\n })\n\n enqueue.assign(({ context, spawn }) => {\n const { subscriptions, publishProcesses } = context\n const publishProcess = publishProcesses.get(item.seedLocalId)\n if (!publishProcess) {\n console.warn(`Publish process with seedLocalId \"${item.seedLocalId}\" does not exist.`)\n return context\n }\n\n if (subscriptions.has(item.seedLocalId)) {\n console.warn(`Subscription with seedLocalId \"${item.seedLocalId}\" already exists.`)\n return context\n }\n\n const subscriptionProcess = spawn(subscribe, {\n input: { publishProcess, seedLocalId: item.seedLocalId },\n })\n\n subscriptions.set(item.seedLocalId, subscriptionProcess)\n\n return {\n ...context,\n subscriptions: new Map(subscriptions),\n }\n })\n})\n","import {\n isPublishWallet,\n type PublishWallet,\n} from '~/helpers/seedSigner'\nimport { getPublishWallet } from '~/helpers/publishWalletRegistry'\n\nexport const retryAttestations = ({\n context,\n event,\n}: {\n context: {\n publishProcesses: Map<\n string,\n { send: (event: { type: string; account?: PublishWallet; wallet?: PublishWallet }) => void }\n >\n }\n event: unknown\n}) => {\n const ev = event as { seedLocalId: string; account?: unknown }\n const { seedLocalId, account } = ev\n const publishProcess = context.publishProcesses.get(seedLocalId)\n if (!publishProcess) {\n console.warn(`Publish process with seedLocalId \"${seedLocalId}\" does not exist.`)\n return\n }\n const wallet =\n account == null\n ? getPublishWallet() ?? undefined\n : isPublishWallet(account)\n ? account\n : undefined\n if (account != null && !wallet) {\n console.warn(\n '[retryAttestations] account must be a PublishWallet. Use fromThirdwebAccount / fromEip1193Provider / fromEthersWallet.',\n )\n }\n publishProcess.send({ type: 'retry', account: wallet, wallet })\n}\n","import type { AnyActorRef } from 'xstate'\n\n/**\n * Spawned publish/subscription actors are children of the publish manager (`enqueue.stopChild`).\n * DB-restored actors are created with `createActor` and are not children — stop them with `.stop()`.\n */\nexport function stopScopedOrStandaloneChild(\n self: AnyActorRef,\n child: AnyActorRef,\n enqueue: { stopChild: (c: AnyActorRef) => void },\n): void {\n if (child._parent === self) {\n enqueue.stopChild(child)\n } else {\n child.stop()\n }\n}\n","import { BaseDb, publishProcesses } from '@seedprotocol/sdk'\nimport { EventObject, fromCallback } from 'xstate'\nimport { eq, and, desc } from 'drizzle-orm'\nimport debug from 'debug'\n\nconst logger = debug('seedProtocol:services:PublishManager:actors:savePublish')\n\n/**\n * Multiple savePublish actors can be in flight per seed (subscribe + periodic + final).\n * SQLite writes complete in completion order, not invocation order — a slower stale write\n * can finish after the terminal save, miss the in_progress row (already completed), and\n * INSERT a new row with an intermediate snapshot. That makes UIs jump back to e.g.\n * creatingAttestations seconds after success. Serialize the actual DB work per seedLocalId.\n */\nconst saveWriteTailBySeed = new Map<string, Promise<void>>()\n\nfunction enqueueSaveWrite(seedLocalId: string, write: () => Promise<void>): Promise<void> {\n const prev = saveWriteTailBySeed.get(seedLocalId) ?? Promise.resolve()\n const next = prev.then(write)\n saveWriteTailBySeed.set(seedLocalId, next.catch(() => {}))\n return next\n}\n\nexport function isTerminalPublishRowStatus(\n status: string | null | undefined,\n): status is 'completed' | 'failed' | 'interrupted' {\n return status === 'completed' || status === 'failed' || status === 'interrupted'\n}\n\nfunction statusFromSnapshot(snapshot: { status?: string; value?: unknown }): 'in_progress' | 'completed' | 'failed' | 'interrupted' {\n if (snapshot.status === 'done') {\n if (snapshot.value === 'success') return 'completed'\n if (snapshot.value === 'failure') return 'failed'\n return 'completed'\n }\n return 'in_progress'\n}\n\nconst MAX_ERROR_MESSAGE_LENGTH = 500\nconst MAX_ERROR_DETAILS_LENGTH = 2000\nconst MAX_ERROR_CODE_LENGTH = 100\n\n/** JSON.stringify cannot serialize BigInt; publish context (e.g. gas, tx fields) may contain bigint. */\nfunction jsonStringifyPersistedSnapshot(value: unknown): string {\n return JSON.stringify(value, (_key, v) => (typeof v === 'bigint' ? v.toString() : v))\n}\n\n/** XState persisted snapshots usually have `context` at the root; some shapes nest it. */\nfunction publishRunIdFromSnapshot(snapshot: unknown): string | undefined {\n if (snapshot == null || typeof snapshot !== 'object') return undefined\n const s = snapshot as Record<string, unknown>\n const nested = s.snapshot as { context?: { publishRunId?: string } } | undefined\n const ctx =\n (s.context as { publishRunId?: string } | undefined) ?? nested?.context\n const id = ctx?.publishRunId\n return typeof id === 'string' && id.length > 0 ? id : undefined\n}\n\n/**\n * After a DB restore, `context.error` is the JSON form of the original error: own enumerable\n * fields (`name`, `code`, …) survive but `message` and `stack` do not.\n */\nfunction errorMessageOf(err: unknown): string | undefined {\n if (err instanceof Error) return err.message\n if (typeof err === 'object') {\n const message = (err as { message?: unknown }).message\n return typeof message === 'string' ? message : undefined\n }\n return String(err)\n}\n\n/** `code` on publish errors (`ManagedAccountPublishError`, `Eip7702ModularAccountPublishError`, …). */\nfunction errorCodeOf(err: unknown): string | undefined {\n if (err == null || typeof err !== 'object') return undefined\n const code = (err as { code?: unknown }).code\n return typeof code === 'string' && code.length > 0 ? code.slice(0, MAX_ERROR_CODE_LENGTH) : undefined\n}\n\ntype PublishErrorFields = {\n errorMessage?: string\n errorStep?: string\n errorDetails?: string\n errorCode?: string | null\n}\n\nexport function errorFieldsFromContext(context: { error?: unknown; errorStep?: string } | undefined, status: 'in_progress' | 'completed' | 'failed' | 'interrupted'): PublishErrorFields {\n if (!context?.error) return {}\n if (status !== 'failed' && status !== 'in_progress') return {}\n const err = context.error\n const errorMessage = errorMessageOf(err)?.slice(0, MAX_ERROR_MESSAGE_LENGTH)\n const errorStep = context.errorStep\n const errorCode = errorCodeOf(err)\n let errorDetails: string | undefined\n if (err instanceof Error && err.stack) {\n errorDetails = err.stack.slice(0, MAX_ERROR_DETAILS_LENGTH)\n } else if (err != null && typeof err === 'object') {\n try {\n errorDetails = JSON.stringify(err).slice(0, MAX_ERROR_DETAILS_LENGTH)\n } catch {\n errorDetails = String(err).slice(0, MAX_ERROR_DETAILS_LENGTH)\n }\n } else if (err != null) {\n errorDetails = String(err).slice(0, MAX_ERROR_DETAILS_LENGTH)\n }\n // A restored error has no message or stack; keep the ones saved before the restore.\n return {\n ...(errorMessage !== undefined ? { errorMessage } : {}),\n errorStep,\n ...(err instanceof Error || errorMessage !== undefined ? { errorDetails } : {}),\n errorCode: errorCode ?? null,\n }\n}\n\nexport function markInProgressPublishInterrupted(seedLocalId: string): Promise<void> {\n return enqueueSaveWrite(seedLocalId, async () => {\n const db = BaseDb.getAppDb()\n if (!db) {\n logger('markInProgressPublishInterrupted: DB not ready, skipping')\n return\n }\n\n const existing = await db\n .select()\n .from(publishProcesses)\n .where(and(eq(publishProcesses.seedLocalId, seedLocalId), eq(publishProcesses.status, 'in_progress')))\n .orderBy(desc(publishProcesses.updatedAt))\n .limit(1)\n\n if (existing.length === 0) {\n return\n }\n\n const now = Date.now()\n await db\n .update(publishProcesses)\n .set({\n status: 'interrupted',\n completedAt: now,\n updatedAt: now,\n errorMessage: null,\n errorStep: null,\n errorDetails: null,\n errorCode: null,\n })\n .where(eq(publishProcesses.id, existing[0].id!))\n })\n}\n\nexport const savePublish = fromCallback<\n EventObject & { seedLocalId?: string; triggerPublishDone?: boolean },\n { persistedSnapshot: unknown; seedLocalId: string; triggerPublishDone?: boolean }\n>(({ sendBack, input: { persistedSnapshot, seedLocalId, triggerPublishDone } }) => {\n logger('savePublish seedLocalId', seedLocalId)\n const snapshot = persistedSnapshot as {\n status?: string\n value?: unknown\n context?: {\n publishRunId?: string\n modelName?: string\n schemaId?: string\n item?: { seedLocalId: string; seedUid?: string; modelName?: string; schemaId?: string }\n error?: unknown\n errorStep?: string\n }\n }\n\n const _save = async () => {\n const db = BaseDb.getAppDb()\n if (!db) {\n logger('savePublish: DB not ready, skipping')\n sendBack({ type: 'SAVE_PUBLISH_DONE', seedLocalId, triggerPublishDone })\n return\n }\n\n const existing = await db\n .select()\n .from(publishProcesses)\n .where(and(eq(publishProcesses.seedLocalId, seedLocalId), eq(publishProcesses.status, 'in_progress')))\n .orderBy(desc(publishProcesses.updatedAt))\n .limit(1)\n\n const snapshotStr =\n typeof persistedSnapshot === 'string' ? persistedSnapshot : jsonStringifyPersistedSnapshot(persistedSnapshot)\n const status = statusFromSnapshot(snapshot)\n const now = Date.now()\n const errorFields = errorFieldsFromContext(snapshot.context, status)\n\n if (existing.length > 0) {\n const rec = existing[0]\n await db\n .update(publishProcesses)\n .set({\n persistedSnapshot: snapshotStr,\n status,\n updatedAt: now,\n ...(snapshot.status === 'done' && status !== 'in_progress' ? { completedAt: now } : {}),\n ...errorFields,\n })\n .where(eq(publishProcesses.id, rec.id!))\n } else {\n // No in_progress row: either first save of a new run, or a stale async save after the row\n // was already moved to completed (INSERT would create a duplicate with a newer startedAt).\n const incomingRunId = publishRunIdFromSnapshot(snapshot)\n if (incomingRunId != null && status === 'in_progress' && snapshot.status !== 'done') {\n const latestAny = await db\n .select()\n .from(publishProcesses)\n .where(eq(publishProcesses.seedLocalId, seedLocalId))\n .orderBy(desc(publishProcesses.startedAt))\n .limit(1)\n const latest = latestAny[0]\n if (latest && isTerminalPublishRowStatus(latest.status)) {\n try {\n const prevParsed = JSON.parse(latest.persistedSnapshot) as unknown\n const terminalRunId = publishRunIdFromSnapshot(prevParsed)\n if (terminalRunId === incomingRunId) {\n logger(\n 'savePublish: skip stale insert — same publishRunId as latest terminal row',\n seedLocalId,\n incomingRunId,\n )\n return\n }\n } catch {\n /* ignore parse errors; proceed with insert */\n }\n }\n }\n\n const item = snapshot.context?.item\n const modelName = snapshot.context?.modelName ?? item?.modelName ?? ''\n const schemaId = snapshot.context?.schemaId ?? item?.schemaId\n await db.insert(publishProcesses).values({\n seedLocalId,\n modelName,\n schemaId: schemaId ?? null,\n status,\n startedAt: now,\n persistedSnapshot: snapshotStr,\n createdAt: now,\n updatedAt: now,\n ...errorFields,\n })\n }\n }\n\n enqueueSaveWrite(seedLocalId, _save)\n .then(() => {\n sendBack({ type: 'SAVE_PUBLISH_DONE', seedLocalId, triggerPublishDone })\n })\n .catch((err) => {\n logger('savePublish error', err)\n sendBack({ type: 'SAVE_PUBLISH_DONE', seedLocalId, triggerPublishDone })\n })\n})\n","import debug from 'debug'\n\nconst logger = debug('seedProtocol:PublishManager:publishLocks')\n\n/**\n * One tab runs a given seed's publish. Every tab restores `in_progress` publish rows on load, and\n * two tabs resuming the same publish would upload and attest twice. The tab running a publish holds\n * a Web Lock for its seed; the browser releases it when the tab closes or crashes, and the next tab\n * to restore picks the publish up. See docs/MULTI_TAB.md.\n *\n * Where Web Locks are missing (Node, Bun, old browsers) every lock is granted, as before.\n */\n\ntype LockManagerLike = Pick<LockManager, 'request'>\n\nlet getLockManager = (): LockManagerLike | undefined =>\n typeof navigator !== 'undefined' ? navigator.locks : undefined\n\n/** seedLocalId → releases this tab's lock */\nconst held = new Map<string, () => void>()\n\nexport function publishLockName(seedLocalId: string): string {\n return `seed:publish:${seedLocalId}`\n}\n\n/**\n * Takes the seed's publish lock if no other tab holds it. Resolves true when this tab holds it\n * (including already), false when another tab is running that publish.\n */\nexport async function tryHoldPublishLock(seedLocalId: string): Promise<boolean> {\n if (held.has(seedLocalId)) return true\n const locks = getLockManager()\n if (!locks) return true\n\n return new Promise<boolean>((resolve, reject) => {\n locks\n .request(publishLockName(seedLocalId), { mode: 'exclusive', ifAvailable: true }, (lock) => {\n if (!lock) {\n resolve(false)\n return undefined\n }\n // Hold until released; the callback's promise is the lock's lifetime.\n return new Promise<void>((release) => {\n held.set(seedLocalId, () => {\n held.delete(seedLocalId)\n release()\n })\n resolve(true)\n })\n })\n .catch((error) => {\n logger(`publish lock request for ${seedLocalId} failed`, error)\n reject(error)\n })\n })\n}\n\nexport function releasePublishLock(seedLocalId: string): void {\n held.get(seedLocalId)?.()\n}\n\nexport function releaseAllPublishLocks(): void {\n for (const release of [...held.values()]) release()\n}\n\nexport function isHoldingPublishLock(seedLocalId: string): boolean {\n return held.has(seedLocalId)\n}\n\n/** Tests only: swap the lock manager (Bun has no navigator.locks). */\nexport function setPublishLockManagerForTests(locks: LockManagerLike | undefined): void {\n releaseAllPublishLocks()\n getLockManager = () => locks\n}\n","import type { AnyActorRef } from 'xstate'\nimport { enqueueActions } from 'xstate'\nimport { stopScopedOrStandaloneChild } from './stopScopedOrStandaloneChild'\nimport { markInProgressPublishInterrupted } from '../actors/savePublish'\nimport { releasePublishLock } from '../publishLocks'\n\nexport const stopPublish = enqueueActions(({ context, event, enqueue, self }) => {\n const { publishProcesses, subscriptions } = context\n const { seedLocalId } = event as unknown as { seedLocalId: string }\n\n void markInProgressPublishInterrupted(seedLocalId).catch((error) => {\n console.warn(\n `[stopPublish] Failed to mark publish_processes row interrupted for \"${seedLocalId}\":`,\n error,\n )\n })\n\n releasePublishLock(seedLocalId)\n\n const publishProcess = publishProcesses.get(seedLocalId)\n if (!publishProcess) {\n console.warn(`Publish process with seedLocalId \"${seedLocalId}\" does not exist.`)\n return\n }\n\n stopScopedOrStandaloneChild(self, publishProcess as AnyActorRef, enqueue)\n\n const subscriptionProcess = subscriptions.get(seedLocalId)\n if (subscriptionProcess) {\n stopScopedOrStandaloneChild(self, subscriptionProcess as AnyActorRef, enqueue)\n }\n\n const newPublishProcesses = new Map(publishProcesses)\n newPublishProcesses.delete(seedLocalId)\n const newSubscriptions = new Map(subscriptions)\n newSubscriptions.delete(seedLocalId)\n\n enqueue.assign({\n publishProcesses: newPublishProcesses,\n subscriptions: newSubscriptions,\n })\n})\n","import type { ActorRef, AnyActorRef, EventObject } from 'xstate'\nimport { enqueueActions } from 'xstate'\nimport debug from 'debug'\nimport { stopScopedOrStandaloneChild } from './stopScopedOrStandaloneChild'\nimport { releaseAllPublishLocks } from '../publishLocks'\n\nconst logger = debug('seedProtocol:PublishManager:index')\n\nexport const stopAll = enqueueActions(({ context, enqueue, self }) => {\n logger('Stopping all actors...')\n\n context.publishProcesses.forEach((publishProcess: ActorRef<any, any>) => {\n stopScopedOrStandaloneChild(self, publishProcess as AnyActorRef, enqueue)\n })\n context.subscriptions.forEach((subscriptionProcess: ActorRef<any, EventObject>) => {\n stopScopedOrStandaloneChild(self, subscriptionProcess as AnyActorRef, enqueue)\n })\n\n // Stopped here, but rows stay in_progress: the next tab to restore may resume them.\n releaseAllPublishLocks()\n\n enqueue.assign({\n publishProcesses: new Map(),\n subscriptions: new Map(),\n })\n})\n","import { enqueueActions } from 'xstate'\n\nexport const query = enqueueActions(({ context, event, enqueue }) => {\n const { seedLocalId } = event as unknown as { seedLocalId: string }\n const publishProcess = context.publishProcesses.get(seedLocalId)\n if (!publishProcess) {\n console.warn(`Publish process with seedLocalId \"${seedLocalId}\" does not exist.`)\n return\n }\n\n enqueue.stopChild(publishProcess)\n\n const subscriptionProcess = context.subscriptions.get(seedLocalId)\n if (subscriptionProcess) {\n enqueue.stopChild(subscriptionProcess)\n }\n\n const newPublishProcesses = new Map(context.publishProcesses)\n newPublishProcesses.delete(seedLocalId)\n const newSubscriptions = new Map(context.subscriptions)\n newSubscriptions.delete(seedLocalId)\n\n enqueue.assign({\n publishProcesses: newPublishProcesses,\n subscriptions: newSubscriptions,\n })\n})\n","import { assign } from 'xstate'\n\nexport const addSubscription = assign(({ context, event }) => {\n const { subscriptions } = context\n const { seedLocalId, newSubscription } = event as unknown as {\n seedLocalId: string\n newSubscription?: import('xstate').ActorRef<any, import('xstate').EventObject>\n }\n\n if (newSubscription) {\n subscriptions.set(seedLocalId, newSubscription)\n }\n\n return {\n subscriptions: new Map(subscriptions),\n }\n})\n","import { assign } from 'xstate'\nimport { savePublish } from '../actors/savePublish'\n\ntype PublishProcessActor = {\n getPersistedSnapshot?: () => unknown\n getSnapshot: () => { status?: string; value?: unknown; context?: Record<string, unknown> }\n}\n\n/** Never persist multi-megabyte binary fields to SQLite (periodic saves during bundler upload). */\nconst HEAVY_PUBLISH_CONTEXT_KEYS = ['signedDataItems', 'arweaveUploadData'] as const\n\n/**\n * Never persist key material. `arweaveJwk` holds the private `d`; an ethers HD wallet passed as\n * `dataItemSigner` serializes its mnemonic. A restored publish falls back to the PublishProvider\n * config for both (`context.x ?? config.x`), so the key must be configured again to sign after a reload.\n */\nconst SECRET_PUBLISH_CONTEXT_KEYS = ['arweaveJwk', 'dataItemSigner'] as const\n\nconst STRIPPED_KEYS = new Set<string>([...HEAVY_PUBLISH_CONTEXT_KEYS, ...SECRET_PUBLISH_CONTEXT_KEYS])\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value == null || typeof value !== 'object') return false\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * Child actor snapshots carry their `input` (`{ context }`), so the keys can appear anywhere in\n * the tree, not only on the root context. Walks plain objects and arrays; class instances\n * (Item, Uint8Array, …) are kept as they are.\n */\nfunction stripPublishSnapshotFields(value: unknown, seen = new WeakMap<object, unknown>()): unknown {\n if (Array.isArray(value)) {\n if (seen.has(value)) return seen.get(value)\n const out: unknown[] = []\n seen.set(value, out)\n for (const v of value) out.push(stripPublishSnapshotFields(v, seen))\n return out\n }\n if (!isPlainObject(value)) return value\n if (seen.has(value)) return seen.get(value)\n const out: Record<string, unknown> = {}\n seen.set(value, out)\n for (const [k, v] of Object.entries(value)) {\n if (STRIPPED_KEYS.has(k)) continue\n out[k] = stripPublishSnapshotFields(v, seen)\n }\n return out\n}\n\nexport function getPersistableSnapshot(actor: PublishProcessActor): unknown {\n try {\n const snap = actor.getPersistedSnapshot?.() ?? actor.getSnapshot()\n return stripPublishSnapshotFields(snap)\n } catch {\n const snapshot = actor.getSnapshot()\n const ctx = snapshot.context\n if (!ctx?.item) return stripPublishSnapshotFields(snapshot)\n const item = ctx.item as { seedLocalId?: string; modelName?: string; schemaId?: string }\n return stripPublishSnapshotFields({\n ...snapshot,\n context: {\n ...ctx,\n item: {\n seedLocalId: item.seedLocalId,\n modelName: item.modelName,\n schemaId: item.schemaId,\n },\n },\n })\n }\n}\n\nexport const requestSavePublish = assign(({ context, event, spawn }) => {\n const { publishProcesses } = context\n const { seedLocalId, publishProcess, triggerPublishDone } = event as unknown as {\n seedLocalId: string\n publishProcess?: PublishProcessActor\n triggerPublishDone?: boolean\n }\n\n if (!publishProcess) {\n return context\n }\n\n const newPublishProcesses = new Map(publishProcesses)\n newPublishProcesses.set(seedLocalId, publishProcess)\n\n const persistedSnapshot = getPersistableSnapshot(publishProcess)\n\n spawn(savePublish, {\n id: `savePublish_${seedLocalId}_${Date.now()}`,\n input: { persistedSnapshot, seedLocalId, triggerPublishDone },\n })\n\n return { publishProcesses: newPublishProcesses }\n})\n","import { assign } from 'xstate'\nimport { releasePublishLock } from '../publishLocks'\n\nexport const publishDone = assign(({ context, event }) => {\n const { publishProcesses, subscriptions, settledPublishes } = context\n const seedLocalId = (event as unknown as { seedLocalId: string }).seedLocalId\n releasePublishLock(seedLocalId)\n const subscriptionProcess = subscriptions.get(seedLocalId)\n if (subscriptionProcess) {\n subscriptionProcess.send({ type: 'UNSUBSCRIBE' })\n }\n const finished = publishProcesses.get(seedLocalId)\n const newPublishProcesses = new Map(publishProcesses)\n newPublishProcesses.delete(seedLocalId)\n const newSubscriptions = new Map(subscriptions)\n newSubscriptions.delete(seedLocalId)\n const newSettled = new Map(settledPublishes)\n if (finished) newSettled.set(seedLocalId, finished)\n return {\n publishProcesses: newPublishProcesses,\n subscriptions: newSubscriptions,\n settledPublishes: newSettled,\n }\n})\n","import { assign } from 'xstate'\n\nexport const removeSubscription = assign(({ context, event }) => {\n const { subscriptions } = context\n const seedLocalId = (event as unknown as { seedLocalId: string }).seedLocalId\n const newSubscriptions = new Map(subscriptions)\n newSubscriptions.delete(seedLocalId)\n return {\n subscriptions: newSubscriptions,\n }\n})\n","import { BaseDb, publishProcesses } from '@seedprotocol/sdk'\nimport { createActor, EventObject, fromCallback } from 'xstate'\nimport { eq } from 'drizzle-orm'\nimport { publishMachine } from '../../publish'\nimport { subscribe } from './subscribe'\nimport { tryHoldPublishLock } from '../publishLocks'\n\nconst RESTORE_DB_WAIT_MS = 60_000\nconst RESTORE_DB_POLL_MS = 2_000\n\nfunction envMs(name: string, fallback: number): number {\n const raw = typeof process !== 'undefined' ? process.env[name] : undefined\n if (raw == null || raw === '') return fallback\n const n = Number(raw)\n return Number.isFinite(n) && n >= 0 ? n : fallback\n}\n\nasync function waitForDb(maxWaitMs: number, pollMs: number): Promise<boolean> {\n const deadline = Date.now() + maxWaitMs\n while (Date.now() < deadline) {\n try {\n if (BaseDb.isAppDbReady() && BaseDb.getAppDb()) return true\n } catch {\n // Db facade not configured yet\n }\n await new Promise((r) => setTimeout(r, pollMs))\n }\n return false\n}\n\n/** Minimal snapshot shape for restore; avoids excessive type recursion from SnapshotFrom<typeof publishMachine>.\n * Older rows may omit `context.attestationStrategy`; publish guards then fall back to `useDirectEas`. */\ninterface PersistedSnapshot {\n status?: string\n value?: string | Record<string, unknown>\n context?: {\n item?: { seedLocalId?: string; modelName?: string; schemaId?: string }\n modelName?: string\n schemaId?: string\n reimbursementTransactionId?: string\n requestResponse?: unknown\n arweaveTransactions?: unknown[]\n publishUploads?: unknown[]\n }\n}\n\nfunction getStateValue(parsed: PersistedSnapshot): string {\n const v = parsed.value\n if (typeof v === 'string') return v\n if (v && typeof v === 'object') {\n const keys = Object.keys(v)\n return (keys[0] ?? '') as string\n }\n return ''\n}\n\nfunction isRestorableSnapshot(parsed: PersistedSnapshot): boolean {\n const stateValue = getStateValue(parsed)\n if (stateValue === 'pollingForConfirmation') {\n if (!parsed.context?.reimbursementTransactionId || !parsed.context?.requestResponse) return false\n }\n if (stateValue === 'uploadingData') {\n const txs = parsed.context?.arweaveTransactions\n const uploads = parsed.context?.publishUploads\n if (!Array.isArray(txs) || txs.length === 0 || !Array.isArray(uploads)) return false\n }\n return true\n}\n\n/**\n * XState `persistContext` serializes actor refs as `{ xstate$$type: 1, id }`. `restoreSnapshot` swaps those\n * for live child actors; if the id is not in `snapshot.children`, `context.item` becomes `undefined` and\n * restored publishes throw on resume (e.g. createAttestations). Real item data is always a plain object.\n */\nfunction isPersistedActorRef(value: unknown): value is { xstate$$type: number; id: string } {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'xstate$$type' in value &&\n (value as { xstate$$type: number }).xstate$$type === 1 &&\n typeof (value as { id?: unknown }).id === 'string'\n )\n}\n\nfunction patchPublishContextItemForRestore(\n parsed: PersistedSnapshot,\n seedLocalId: string,\n record: { modelName?: string | null; schemaId?: string | null },\n) {\n parsed.context = parsed.context ?? {}\n const raw = parsed.context.item\n if (isPersistedActorRef(raw)) {\n parsed.context.item = {\n seedLocalId,\n modelName: parsed.context.modelName ?? record.modelName ?? '',\n schemaId: parsed.context.schemaId ?? record.schemaId ?? undefined,\n }\n return\n }\n parsed.context.item = {\n ...(typeof raw === 'object' && raw !== null && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : {}),\n seedLocalId,\n modelName:\n (raw as { modelName?: string } | undefined)?.modelName ??\n parsed.context.modelName ??\n record.modelName ??\n '',\n schemaId:\n (raw as { schemaId?: string } | undefined)?.schemaId ??\n parsed.context.schemaId ??\n record.schemaId ??\n undefined,\n }\n}\n\nexport interface RestoreFromDbInput {\n context: {\n publishProcesses: Map<string, unknown>\n subscriptions: Map<string, unknown>\n }\n}\n\nexport const restoreFromDb = fromCallback<EventObject, RestoreFromDbInput>(\n ({ sendBack, input: { context } }) => {\n const _restoreFromDb = async () => {\n const newPublishProcesses = new Map<string, import('xstate').ActorRef<any, any>>()\n const newSubscriptions = new Map<string, import('xstate').ActorRef<any, EventObject>>()\n\n // BaseDb is configured by platformClassesInit when client.init() runs.\n // PublishManager starts on module load, which can happen before client.init().\n // Wait for DB to be ready before attempting restore (poll every 2s, up to 60s).\n const dbReady = await waitForDb(\n envMs('SEED_PUBLISH_RESTORE_WAIT_MS', RESTORE_DB_WAIT_MS),\n envMs('SEED_PUBLISH_RESTORE_POLL_MS', RESTORE_DB_POLL_MS),\n )\n if (!dbReady) {\n return { newPublishProcesses, newSubscriptions }\n }\n\n const db = BaseDb.getAppDb()\n if (!db) {\n return { newPublishProcesses, newSubscriptions }\n }\n\n const inProgress = await db\n .select()\n .from(publishProcesses)\n .where(eq(publishProcesses.status, 'in_progress'))\n\n // Dedupe by seedLocalId, keep latest per seedLocalId (by updatedAt then createdAt)\n const bySeed = new Map<string, (typeof inProgress)[0]>()\n const sorted = [...inProgress].sort(\n (a, b) => (b.updatedAt ?? b.createdAt ?? 0) - (a.updatedAt ?? a.createdAt ?? 0)\n )\n for (const rec of sorted) {\n if (!bySeed.has(rec.seedLocalId)) bySeed.set(rec.seedLocalId, rec)\n }\n const publishProcessRecords = Array.from(bySeed.values())\n\n for (const publishProcessRecord of publishProcessRecords) {\n let parsed: PersistedSnapshot\n try {\n parsed = JSON.parse(publishProcessRecord.persistedSnapshot) as PersistedSnapshot\n } catch {\n continue\n }\n if (parsed.status === 'done') continue\n const seedLocalId = parsed.context?.item?.seedLocalId ?? publishProcessRecord.seedLocalId\n if (!seedLocalId) continue\n if (!isRestorableSnapshot(parsed)) continue\n // Another open tab is already running this publish; it keeps it.\n if (!(await tryHoldPublishLock(seedLocalId))) continue\n\n // Item is an SDK class instance; persistence loses getters. Also strip mistaken XState actor stubs on item.\n patchPublishContextItemForRestore(parsed, seedLocalId, publishProcessRecord)\n\n const publishProcess = createActor(publishMachine as unknown as import('xstate').AnyActorLogic, {\n snapshot: parsed as any,\n input: undefined,\n })\n\n const subscription = createActor(subscribe, {\n input: {\n publishProcess,\n seedLocalId,\n },\n })\n newPublishProcesses.set(seedLocalId, publishProcess)\n newSubscriptions.set(seedLocalId, subscription)\n\n publishProcess.start()\n subscription.start()\n }\n return { newPublishProcesses, newSubscriptions }\n }\n\n const empty = () => ({\n newPublishProcesses: new Map<string, import('xstate').ActorRef<any, any>>(),\n newSubscriptions: new Map<string, import('xstate').ActorRef<any, EventObject>>(),\n })\n\n _restoreFromDb()\n .then((result) => {\n const { newPublishProcesses, newSubscriptions } = result ?? empty()\n sendBack({\n type: 'RESTORE_FROM_DB_DONE',\n publishProcesses: newPublishProcesses,\n subscriptions: newSubscriptions,\n })\n })\n .catch(() => {\n const { newPublishProcesses, newSubscriptions } = empty()\n sendBack({\n type: 'RESTORE_FROM_DB_DONE',\n publishProcesses: newPublishProcesses,\n subscriptions: newSubscriptions,\n })\n })\n }\n)\n","import { assign } from 'xstate'\n\nexport const queueCreatePublish = assign(({ context, event }) => {\n const pending = context.pendingCreates ?? []\n return {\n pendingCreates: [...pending, event],\n }\n})\n","import { enqueueActions } from 'xstate'\n\n/** Replay CREATE_PUBLISH events that arrived while restore was still running. */\nexport const drainPendingCreates = enqueueActions(({ context, enqueue }) => {\n const pending = context.pendingCreates ?? []\n if (pending.length === 0) return\n enqueue.assign({ pendingCreates: [] })\n for (const ev of pending) {\n enqueue.raise(ev)\n }\n})\n","import { ActorRefFrom, createActor, setup } from 'xstate'\nimport { Item } from '@seedprotocol/sdk'\nimport { publishMachine } from '../publish'\nimport { assignRestoreFromDb } from './actions/assignRestoreFromDb'\nimport { createPublish } from './actions/createPublish'\nimport { retryAttestations } from './actions/retryAttestations'\nimport { stopPublish } from './actions/stopPublish'\nimport { stopAll } from './actions/stopAll'\nimport { query } from './actions/query'\nimport { addSubscription } from './actions/addSubscription'\nimport { requestSavePublish } from './actions/requestSavePublish'\nimport { publishDone } from './actions/publishDone'\nimport { removeSubscription } from './actions/removeSubscription'\nimport { restoreFromDb } from './actors/restoreFromDb'\nimport { queueCreatePublish } from './actions/queueCreatePublish'\nimport { drainPendingCreates } from './actions/drainPendingCreates'\nimport { registerCreatePublishResolver } from './createPublishResult'\nimport { setPublishManagerRef } from './publishManagerRef'\nimport { isHoldingPublishLock, releasePublishLock, tryHoldPublishLock } from './publishLocks'\nimport debug from 'debug'\n\nconst logger = debug('seedProtocol:PublishManager:index')\n\nexport interface PublishManagerMachineContext {\n publishProcesses: Map<string, import('xstate').ActorRef<any, any>>\n subscriptions: Map<string, import('xstate').ActorRef<any, import('xstate').EventObject>>\n /** CREATE_PUBLISH events received before restore finishes. */\n pendingCreates: PublishManagerEvent[]\n /** Last finished actor per seed. Not used by the in-flight duplicate guard. */\n settledPublishes: Map<string, import('xstate').ActorRef<any, any>>\n}\n\ntype PublishManagerEvent =\n | { type: 'RESTORE_FROM_DB_DONE'; publishProcesses: PublishManagerMachineContext['publishProcesses']; subscriptions: PublishManagerMachineContext['subscriptions'] }\n | { type: 'CREATE_PUBLISH'; item: import('@seedprotocol/sdk').Item<any>; address: string; account?: unknown; options?: import('../../config').CreatePublishOptions; createToken?: number }\n | { type: 'ADD_SUBSCRIPTION'; seedLocalId: string; newSubscription?: import('xstate').ActorRef<any, any> }\n | { type: 'REQUEST_SAVE_PUBLISH'; seedLocalId: string; publishProcess?: unknown; triggerPublishDone?: boolean }\n | { type: 'SAVE_PUBLISH_DONE'; seedLocalId: string; triggerPublishDone?: boolean }\n | { type: 'PUBLISH_DONE'; seedLocalId: string }\n | { type: 'REMOVE_SUBSCRIPTION'; seedLocalId: string }\n | { type: 'RETRY_ATTESTATIONS'; seedLocalId: string; account?: unknown }\n | { type: 'STOP_PUBLISH'; seedLocalId: string }\n | { type: 'QUERY'; seedLocalId: string }\n | { type: 'STOP_ALL' }\n\nexport const publishManagerMachine = setup({\n types: {\n context: {} as PublishManagerMachineContext,\n input: {} as PublishManagerMachineContext,\n events: {} as PublishManagerEvent,\n },\n actors: {\n restoreFromDb,\n },\n actions: {\n assignRestoreFromDb,\n createPublish,\n queueCreatePublish,\n drainPendingCreates,\n addSubscription,\n requestSavePublish,\n publishDone,\n removeSubscription,\n retryAttestations,\n stopPublish,\n stopAll,\n query,\n } as unknown as Record<string, (args: unknown) => void>,\n}).createMachine({\n id: 'publishManager',\n initial: 'restoreFromDb',\n context: {\n publishProcesses: new Map(),\n subscriptions: new Map(),\n pendingCreates: [],\n settledPublishes: new Map(),\n },\n states: {\n restoreFromDb: {\n on: {\n RESTORE_FROM_DB_DONE: {\n target: 'active',\n actions: ['assignRestoreFromDb'],\n },\n CREATE_PUBLISH: {\n actions: ['queueCreatePublish'],\n },\n },\n invoke: {\n src: 'restoreFromDb',\n input: ({ context }) => ({ context }),\n },\n },\n active: {\n entry: 'drainPendingCreates',\n on: {\n CREATE_PUBLISH: {\n actions: ['createPublish'],\n },\n ADD_SUBSCRIPTION: {\n actions: ['addSubscription'],\n },\n REQUEST_SAVE_PUBLISH: {\n actions: ['requestSavePublish'],\n },\n SAVE_PUBLISH_DONE: [\n {\n guard: ({ event }) => (event as { triggerPublishDone?: boolean }).triggerPublishDone === true,\n actions: ['publishDone'],\n },\n ],\n PUBLISH_DONE: {\n actions: ['publishDone'],\n },\n REMOVE_SUBSCRIPTION: {\n actions: ['removeSubscription'],\n },\n RETRY_ATTESTATIONS: {\n actions: ['retryAttestations'],\n },\n STOP_PUBLISH: {\n actions: ['stopPublish'],\n },\n QUERY: {\n actions: ['query'],\n },\n STOP_ALL: {\n actions: ['stopAll'],\n },\n },\n },\n },\n})\n\nconst initialManagerContext = {\n publishProcesses: new Map(),\n subscriptions: new Map(),\n pendingCreates: [] as PublishManagerEvent[],\n settledPublishes: new Map(),\n}\n\nconst publishManager = createActor(publishManagerMachine, {\n input: initialManagerContext,\n})\n\n/**\n * `snapshot.status === 'active'` is true before `start()` and while restore is running.\n * This flag is the only signal that `start()` has been called. Calling it twice throws.\n */\nlet publishManagerStarted = false\n\nfunction ensurePublishManagerStarted() {\n if (publishManagerStarted) return\n try {\n publishManager.start()\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n if (!/already started/i.test(message)) throw err\n }\n publishManagerStarted = true\n}\n\n// Set ref for subscribe actor to call savePublish, onPublishDone, removeSubscription\nsetPublishManagerRef({\n savePublish: (seedLocalId, publishProcess, options) => {\n publishManager.send({\n type: 'REQUEST_SAVE_PUBLISH',\n seedLocalId,\n publishProcess,\n triggerPublishDone: options?.triggerPublishDone,\n })\n },\n onPublishDone: (seedLocalId) => {\n publishManager.send({ type: 'PUBLISH_DONE', seedLocalId })\n },\n removeSubscription: (seedLocalId) => {\n publishManager.send({ type: 'REMOVE_SUBSCRIPTION', seedLocalId })\n },\n})\n\nconst subscription = publishManager.subscribe((snapshot) => {\n logger('PublishManager snapshot:', snapshot)\n})\n\nif (typeof document !== 'undefined') {\n ensurePublishManagerStarted()\n\n window.addEventListener('load', () => {\n logger('PublishManager started')\n })\n\n window.addEventListener('beforeunload', () => {\n subscription.unsubscribe()\n publishManager.stop()\n })\n}\n\nexport const PublishManager = {\n getService: () => publishManager,\n /**\n * Start the manager if this process has not, then resolve when the machine value is `active`.\n * Node does not auto-start. `getSnapshot().status` is not readiness.\n */\n ready: (): Promise<void> => {\n ensurePublishManagerStarted()\n if (publishManager.getSnapshot().value === 'active') return Promise.resolve()\n return new Promise((resolve) => {\n const sub = publishManager.subscribe((snapshot) => {\n if (snapshot.value === 'active') {\n sub.unsubscribe()\n resolve()\n }\n })\n if (publishManager.getSnapshot().value === 'active') {\n sub.unsubscribe()\n resolve()\n }\n })\n },\n /**\n * Spawn a publish. Resolves with the child actor once it exists.\n * Resolves `undefined` when the address is missing or that seed is already in flight, in this\n * tab or another one. This promise means the process started, not that the chain publish finished.\n */\n createPublish: async (\n item: InstanceType<typeof Item>,\n address: string,\n account?: import('../../helpers/seedSigner').PublishWallet,\n options?: import('../../config').CreatePublishOptions\n ): Promise<import('xstate').ActorRef<any, any> | undefined> => {\n const { seedLocalId } = item\n const heldBefore = isHoldingPublishLock(seedLocalId)\n if (!(await tryHoldPublishLock(seedLocalId))) {\n console.warn(`[createPublish] \"${seedLocalId}\" is already publishing in another tab; skipping.`)\n return undefined\n }\n const publishProcess = await new Promise<import('xstate').ActorRef<any, any> | undefined>((resolve) => {\n const createToken = registerCreatePublishResolver(resolve)\n publishManager.send({ type: 'CREATE_PUBLISH', item, address, account, options, createToken })\n })\n // Nothing spawned (e.g. no address): don't keep a lock this call took.\n if (!publishProcess && !heldBefore) releasePublishLock(seedLocalId)\n return publishProcess\n },\n retryAttestations: (seedLocalId: string, account?: import('../../helpers/seedSigner').PublishWallet) =>\n publishManager.send({ type: 'RETRY_ATTESTATIONS', seedLocalId, account }),\n stopPublish: (seedLocalId: string) => publishManager.send({ type: 'STOP_PUBLISH', seedLocalId }),\n query: (seedLocalId: string) => publishManager.send({ type: 'QUERY', seedLocalId }),\n stopAll: () => publishManager.send({ type: 'STOP_ALL' }),\n getPublish: (seedLocalId: string) => {\n const ctx = publishManager.getSnapshot().context\n return ctx.publishProcesses.get(seedLocalId) ?? ctx.settledPublishes.get(seedLocalId)\n },\n savePublish: (seedLocalId: string, publishProcess: ActorRefFrom<typeof publishMachine>) =>\n publishManager.send({ type: 'REQUEST_SAVE_PUBLISH', seedLocalId, publishProcess }),\n addSubscription: (seedLocalId: string, subscriptionActor: import('xstate').ActorRef<any, any>) =>\n publishManager.send({ type: 'ADD_SUBSCRIPTION', seedLocalId, newSubscription: subscriptionActor }),\n removeSubscription: (seedLocalId: string) => publishManager.send({ type: 'REMOVE_SUBSCRIPTION', seedLocalId }),\n}\n","import type { Address, Hex, LocalAccount, SignableMessage } from 'viem'\nimport { createPublicClient, http, type Hash } from 'viem'\nimport { entryPoint08Address } from 'viem/account-abstraction'\nimport { createSmartAccountClient } from 'permissionless'\nimport { to7702SimpleSmartAccount } from 'permissionless/accounts'\nimport { createPimlicoClient } from 'permissionless/clients/pimlico'\nimport {\n brandTxSender,\n type SeedSigner,\n type SeedTxRequest,\n type SeedTxSender,\n} from '../seedSigner'\nimport { getPublishRpcUrl, getPublishViemChain } from '../chainConfig'\nimport { ManagedAccountPublishError } from '../../errors'\nimport { userOpFailureError } from '../describeRevert'\n\nexport type CreatePermissionlessTxSenderOptions = {\n signer: SeedSigner\n bundlerUrl: string\n /** Sponsoring paymaster. Defaults to `bundlerUrl`. */\n paymasterUrl?: string\n /** `false` sends without a paymaster: the account pays its own gas. Default `true`. */\n sponsored?: boolean\n}\n\nfunction seedSignerToLocalAccount(signer: SeedSigner): LocalAccount {\n return {\n address: signer.address,\n type: 'local',\n source: 'custom',\n publicKey: '0x',\n signMessage: async ({ message }: { message: SignableMessage }) =>\n signer.signMessage({ message }),\n signTransaction: async () => {\n throw new Error(\n '@seedprotocol/publish: permissionless EIP-7702 path does not use signTransaction',\n )\n },\n signTypedData: async () => {\n throw new Error(\n '@seedprotocol/publish: signTypedData is not implemented on SeedSigner yet',\n )\n },\n }\n}\n\n/**\n * Throws when the bundler lists its EntryPoints and v0.8 is not among them (e.g. a local twin's\n * v0.6 bundler, which belongs in `PublishConfig.thirdweb.bundlerUrl`). Bundlers that do not\n * answer `eth_supportedEntryPoints` are let through.\n * @internal Exported for unit tests.\n */\nexport async function assertBundlerSupportsEntryPoint08(bundlerUrl: string): Promise<void> {\n let supported: unknown\n try {\n const res = await fetch(bundlerUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_supportedEntryPoints', params: [] }),\n })\n supported = ((await res.json()) as { result?: unknown }).result\n } catch {\n return\n }\n if (!Array.isArray(supported)) return\n const list = supported.map((a) => String(a).toLowerCase())\n if (list.includes(entryPoint08Address.toLowerCase())) return\n throw new Error(\n `@seedprotocol/publish: PublishConfig.bundlerUrl (${bundlerUrl}) does not support EntryPoint v0.8 (it lists ${list.join(', ') || 'none'}). ` +\n `The top-level bundlerUrl is only for the permissionless EIP-7702 sender. For Thirdweb in-app wallets (e.g. a local twin's bundler), set PublishConfig.thirdweb.bundlerUrl instead.`,\n )\n}\n\n/**\n * EIP-7702 `SeedTxSender` via permissionless `to7702SimpleSmartAccount`, sponsored by a paymaster\n * unless `sponsored` is false.\n * @throws when `bundlerUrl` reports no EntryPoint v0.8 support\n */\nexport async function createPermissionlessTxSender(\n options: CreatePermissionlessTxSenderOptions,\n): Promise<SeedTxSender> {\n const { signer, bundlerUrl, paymasterUrl, sponsored = true } = options\n await assertBundlerSupportsEntryPoint08(bundlerUrl)\n const chain = getPublishViemChain()\n const rpcUrl = getPublishRpcUrl()\n const address = signer.address as Address\n\n const publicClient = createPublicClient({\n chain,\n transport: http(rpcUrl),\n })\n\n const owner = seedSignerToLocalAccount(signer)\n\n const simpleAccount = await to7702SimpleSmartAccount({\n client: publicClient,\n owner,\n entryPoint: {\n address: entryPoint08Address,\n version: '0.8',\n },\n })\n\n const pimlicoUrl = paymasterUrl ?? bundlerUrl\n const pimlicoClient = createPimlicoClient({\n transport: http(pimlicoUrl),\n entryPoint: {\n address: entryPoint08Address,\n version: '0.8',\n },\n })\n\n const smartAccountClient = createSmartAccountClient({\n account: simpleAccount,\n chain,\n bundlerTransport: http(bundlerUrl),\n ...(sponsored ? { paymaster: pimlicoClient } : {}),\n userOperation: {\n estimateFeesPerGas: async () => (await pimlicoClient.getUserOperationGasPrice()).fast,\n },\n })\n\n return brandTxSender({\n address: (simpleAccount.address ?? address) as Address,\n sendTransaction: async (tx: SeedTxRequest) => {\n let receipt: UserOpReceiptLike\n try {\n const userOpHash = await smartAccountClient.sendUserOperation({\n calls: [{ to: tx.to, data: tx.data, value: tx.value ?? 0n }],\n })\n receipt = await smartAccountClient.waitForUserOperationReceipt({ hash: userOpHash })\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Error(\n `@seedprotocol/publish: permissionless/EIP-7702 send failed (${msg}). Ensure bundlerUrl/paymasterUrl support EntryPoint v0.8, or use accountMode: 'eoa' / Thirdweb adapter.`,\n { cause: err },\n )\n }\n return { transactionHash: assertUserOpSucceeded(receipt, simpleAccount.address) }\n },\n })\n}\n\ntype UserOpReceiptLike = { success: boolean; reason?: string; receipt: { transactionHash: Hash } }\n\n/**\n * Returns the transaction hash of a successful UserOp, and throws for a failed one. The\n * bundle transaction itself succeeds when a UserOp in it fails, so its receipt alone would\n * pass a failed publish off as a success.\n * @throws ManagedAccountPublishError `USEROP_REVERTED` or `USEROP_FAILED_NO_REASON`\n * @internal Exported for unit tests.\n */\nexport function assertUserOpSucceeded(receipt: UserOpReceiptLike, sender?: string): Hex {\n const txHash = receipt.receipt.transactionHash as Hex\n if (receipt.success) return txHash\n const reason = receipt.reason\n if (reason && !/^0x[0-9a-f]*$/i.test(reason)) {\n throw new ManagedAccountPublishError(\n `The publish UserOp in transaction ${txHash} failed: ${reason}`,\n 'USEROP_REVERTED',\n sender,\n )\n }\n throw userOpFailureError({ txHash, revertData: reason as Hex | undefined, sender })\n}\n","import type { Item } from '@seedprotocol/sdk'\nimport { PublishManager } from '../services/publishManager'\nimport type { CreatePublishOptions } from '../config'\nimport { getPublishConfig } from '../config'\nimport { getPublishWallet } from './publishWalletRegistry'\nimport { isPublishWallet, isSeedSigner, type PublishWallet, type SeedSigner } from './seedSigner'\nimport { ethers } from 'ethers'\nimport { createPermissionlessTxSender } from './adapters/permissionlessTxSender'\nimport { resolvePublishPayment } from '../payment'\nimport type { ManagedAccountPublishError } from '../errors'\n\n/**\n * `started` resolves with the spawned publish actor once it exists, or `undefined` when\n * that seed is already publishing in this tab or another. It does not wait for the\n * publish to finish; use {@link publishItem} (or `item.publish()`) for that.\n */\nexport type PublishStarted = Promise<import('xstate').ActorRef<any, any> | undefined>\n\nexport type EnsureWalletThenPublishResult =\n | { outcome: 'started'; started: PublishStarted }\n | { outcome: 'no_address' }\n | { outcome: 'no_wallet' }\n | { outcome: 'needs_deploy' }\n | { outcome: 'managed_not_ready'; error: ManagedAccountPublishError }\n\nfunction coerceDataItemSigner(\n signer: CreatePublishOptions['dataItemSigner'] | SeedSigner | PublishWallet | undefined,\n): CreatePublishOptions['dataItemSigner'] {\n if (!signer) return undefined\n if (signer instanceof ethers.Wallet) return signer\n if (isPublishWallet(signer)) return signer.signer\n if (isSeedSigner(signer)) return signer\n return undefined\n}\n\n/**\n * Vendor-neutral publish entry: uses the registered publish wallet (EIP-1193 / permissionless / ethers).\n * When `useModularExecutor` is true, callers should use the Thirdweb `ensureSmartWalletThenPublish` instead.\n */\nexport async function ensureWalletThenPublish(\n item: Item<any>,\n options?: CreatePublishOptions,\n): Promise<EnsureWalletThenPublishResult> {\n const config = getPublishConfig()\n const payment = resolvePublishPayment(config)\n if (payment.sender === 'modular') {\n // Modular / ManagedAccount Thirdweb bootstrap is adapter-only.\n const { ensureSmartWalletThenPublish } = await import('./ensureSmartWalletThenPublish')\n return ensureSmartWalletThenPublish(item, null, async () => {\n const w = getPublishWallet()\n return w?.publisherAddress ?? w?.signer.address ?? null\n }, options)\n }\n\n let session = getPublishWallet()\n if (!session) {\n return { outcome: 'no_wallet' }\n }\n\n // Upgrade EOA sender to permissionless EIP-7702 when configured.\n if (payment.sender === 'eip7702') {\n const txSender = await createPermissionlessTxSender({\n signer: session.signer,\n bundlerUrl: config.bundlerUrl!,\n paymasterUrl: config.paymasterUrl,\n sponsored: payment.gas.payer === 'sponsored',\n })\n session = {\n ...session,\n txSender,\n publisherAddress: session.publisherAddress ?? session.signer.address,\n }\n }\n\n const address =\n session.publisherAddress ?? session.txSender.address ?? session.signer.address\n if (!address?.trim()) {\n return { outcome: 'no_address' }\n }\n\n const started = PublishManager.createPublish(item, address, session, {\n ...options,\n dataItemSigner: coerceDataItemSigner(options?.dataItemSigner) ?? session.signer,\n })\n return { outcome: 'started', started }\n}\n","import type { IItem, ItemPublishOptions } from '@seedprotocol/sdk'\nimport type { ActorRef } from 'xstate'\nimport type { CreatePublishOptions } from '../config'\nimport { PublishManager } from '../services/publishManager'\nimport { PublishMachineStates } from './constants'\nimport { ensureWalletThenPublish } from './ensureWalletThenPublish'\n\n/**\n * States where attestation failed but the actor stays alive waiting for a `retry`\n * event (PublishManager.retryAttestations). They are not final, so a waiter has to\n * treat them as failure or it would hang.\n */\nconst RECOVERABLE_FAILURE_STATES = new Set([\n 'attestationFailureRecoverable',\n 'attestationFailureRecoverableDirectToEas',\n])\n\nfunction errorMessage(error: unknown): string | undefined {\n if (!error) return undefined\n if (error instanceof Error) return error.message\n if (typeof error === 'string') return error\n if (typeof error === 'object' && 'message' in error && typeof error.message === 'string') {\n return error.message\n }\n return String(error)\n}\n\ntype PublishSnapshot = {\n value: unknown\n status?: string\n context?: { error?: unknown; errorStep?: string }\n}\n\n/**\n * Resolves when a publish actor reaches `success`; rejects on `failure`, when it is\n * stopped, or when attestation fails into a state that waits for a retry.\n */\nexport function waitForPublishActor(actor: ActorRef<any, any>, seedLocalId: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false\n let sub: { unsubscribe(): void } | undefined\n const finish = (error?: Error) => {\n if (settled) return\n settled = true\n sub?.unsubscribe()\n if (error) reject(error)\n else resolve()\n }\n\n const check = (snapshot: PublishSnapshot) => {\n const value = snapshot.value as string\n const cause = snapshot.context?.error\n const detail = errorMessage(cause)\n if (value === PublishMachineStates.SUCCESS) {\n finish()\n } else if (value === PublishMachineStates.FAILURE) {\n const step = snapshot.context?.errorStep ? ` at ${snapshot.context.errorStep}` : ''\n finish(new Error(`Publish of ${seedLocalId} failed${step}: ${detail ?? 'unknown error'}`, { cause }))\n } else if (RECOVERABLE_FAILURE_STATES.has(value)) {\n finish(\n new Error(\n `Creating attestations for ${seedLocalId} failed: ${detail ?? 'unknown error'}. ` +\n `Uploads are kept; retry with PublishManager.retryAttestations('${seedLocalId}').`,\n { cause },\n ),\n )\n } else if (snapshot.status === 'done' || snapshot.status === 'stopped') {\n finish(new Error(`Publish of ${seedLocalId} was stopped before it finished.`))\n }\n }\n\n sub = actor.subscribe({\n next: check,\n error: (error: unknown) => finish(error instanceof Error ? error : new Error(String(error))),\n complete: () => check(actor.getSnapshot() as PublishSnapshot),\n })\n // subscribe() does not replay the current snapshot.\n check(actor.getSnapshot() as PublishSnapshot)\n })\n}\n\n/**\n * Publish an item and wait for it to finish: uploads to Arweave, then attestations on EAS.\n *\n * This is the executor behind the SDK's `item.publish()`. `initPublish()` registers it\n * with `setPublishExecutor`, so apps normally call `item.publish(options)` rather than\n * this. It uses the registered publish wallet (`useSeedWallet().connect`, `setPublishWallet`)\n * the same way {@link ensureWalletThenPublish} does.\n *\n * Rejects when no wallet or address is available, when the smart account still needs\n * deploying, when the seed is already publishing (in this tab or another), or when the\n * publish fails.\n */\nexport async function publishItem(item: IItem<any>, options?: ItemPublishOptions): Promise<void> {\n // Node does not auto-start the manager; createPublish waits for it to be active.\n await PublishManager.ready()\n const result = await ensureWalletThenPublish(item as any, options as CreatePublishOptions | undefined)\n switch (result.outcome) {\n case 'started':\n break\n case 'no_wallet':\n throw new Error(\n 'No publish wallet is connected. Connect one (useSeedWallet().connect, or setPublishWallet) before publishing.',\n )\n case 'no_address':\n throw new Error('The publish wallet has no publisher address.')\n case 'needs_deploy':\n throw new Error('The smart account must be deployed before publishing.')\n case 'managed_not_ready':\n throw result.error\n }\n const actor = await result.started\n if (!actor) {\n throw new Error(`Publish of ${item.seedLocalId} did not start: it is already publishing in this tab or another.`)\n }\n await waitForPublishActor(actor, item.seedLocalId)\n}\n","import { assertPublishPaymentConfig, resolveSponsorGas, resolveUseArweaveBundler } from './payment'\nimport {\n DEFAULT_ARWEAVE_GRAPHQL_URL,\n setAdditionalSyncAddresses,\n setGetPublisherForNewSeeds,\n setPublishExecutor,\n setRevokeExecutor,\n whenLeaderTab,\n type TransactionTag,\n} from '@seedprotocol/sdk'\nimport type { Chain } from 'viem'\nimport { revokeAttestations } from './services/revoke/revokeAttestations'\nimport { publishItem } from './helpers/publishItem'\nimport {\n configureEasReadChain,\n expectEasReadChain,\n resolveEasChainDeployment,\n type EasChainDeployment,\n} from '@seedprotocol/eas'\nimport { MANAGED_ACCOUNT_FACTORY_ADDRESSES } from './helpers/constants'\nimport { ethers } from 'ethers'\nimport { DEFAULT_PUBLISH_CHAIN } from './helpers/defaultChain'\nimport { getPublishWallet } from './helpers/publishWalletRegistry'\n\n// initPublish will set the chain. Until then the SDK's EAS sync waits instead of reading the\n// default chain into a local DB that publish is about to point elsewhere.\nexpectEasReadChain('publish')\n\n/** Serialized upload item for Arweave signing (input to callback or used internally with JWK) */\nexport interface SerializedPublishUpload {\n versionLocalId: string\n itemPropertyName: string\n transactionJson: Record<string, unknown>\n}\n\n/** Result from Arweave signing (signed transaction + metadata) */\nexport interface ArweaveTransactionInfoResult {\n transaction: Record<string, unknown> & { chunks?: unknown }\n versionId: string\n modelName: string\n}\n\n/** Result from DataItem signing (compatible shape for createAttestations) */\nexport interface ArweaveDataItemInfoResult {\n transaction: { id: string }\n versionId?: string\n modelName?: string\n}\n\nexport type PublishAccountMode = 'eoa' | 'eip7702'\n\nexport interface ThirdwebWalletOptions {\n /**\n * Bundler for the managed (EIP-4337, EntryPoint v0.6) smart account's UserOps. Defaults to\n * Thirdweb's hosted bundler for the chain; required on a local chain. This is the bundler a\n * local twin uses, not the top-level {@link PublishConfig.bundlerUrl}.\n */\n bundlerUrl?: string\n /**\n * Sponsor gas through Thirdweb: the managed smart account's UserOps and, in `'EIP7702'` mode,\n * the in-app EOA's transactions. Default `true` (`false` with `payment: { gas: 'user' }`). Set `false` where Thirdweb's paymaster is\n * unavailable (local chains); the accounts then pay their own gas and must hold ETH.\n */\n sponsorGas?: boolean\n /**\n * How the user's in-app EOA (the managed account's admin) sends its own transactions, such as\n * installing the Seed executor: `'EIP7702'` (default) goes through Thirdweb's hosted EIP-7702\n * service (gas-sponsored per `sponsorGas`); `'EOA'` sends plain transactions and needs ETH.\n * A local chain requires `'EOA'`: the wallet throws for `'EIP7702'` there. The address is the\n * same either way.\n */\n modularWalletMode?: 'EIP7702' | 'EOA'\n}\n\nexport interface PublishConfig {\n /**\n * Thirdweb client id — only required when using `@seedprotocol/publish/thirdweb`.\n * When set without `rpcUrl`, the public client falls back to Thirdweb’s RPC edge.\n * Browser client ids are usually locked to app origins; Node servers should also set\n * `thirdwebSecretKey` or those RPC and bundler calls return 401.\n */\n thirdwebClientId?: string\n /**\n * Thirdweb secret key for server-side clients. Sent as `x-secret-key` on viem reads\n * of the Thirdweb RPC URL, and passed to `createThirdwebClient` for sends.\n * Do not ship this to the browser. It does not replace `rpcUrl` or `thirdwebClientId`\n * when building the viem RPC URL.\n */\n thirdwebSecretKey?: string\n /**\n * Viem chain for reads, writes and wallet connection. Defaults to Optimism Sepolia.\n * Any EVM chain with EAS deployed works. Chains in `EAS_CHAIN_DEPLOYMENTS` (`@seedprotocol/eas`)\n * resolve contract addresses automatically; others need {@link easContractAddress} and\n * {@link schemaRegistryAddress}.\n */\n chain?: Chain\n /** EAS contract on {@link chain}. Defaults to the known deployment for `chain.id`. */\n easContractAddress?: string\n /** EAS SchemaRegistry on {@link chain}. Defaults to the known deployment for `chain.id`. */\n schemaRegistryAddress?: string\n /**\n * Thirdweb ManagedAccount factory on {@link chain}. Only used by managed / modular account flows.\n * Built in for Optimism Sepolia; required on other chains when those flows are enabled.\n */\n managedAccountFactoryAddress?: string\n /**\n * JSON-RPC URL for the publish chain. Required when `thirdwebClientId` is unset.\n * Prefer a public chain RPC from Node. A domain-locked client id in the default\n * Thirdweb URL returns 401 unless `thirdwebSecretKey` is also set.\n * Thirdweb wallets and contract calls use it too; without it they use Thirdweb's RPC edge.\n */\n rpcUrl?: string\n /**\n * Thirdweb in-app wallet settings (`@seedprotocol/publish/thirdweb`). Defaults suit Thirdweb-hosted\n * chains; a local chain (e.g. the OP Sepolia twin) needs `bundlerUrl`, `sponsorGas: false` and\n * `modularWalletMode: 'EOA'`.\n */\n thirdweb?: ThirdwebWalletOptions\n /**\n * Who pays for publishes: `gas` (`'sponsored'` | `'user'`) and `storage` (`'operator'` |\n * `'user'`). Optional; the settings below decide when it's left out. When set, it supplies\n * their defaults (e.g. `gas: 'user'` makes Thirdweb wallets unsponsored) and `initPublish`\n * throws on a contradiction. See `resolvePublishPayment`.\n */\n payment?: import('./payment').PublishPaymentConfig\n /**\n * EntryPoint v0.8 bundler for the permissionless EIP-7702 `SeedTxSender` used by non-Thirdweb\n * wallets. Setting it switches `accountMode` to `eip7702`. Not used by Thirdweb wallets: a local\n * twin's (v0.6) bundler goes in {@link ThirdwebWalletOptions.bundlerUrl}. A bundler that\n * reports no v0.8 support is rejected when the sender is created.\n */\n bundlerUrl?: string\n /**\n * Paymaster / sponsorship endpoint for permissionless EIP-7702 sends. Defaults to `bundlerUrl`,\n * so the bundler is asked to sponsor; set `payment: { gas: 'user' }` to send without a paymaster.\n */\n paymasterUrl?: string\n /**\n * How non-Thirdweb wallets submit txs. Defaults to `eip7702` when `bundlerUrl` is set, else `eoa`.\n */\n accountMode?: PublishAccountMode\n /** Upload API base URL (e.g. from VITE_UPLOAD_API_BASE_URL or NEXT_PUBLIC_UPLOAD_API_BASE_URL). Also used for bundler when useArweaveBundler is true. */\n uploadApiBaseUrl: string\n /**\n * Gateway transport for publish + read paths. Prefer resolving once via\n * `resolveSeedGatewayEndpoints(seedGatewayConfigFromSeedConfig(config))` at app bootstrap\n * and passing `uploadApiBaseUrl` / `arweaveGraphqlUrl` from the result.\n */\n gatewayTransport?: 'http-gateway' | 'hyper' | 'hybrid'\n /** Operator Gateway Hyper key (z32) — informational; sidecar is configured separately. */\n gatewayHyperKey?: string\n /**\n * Optional origin for verifying uploads via `GET /api/upload/arweave/data/:id`.\n * Defaults to {@link uploadApiBaseUrl} (e.g. set `ARWEAVE_UPLOAD_API_BASE_URL` as `uploadApiBaseUrl`).\n */\n arweaveUploadVerificationBaseUrl?: string\n /**\n * Arweave gateway GraphQL URL for resolving L1 bundle tx ids after bundler upload.\n * Defaults to {@link DEFAULT_ARWEAVE_GRAPHQL_URL}.\n */\n arweaveGraphqlUrl?: string\n /**\n * Bypass the SeedProtocol contract and call EAS attest/multiAttest directly from the user's wallet.\n * Default: false (uses contract multiPublish).\n */\n useDirectEas?: boolean\n /**\n * Seed executor module (SeedProtocolExecutor). Must match the executor pinned by the\n * ManagedAccount's `SeedExecutorRouterExtension` (`readFactorySeedExecutor` reads it from the\n * factory). When set, onConnect / publish prep install it with `installSeedExecutor()` if\n * missing; accounts without the extension are skipped.\n */\n modularAccountModuleContract?: string\n /** Unused: `installSeedExecutor()` takes no install data. */\n modularAccountModuleData?: string\n /**\n * Use the modular executor for multiPublish.\n * Default: false (uses the smart wallet executor).\n */\n useModularExecutor?: boolean\n /**\n * When true (and `useModularExecutor`), attempts to deploy / bootstrap the modular in-app wallet’s\n * EIP-7702 smart account on the publish chain via Thirdweb’s `deploySmartAccount` when bytecode is still empty.\n * When **undefined** and `useModularExecutor` is true, defaults to **true**. Set explicitly to **false** to surface\n * an error instead of auto-deploying.\n */\n autoDeployEip7702ModularAccount?: boolean\n /**\n * When true (and `useModularExecutor`), attempts to deploy the ManagedAccount via the factory\n * if it is not yet deployed on the publish chain. Default: false (surface `managed_not_ready` instead).\n */\n autoDeployManagedAccount?: boolean\n /**\n * Optional override for automatic ManagedAccount factory deploy when {@link autoDeployManagedAccount} is true.\n * When unset, uses Thirdweb `deploySmartAccount` on the managed EIP-4337 in-app wallet account.\n */\n deployManagedAccount?: (params: {\n managedAddress: string\n managedSigningAccount: import('./helpers/seedSigner').PublishWallet\n }) => Promise<void>\n /**\n * Called when optional wallet setup steps fail after connect (e.g. executor module install).\n */\n onWalletSetupWarning?: (error: unknown) => void\n /**\n * EXPERIMENTAL: Use Arweave bundler for instant uploads instead of reimbursement + chunk upload.\n * When true, skips sendReimbursementRequest, pollForConfirmation, and chunk-by-chunk uploadData.\n * Uses uploadApiBaseUrl for the bundler endpoint. Not yet validated for production.\n */\n useArweaveBundler?: boolean\n /**\n * Tags appended to every Arweave upload after Content-SHA-256 / Content-Type (e.g. App-Name).\n * Merged at publish time with {@link CreatePublishOptions.arweaveUploadTags} as\n * `[...config, ...options]`.\n */\n arweaveUploadTags?: TransactionTag[]\n /**\n * Default Html embedded data-URI policy for publishes when not overridden per {@link CreatePublishOptions}.\n * Default behavior when unset: `materialize`.\n */\n htmlEmbeddedDataUriPolicy?: import('./types').HtmlEmbeddedDataUriPolicy\n /**\n * Optional fallback: Sign Arweave upload transactions (non-bundler path). Prefer passing at createPublish time.\n */\n signArweaveTransactions?: (\n uploads: SerializedPublishUpload[]\n ) => Promise<ArweaveTransactionInfoResult[]>\n /**\n * Optional fallback: Arweave JWK for in-process signing (non-bundler path). Prefer passing at createPublish time.\n * A publish restored after a reload never has the per-publish JWK (it is not saved to the\n * database), so it signs with this one, or fails at creatingArweaveTransactions without it.\n */\n arweaveJwk?: { kty: string; n: string; e: string; d?: string; [key: string]: unknown }\n /**\n * Optional fallback: Signer for DataItem creation when useArweaveBundler is true. Prefer passing at createPublish time.\n */\n dataItemSigner?: ethers.Wallet | import('./helpers/seedSigner').SeedSigner\n /**\n * Optional fallback: Sign DataItems when useArweaveBundler is true. Prefer passing at createPublish time.\n * Each upload includes `tags` (content + configured {@link arweaveUploadTags}); forward them into the DataItem.\n */\n signDataItems?: (\n uploads: import('./services/publish/helpers/getPublishUploadData').PublishUploadData[]\n ) => Promise<ArweaveDataItemInfoResult[]>\n /**\n * Optional USD spot prices for publish cost estimates. When unset, Coinbase ETH-USD / AR-USD spots are used.\n * Results are cached for 60s.\n */\n getTokenPrices?: () => Promise<{ ethUsd: number; arUsd: number }>\n /**\n * Called when an author publish run reaches success with the resolved batch UID list.\n * Tool backends use this to call {@link import('./services/publishedBy').attestPublishedBy}.\n * Per-publish {@link CreatePublishOptions.onPublished} overrides this when set.\n */\n onPublished?: import('./services/publishedBy').OnPublishedCallback\n /**\n * Approves each publish before it spends anything; return `false` to refuse, or `{ token }` to\n * send a token to the upload API with the publish's requests. See {@link AuthorizePublish}.\n */\n authorizePublish?: import('./authorization').AuthorizePublish\n}\n\n/** Options passed at createPublish time. Signers here override config fallbacks. */\nexport interface CreatePublishOptions {\n /** `patch` (default): pending properties only. `new_version`: new Version attestation + all properties. */\n publishMode?: import('./types').PublishMode\n /**\n * Required when useArweaveBundler: sign DataItems (wallet flow).\n * Use each upload's `tags` when building the signed DataItem.\n */\n signDataItems?: (\n uploads: import('./services/publish/helpers/getPublishUploadData').PublishUploadData[]\n ) => Promise<ArweaveDataItemInfoResult[]>\n /** Required when useArweaveBundler: signer for DataItems (backend/script flow) */\n dataItemSigner?: ethers.Wallet | import('./helpers/seedSigner').SeedSigner\n /** Required when NOT useArweaveBundler: sign Arweave transactions */\n signArweaveTransactions?: (\n uploads: SerializedPublishUpload[]\n ) => Promise<ArweaveTransactionInfoResult[]>\n /**\n * Required when NOT useArweaveBundler: JWK for in-process signing. Kept in memory only; it is\n * stripped from the saved publish snapshot, so a publish resumed after a reload falls back to\n * {@link PublishConfig.arweaveJwk}.\n */\n arweaveJwk?: { kty: string; n: string; e: string; d?: string; [key: string]: unknown }\n /**\n * Extra tags for this publish only, appended after {@link PublishConfig.arweaveUploadTags}.\n * Resolved order: `[...initPublishTags, ...theseTags]`.\n */\n arweaveUploadTags?: TransactionTag[]\n /**\n * Default for Html embedded data-URI handling when a property does not set `htmlEmbeddedDataUriPolicy`.\n * Default: `materialize`.\n */\n htmlEmbeddedDataUriPolicy?: import('./types').HtmlEmbeddedDataUriPolicy\n /**\n * Called when this publish run succeeds with the resolved Seed/Version/property UID batch.\n * Overrides {@link PublishConfig.onPublished} when both are set.\n */\n onPublished?: import('./services/publishedBy').OnPublishedCallback\n /** Overrides {@link PublishConfig.authorizePublish} for this publish. */\n authorizePublish?: import('./authorization').AuthorizePublish\n}\n\n/** Internal: module-level config ref set by PublishProvider on mount. */\nlet configRef: PublishConfig | null = null\n\n/**\n * Internal: Set config ref. Called by PublishProvider on mount or initPublish.\n */\nexport function setConfigRef(c: PublishConfig | null): void {\n configRef = c\n}\n\n/**\n * Internal: Get current config ref. Used by PublishProvider when config is not passed.\n */\nexport function getConfigRef(): PublishConfig | null {\n return configRef\n}\n\n/**\n * Initialize the publish package. Call once before using PublishManager or other publish APIs.\n * Registers the config and SDK hooks: the publish executor behind `item.publish()`, the\n * revoke executor behind `item.unpublish()`, getPublisherForNewSeeds, etc. Until this runs,\n * `item.publish()` and `item.unpublish()` throw.\n * For React apps, you can alternatively pass config to PublishProvider.\n */\nexport function initPublish(c: PublishConfig): void {\n assertPublishPaymentConfig(c)\n // Fail fast on chains without a known EAS deployment and no address overrides.\n const easChain = resolvePublishEasChain(c)\n // Point SDK reads (EAS sync, schema lookups) at the chain we publish to. Throws when\n // SeedConfig.eas.chainId names a different chain.\n configureEasReadChain('publish', { chainId: easChain.chainId, indexerUrl: easChain.indexerUrl })\n setConfigRef(c)\n setGetPublisherForNewSeeds(async () => {\n const wallet = getPublishWallet()\n if (wallet?.publisherAddress) return wallet.publisherAddress\n if (wallet?.signer?.address) return wallet.signer.address\n return undefined\n })\n setPublishExecutor(publishItem)\n setRevokeExecutor(revokeAttestations)\n // Polls every 45 s; one tab is enough (docs/MULTI_TAB.md). Starts on takeover if this tab\n // isn't the leader yet.\n void whenLeaderTab()\n .then(() => import('./services/arweaveL1Finalize/worker'))\n .then((m) => {\n m.startArweaveL1FinalizeWorker()\n })\n setAdditionalSyncAddresses(async () => {\n if (c.useModularExecutor && c.modularAccountModuleContract) {\n return [c.modularAccountModuleContract]\n }\n return []\n })\n}\n\n/** Alias for initPublish. Use initPublish for the primary API. */\nexport const configurePublish = initPublish\n\nexport interface ResolvedPublishConfig extends PublishConfig {\n /**\n * ManagedAccount factory on the publish chain, or undefined when none is known for this chain.\n * Use {@link requireManagedAccountFactoryAddress} where a factory is mandatory.\n */\n thirdwebAccountFactoryAddress: string | undefined\n uploadApiBaseUrl: string\n /** Resolved verification origin (defaults to uploadApiBaseUrl). */\n arweaveUploadVerificationBaseUrl: string\n /** Resolved GraphQL endpoint for L1 tx resolution (defaults to DEFAULT_ARWEAVE_GRAPHQL_URL). */\n arweaveGraphqlUrl: string\n easContractAddress: string\n schemaRegistryAddress: string\n /** EAS deployment for the publish chain (addresses, indexer and explorer URLs). */\n easChain: EasChainDeployment\n useDirectEas: boolean\n modularAccountModuleData: string\n useModularExecutor: boolean\n useArweaveBundler: boolean\n /** Resolved: defaults to false. */\n autoDeployManagedAccount: boolean\n /**\n * Resolved: when `useModularExecutor` is true, defaults to true unless explicitly false.\n */\n autoDeployEip7702ModularAccount: boolean\n /** Resolved viem chain (defaults to Optimism Sepolia; see `DEFAULT_PUBLISH_CHAIN`). */\n chain: Chain\n /** Resolved account mode for non-Thirdweb senders. */\n accountMode: PublishAccountMode\n /** Resolved Thirdweb wallet settings (defaults applied). */\n thirdweb: ResolvedThirdwebWalletOptions\n}\n\nexport type ResolvedThirdwebWalletOptions = {\n bundlerUrl: string | undefined\n sponsorGas: boolean\n modularWalletMode: 'EIP7702' | 'EOA'\n}\n\n/** Applies defaults to {@link PublishConfig.thirdweb}. */\nexport function resolveThirdwebWalletOptions(\n config: Pick<PublishConfig, 'thirdweb' | 'payment'> | null | undefined,\n): ResolvedThirdwebWalletOptions {\n const tw = config?.thirdweb ?? {}\n return {\n bundlerUrl: tw.bundlerUrl?.trim() || undefined,\n sponsorGas: resolveSponsorGas(config ?? {}),\n modularWalletMode: tw.modularWalletMode ?? 'EIP7702',\n }\n}\n\n/**\n * Returns the resolved publish config: defaults, env-driven fields, and\n * {@link ResolvedPublishConfig.autoDeployEip7702ModularAccount}.\n *\n * Reads the ref set by {@link initPublish} or {@link PublishProvider} with a `config` prop.\n * **Throws** if publish has not been initialized (same error as other publish APIs).\n */\nexport function getPublishConfig(): ResolvedPublishConfig {\n const config = configRef\n if (!config) {\n throw new Error(\n '@seedprotocol/publish: Call initPublish() or ensure PublishProvider is mounted with config before using the publish package'\n )\n }\n const useArweaveBundler = resolveUseArweaveBundler(config)\n const arweaveUploadVerificationBaseUrl =\n config.arweaveUploadVerificationBaseUrl ?? config.uploadApiBaseUrl\n const arweaveGraphqlUrl = config.arweaveGraphqlUrl ?? DEFAULT_ARWEAVE_GRAPHQL_URL\n const useModularExecutor = config.useModularExecutor ?? false\n const chain = config.chain ?? DEFAULT_PUBLISH_CHAIN\n const easChain = resolvePublishEasChain(config)\n const accountMode: PublishAccountMode =\n config.accountMode ?? (config.bundlerUrl ? 'eip7702' : 'eoa')\n return {\n ...config,\n thirdwebAccountFactoryAddress:\n config.managedAccountFactoryAddress ?? MANAGED_ACCOUNT_FACTORY_ADDRESSES[chain.id],\n easContractAddress: easChain.easContractAddress,\n schemaRegistryAddress: easChain.schemaRegistryAddress,\n easChain,\n useDirectEas: config.useDirectEas ?? false,\n modularAccountModuleData: config.modularAccountModuleData ?? '0x',\n useModularExecutor,\n useArweaveBundler,\n arweaveUploadVerificationBaseUrl,\n arweaveGraphqlUrl,\n autoDeployManagedAccount: config.autoDeployManagedAccount ?? false,\n autoDeployEip7702ModularAccount: resolveAutoDeployEip7702ModularAccount(config, useModularExecutor),\n chain,\n accountMode,\n thirdweb: resolveThirdwebWalletOptions(config),\n }\n}\n\n/**\n * EAS deployment for the configured chain, with {@link PublishConfig.easContractAddress} /\n * {@link PublishConfig.schemaRegistryAddress} overrides applied.\n */\nexport function resolvePublishEasChain(config: PublishConfig): EasChainDeployment {\n const chain = config.chain ?? DEFAULT_PUBLISH_CHAIN\n try {\n return resolveEasChainDeployment(chain.id, {\n name: chain.name,\n easContractAddress: config.easContractAddress as `0x${string}` | undefined,\n schemaRegistryAddress: config.schemaRegistryAddress as `0x${string}` | undefined,\n })\n } catch (error) {\n throw new Error(\n `@seedprotocol/publish: ${chain.name} (chain ${chain.id}) has no known EAS deployment. Pass easContractAddress and schemaRegistryAddress in initPublish / PublishProvider config.`,\n { cause: error },\n )\n }\n}\n\n/** ManagedAccount factory for the publish chain; throws when none is configured. */\nexport function requireManagedAccountFactoryAddress(): string {\n const { thirdwebAccountFactoryAddress, chain } = getPublishConfig()\n if (!thirdwebAccountFactoryAddress) {\n throw new Error(\n `@seedprotocol/publish: no ManagedAccount factory is known for ${chain.name} (chain ${chain.id}). Pass managedAccountFactoryAddress in publish config, or use the EOA / direct EAS path.`,\n )\n }\n return thirdwebAccountFactoryAddress\n}\n\n/** @internal Exported for unit tests. */\nexport function resolveAutoDeployEip7702ModularAccount(\n config: PublishConfig,\n useModularExecutor: boolean,\n): boolean {\n if (config.autoDeployEip7702ModularAccount === true) return true\n if (config.autoDeployEip7702ModularAccount === false) return false\n return useModularExecutor\n}\n","import type { Chain } from 'viem'\nimport { getPublishConfig } from '../config'\nimport { DEFAULT_PUBLISH_CHAIN } from './defaultChain'\n\nexport { DEFAULT_PUBLISH_CHAIN }\n\n/**\n * Resolved viem chain for public client + adapters.\n */\nexport function getPublishViemChain(): Chain {\n try {\n return getPublishConfig().chain ?? DEFAULT_PUBLISH_CHAIN\n } catch {\n return DEFAULT_PUBLISH_CHAIN\n }\n}\n\n/**\n * Resolved RPC URL. Prefer explicit `rpcUrl`; fall back to Thirdweb edge URL when client id is set.\n */\nexport function getPublishRpcUrl(): string {\n const config = getPublishConfig()\n if (config.rpcUrl) return config.rpcUrl\n if (config.thirdwebClientId) {\n const chainId = (config.chain ?? DEFAULT_PUBLISH_CHAIN).id\n return `https://${chainId}.rpc.thirdweb.com/${config.thirdwebClientId}`\n }\n throw new Error(\n '@seedprotocol/publish: rpcUrl is required when thirdwebClientId is not set. A thirdwebSecretKey authenticates Thirdweb RPC but does not build this URL. Pass rpcUrl or thirdwebClientId in initPublish / PublishProvider config.',\n )\n}\n\n/** Display name of the publish chain for user-facing messages. */\nexport function getPublishChainName(): string {\n return getPublishViemChain().name\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAUA,IAAakE,KACX,sEAMWC,KAA6E,EACxF,UAAU,6CACZ,GAqBaC,KACX,8CAMWC,KACXD,IAEWE,KAAuB;CAClC,SAAS;CACT,SAAS;AACX,GAGaC,KAA8B;CACzC;CACA;CACA;CACA;AACF,G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