@nexus-cross/pop 1.4.1-beta.6 → 1.4.1-beta.8

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/AGENTS.md CHANGED
@@ -158,7 +158,7 @@ await safeDrop.refund({ claimAddress, sponsor: address });
158
158
 
159
159
  ```ts
160
160
  const { txHashes, recipient } = await safeDrop.batchClaim({
161
- id: myHandle, // normalized internally
161
+ id: myHandle, // API/result preserve it; contract calls normalize it
162
162
  oauth, // X OAuth proof (handle ownership)
163
163
  sponsor: sender,
164
164
  claimAddress,
@@ -224,8 +224,7 @@ The SDK does not wrap it — use `EventSource` directly. Delivery is best-effort
224
224
  `maxBatchGas`; calibrate these values below the chain block gas limit.
225
225
  6. **`message` ≤ 140 runes** (code points) and `envelopeId` must come from `listEnvelopes()`;
226
226
  otherwise the backend rejects with `INVALID_PARAM` / `ENVELOPE_NOT_FOUND`.
227
- 7. **Handles are normalized** by the SDK (`normalizeHandle`); pass the same handle to deposit and
228
- to the API — do not hand-roll a second normalization.
227
+ 7. **Handle API values are preserved; contract calls are normalized** by `normalizeHandle`.
229
228
  8. **Drops are keyed by bytes32.** Resolve `activeDropOf(claimAddress)` before `drops(dropKey)`.
230
229
 
231
230
  ## 7. API surface
@@ -81,7 +81,7 @@ interface RefundResult {
81
81
  readonly txHash: Hex;
82
82
  }
83
83
  interface BatchClaimParams {
84
- /** 소셜 식별자(내 핸들). 내부에서 normalizeHandle을 거친다. */
84
+ /** 소셜 식별자(내 X 핸들). 컨트랙트 호출 canonical ID로 정규화한다. */
85
85
  id: Id;
86
86
  /** 핸들 소유 증명용 X OAuth 토큰. 서명 발급의 전제. */
87
87
  oauth: OAuthProof;
@@ -1,8 +1,8 @@
1
- import { C as CryptoPort, b as ClaimSignerPort, a as SafeDropChainPort, O as OnePopDrop, D as DropState, S as SafeDrop } from '../createSafeDrop-BGoIQ4nK.js';
2
- import { S as Secret, a as SecretHash, H as Hex, A as Address, I as Id, m as SafeDropApiPort } from '../SafeDropApiPort-B7NfQOsb.js';
1
+ import { C as CryptoPort, b as ClaimSignerPort, a as SafeDropChainPort, O as OnePopDrop, D as DropState, S as SafeDrop } from '../createSafeDrop-DCCWJRxc.js';
2
+ import { S as Secret, a as SecretHash, H as Hex, A as Address, I as Id, m as SafeDropApiPort } from '../SafeDropApiPort-CsPo0Pmn.js';
3
3
  import { PublicClient, WalletClient, Chain, Transport, Abi } from 'viem';
4
- import { H as HttpSafeDropApiAdapterOptions } from '../index-DVeDD7Dp.js';
5
- export { C as CrossAuthClient, a as CrossAuthClientOptions, D as DEFAULT_POP_API_PATHS, b as HttpSafeDropApiAdapter, c as HttpXAuthAdapter, d as HttpXAuthAdapterOptions, O as ONE_POP_BPS_DENOMINATOR, e as ONE_POP_DEPLOYMENTS, f as ONE_POP_FEE_BPS, P as Pkce, g as PopApiPaths, h as PopContracts, i as PopDeployment, j as PopEnvironment, S as SessionStore, X as XAuthClient, k as XAuthClientOptions, l as generatePkce, m as generateState, n as getCrossAuthBaseUrl, o as getOnePopApiBaseUrl, p as getOnePopContracts, q as getOnePopDeployment, r as getPopEnvironment } from '../index-DVeDD7Dp.js';
4
+ import { H as HttpSafeDropApiAdapterOptions } from '../index-CF1w6xbD.js';
5
+ export { C as CrossAuthClient, a as CrossAuthClientOptions, D as DEFAULT_POP_API_PATHS, b as HttpSafeDropApiAdapter, c as HttpXAuthAdapter, d as HttpXAuthAdapterOptions, O as ONE_POP_BPS_DENOMINATOR, e as ONE_POP_DEPLOYMENTS, f as ONE_POP_FEE_BPS, P as Pkce, g as PopApiPaths, h as PopContracts, i as PopDeployment, j as PopEnvironment, S as SessionStore, X as XAuthClient, k as XAuthClientOptions, l as generatePkce, m as generateState, n as getCrossAuthBaseUrl, o as getOnePopApiBaseUrl, p as getOnePopContracts, q as getOnePopDeployment, r as getPopEnvironment } from '../index-CF1w6xbD.js';
6
6
  import '../XAuthPort-BNJePosj.js';
7
7
 
8
8
  /**
@@ -1 +1 @@
1
- import{j as N}from"../chunk-M7FFQCP2.js";import{a as Z,b as q,c as $,d as X,e as j,g as Y,h as D,i as z,j as J,k as P,l as Q,m as ee,n as te,o as ne,p as ie}from"../chunk-ENB6CCH7.js";import{a as d}from"../chunk-5DT3H2VX.js";import{bytesToHex as ae,keccak256 as se,recoverAddress as re,toBytes as pe}from"viem";var l=class{keccak256(e){return se(pe(e))}randomSecret(){let e=new Uint8Array(32);return de().getRandomValues(e),ae(e).slice(2)}recoverAddress(e){return re({hash:e.digest,signature:e.signature})}};function de(){let r=globalThis.crypto;if(!r||typeof r.getRandomValues!="function")throw new Error("Secure crypto RNG (globalThis.crypto.getRandomValues) is unavailable");return r}import{serializeSignature as oe,sign as ye}from"viem/accounts";var h=class{async signDigest(e){try{let t=await ye({hash:e.digest,privateKey:e.claimKey});return oe(t)}catch(t){throw new d("SIGN_FAILED","Failed to sign claim digest with temp key",{cause:t instanceof Error?t.message:String(t)})}}};import{BaseError as G,ContractFunctionRevertedError as K,createWalletClient as ce,http as me,keccak256 as I,parseEventLogs as le,parseSignature as B,toBytes as f,toHex as V}from"viem";import{privateKeyToAccount as he,serializeSignature as _,sign as F}from"viem/accounts";var E=[{name:"sponsor",type:"address"},{name:"amount",type:"uint96"},{name:"claimAddr",type:"address"},{name:"recipient",type:"address"},{name:"secretHash",type:"bytes32"},{name:"id",type:"string"}],S=[{name:"dropKeys",type:"bytes32[]"},{name:"records",type:"tuple[]",components:E}],ue=["AlreadyMapped","AmountOverflow","BelowMinDeposit","ChangeAlreadyRequested","ChangeInProgress","CountExceedsPending","DropAlreadyExists","DropNotFound","ECDSAInvalidSignature","EmptyId","IdMismatch","IdNotMapped","InvalidClaimSignature","InvalidExecutor","InvalidShortString","InvalidValidatorNonce","InvalidValidatorSignature","NoPendingChange","NotRecipient","NotSponsor","PendingLimitExceeded","RecipientNotEmpty","ReentrancyGuardReentrantCall","SameRecipient","SecretMismatch","TokenNotEighteenDecimals","ValidatorSigExpired","ZeroAmount","ZeroClaimAddress","ZeroCount","ZeroFeeRecipient","ZeroRecipient","ZeroSbt","ZeroSecretHash","ZeroToken","ZeroValidator"],R=[...ue.map(r=>({type:"error",name:r,inputs:[]})),{type:"error",name:"ECDSAInvalidSignatureLength",inputs:[{name:"length",type:"uint256"}]},{type:"error",name:"ECDSAInvalidSignatureS",inputs:[{name:"s",type:"bytes32"}]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address"}]},{type:"error",name:"StringTooLong",inputs:[{name:"str",type:"string"}]}],s=[{type:"event",name:"Deposited",inputs:[{name:"addr",type:"address",indexed:!0},{name:"sponsor",type:"address",indexed:!0},{name:"dropKey",type:"bytes32",indexed:!0},{name:"amount",type:"uint256",indexed:!1},{name:"id",type:"string",indexed:!1},{name:"secretHash",type:"bytes32",indexed:!1},{name:"token",type:"address",indexed:!1}],anonymous:!1},{type:"function",name:"activeDropOf",stateMutability:"view",inputs:[{name:"sponsor",type:"address"},{name:"claimAddr",type:"address"}],outputs:[{type:"bytes32"}]},{type:"function",name:"drops",stateMutability:"view",inputs:[{name:"dropKey",type:"bytes32"}],outputs:E},{type:"function",name:"token",stateMutability:"view",inputs:[],outputs:[{type:"address"}]},{type:"function",name:"claimDigest",stateMutability:"view",inputs:[{name:"recipient",type:"address"},{name:"id",type:"string"},{name:"dropKey",type:"bytes32"}],outputs:[{type:"bytes32"}]},{type:"function",name:"anchorClaimDigest",stateMutability:"view",inputs:[{name:"recipient",type:"address"},{name:"id",type:"string"},{name:"dropKey",type:"bytes32"}],outputs:[{type:"bytes32"}]},{type:"function",name:"claimedRecipientOf",stateMutability:"view",inputs:[{name:"id",type:"string"}],outputs:[{type:"address"}]},{type:"function",name:"pendingDropsByXid",stateMutability:"view",inputs:[{name:"id",type:"string"}],outputs:S},{type:"function",name:"pendingDropsByRecipient",stateMutability:"view",inputs:[{name:"recipient",type:"address"}],outputs:S},{type:"function",name:"pendingDropsOf",stateMutability:"view",inputs:[{name:"sponsor",type:"address"}],outputs:S},{type:"function",name:"depositMapped",stateMutability:"nonpayable",inputs:[{name:"amount",type:"uint256"},{name:"id",type:"string"},{name:"permitDeadline",type:"uint256"},{name:"v",type:"uint8"},{name:"r",type:"bytes32"},{name:"s",type:"bytes32"}],outputs:[]},{type:"function",name:"withdrawUnmapped",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"id",type:"string"},{name:"dropKey",type:"bytes32"},{name:"signature",type:"bytes"},{name:"secret",type:"bytes"}],outputs:[]},{type:"function",name:"withdrawUnmappedBatchByKeys",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"id",type:"string"},{name:"anchorDropKey",type:"bytes32"},{name:"signature",type:"bytes"},{name:"secret",type:"bytes"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"executor",type:"address"},{name:"dropKeys",type:"bytes32[]"},{name:"validatorSignature",type:"bytes"}],outputs:[]},{type:"function",name:"withdrawMapped",stateMutability:"nonpayable",inputs:[{name:"dropKey",type:"bytes32"}],outputs:[]},{type:"function",name:"batchWithdrawMapped",stateMutability:"nonpayable",inputs:[{name:"count",type:"uint256"}],outputs:[]},{type:"function",name:"batchWithdrawMapped",stateMutability:"nonpayable",inputs:[{name:"dropKeys",type:"bytes32[]"}],outputs:[]},{type:"function",name:"refund",stateMutability:"nonpayable",inputs:[{name:"dropKey",type:"bytes32"}],outputs:[]},{type:"function",name:"changeNonceById",stateMutability:"view",inputs:[{name:"idKey",type:"bytes32"}],outputs:[{type:"uint256"}]},{type:"function",name:"pendingRecipientChange",stateMutability:"view",inputs:[{name:"idKey",type:"bytes32"}],outputs:[{name:"newRecipient",type:"address"}]},{type:"function",name:"requestRecipientChange",stateMutability:"nonpayable",inputs:[{name:"id",type:"string"},{name:"newRecipient",type:"address"}],outputs:[]},{type:"function",name:"completeRecipientChange",stateMutability:"nonpayable",inputs:[{name:"id",type:"string"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"validatorSignature",type:"bytes"}],outputs:[]},{type:"function",name:"cancelRecipientChange",stateMutability:"nonpayable",inputs:[{name:"id",type:"string"}],outputs:[]},{type:"function",name:"resetRecipient",stateMutability:"nonpayable",inputs:[{name:"id",type:"string"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"validatorSignature",type:"bytes"}],outputs:[]},...R];var T=[{type:"function",name:"deposit",stateMutability:"nonpayable",inputs:[{name:"claimAddr",type:"address"},{name:"amount",type:"uint256"},{name:"id",type:"string"},{name:"secretHash",type:"bytes32"},{name:"deadline",type:"uint256"},{name:"v",type:"uint8"},{name:"r",type:"bytes32"},{name:"s",type:"bytes32"}],outputs:[]},{type:"function",name:"token",stateMutability:"view",inputs:[],outputs:[{type:"address"}]},...R],b=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"nonces",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"eip712Domain",stateMutability:"view",inputs:[],outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}]}],H={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]};var g=[{type:"function",name:"validator",stateMutability:"view",inputs:[],outputs:[{type:"address"}]},{type:"function",name:"validatorClaimDigest",stateMutability:"view",inputs:[{name:"executor",type:"address"},{name:"recipient",type:"address"},{name:"id",type:"string"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}],outputs:[{type:"bytes32"}]},{type:"function",name:"validatorNonceById",stateMutability:"view",inputs:[{name:"idHash",type:"bytes32"}],outputs:[{type:"uint256"}]},{type:"function",name:"claimedRecipientOf",stateMutability:"view",inputs:[{name:"id",type:"string"}],outputs:[{type:"address"}]},{type:"error",name:"ValidatorSigExpired",inputs:[]},{type:"error",name:"InvalidValidatorNonce",inputs:[]}];var be="0x0000000000000000000000000000000000000000",ge=`0x${"00".repeat(32)}`,fe={gas:BigInt(1e6),batchBaseGas:BigInt(1e6),batchGasPerDrop:BigInt(75e4),maxBatchGas:BigInt(3e7),maxFeePerGas:BigInt(4e9),maxPriorityFeePerGas:BigInt(1e9)},k=BigInt(1800),w=class{constructor(e){if(this.address=e.address,this.publicClient=e.publicClient,this.walletClient=e.walletClient,this.chain=e.chain,this.transport=e.transport??me(),this.transactionFees={...fe,...e.withdrawFees,...e.transactionFees},this.transactionFees.gas<=BigInt(0)||this.transactionFees.batchBaseGas<=BigInt(0)||this.transactionFees.batchGasPerDrop<=BigInt(0)||this.transactionFees.maxBatchGas<=BigInt(0)||this.transactionFees.maxFeePerGas<=BigInt(0)||this.transactionFees.maxPriorityFeePerGas<=BigInt(0)||this.transactionFees.maxPriorityFeePerGas>this.transactionFees.maxFeePerGas)throw new d("INVALID_PARAM","invalid EIP-1559 gas configuration");this.depositWithPermit=t=>this.permitDeposit(t)}async getDropByKey(e){try{let[t,n,i,a,o,y]=await this.publicClient.readContract({address:this.address,abi:s,functionName:"drops",args:[e]});return t.toLowerCase()===be?null:{dropKey:e,sponsor:t,amount:n,claimAddress:i,recipient:a,secretHash:o,id:y}}catch(t){throw p("drops",t)}}async getDropKeyByClaimAddress(e,t){try{let n=await this.publicClient.readContract({address:this.address,abi:s,functionName:"activeDropOf",args:[t,e]});return n===ge?null:n}catch(n){throw p("activeDropOf",n)}}async getPendingDropsById(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:s,functionName:"pendingDropsByXid",args:[e.id]});return n.map((i,a)=>M(t[a],i))}catch(t){throw p("pendingDropsByXid",t)}}async getPendingDropsByRecipient(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:s,functionName:"pendingDropsByRecipient",args:[e.recipient]});return n.map((i,a)=>M(t[a],i))}catch(t){throw p("pendingDropsByRecipient",t)}}async getPendingDropsBySponsor(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:s,functionName:"pendingDropsOf",args:[e.sponsor]});return n.map((i,a)=>M(t[a],i))}catch(t){throw p("pendingDropsOf",t)}}async getDrop(e,t){let n=await this.getDropKeyByClaimAddress(e,t);if(!n)return null;let[i,a]=await Promise.all([this.getDropByKey(n),this.escrowToken()]);return i&&a?{...i,token:a}:null}async escrowToken(){try{return await this.publicClient.readContract({address:this.address,abi:T,functionName:"token"})}catch{throw new d("CHAIN_ERROR","token() failed")}}async getClaimDigest(e){try{return await this.publicClient.readContract({address:this.address,abi:s,functionName:"claimDigest",args:[e.recipient,e.id,e.dropKey]})}catch(t){throw p("claimDigest",t)}}async permitDeposit(e){try{let t=this.requireAccount(),n=e.token,[i,a,o]=await Promise.all([this.publicClient.readContract({address:this.address,abi:T,functionName:"token"}),this.publicClient.readContract({address:n,abi:b,functionName:"nonces",args:[t.address]}),this.permitDomain(n)]);if(i.toLowerCase()!==n.toLowerCase())throw new d("INVALID_TOKEN","token does not match the escrow token",{expected:i,received:e.token});let y=BigInt(Math.floor(Date.now()/1e3))+k,u=await this.walletClient.signTypedData({account:t,domain:{...o,chainId:this.chain.id,verifyingContract:n},types:H,primaryType:"Permit",message:{owner:t.address,spender:this.address,value:e.amount,nonce:a,deadline:y}}),{r:C,s:x,v:A,yParity:v}=B(u),c=await this.walletClient.writeContract({address:this.address,abi:T,functionName:"deposit",args:[e.claimAddress,e.amount,e.id,e.secretHash,y,Number(A??BigInt(v+27)),C,x],account:t,chain:this.chain,...this.transactionOverrides()});await e.onSubmitted?.(c);let m=await this.confirm("depositWithPermit",c);return{txHash:c,dropKey:this.depositedDropKey(m.logs,t.address,e.amount,e.id,c)}}catch(t){throw p("depositWithPermit",t)}}async depositMapped(e){try{let t=this.requireAccount(),n=e.token,[i,a,o]=await Promise.all([this.publicClient.readContract({address:this.address,abi:s,functionName:"token"}),this.publicClient.readContract({address:n,abi:b,functionName:"nonces",args:[t.address]}),this.permitDomain(n)]);if(i.toLowerCase()!==n.toLowerCase())throw new d("INVALID_TOKEN","token does not match the escrow token",{expected:i,received:e.token});let y=BigInt(Math.floor(Date.now()/1e3))+k,u=await this.walletClient.signTypedData({account:t,domain:{...o,chainId:this.chain.id,verifyingContract:n},types:H,primaryType:"Permit",message:{owner:t.address,spender:this.address,value:e.amount,nonce:a,deadline:y}}),{r:C,s:x,v:A,yParity:v}=B(u),c=[e.amount,e.id,y,Number(A??BigInt(v+27)),C,x];await this.publicClient.simulateContract({address:this.address,abi:s,functionName:"depositMapped",args:c,account:t});let m=await this.walletClient.writeContract({address:this.address,abi:s,functionName:"depositMapped",args:c,account:t,chain:this.chain,...this.transactionOverrides()});await e.onSubmitted?.(m);let U=await this.confirm("depositMapped",m);return{txHash:m,dropKey:this.depositedDropKey(U.logs,t.address,e.amount,e.id,m)}}catch(t){throw p("depositMapped",t)}}async permitDomain(e){try{let t=await this.publicClient.readContract({address:e,abi:b,functionName:"eip712Domain"});return{name:t[1],version:t[2]}}catch{return{name:await this.publicClient.readContract({address:e,abi:b,functionName:"name"}),version:"1"}}}async withdrawUnmapped(e){try{let t=he(e.claimKey),n=await this.publicClient.readContract({address:this.address,abi:s,functionName:"claimDigest",args:[e.recipient,e.id,e.dropKey]}),i=e.signature??_(await F({hash:n,privateKey:e.claimKey})),o=await ce({account:t,chain:this.chain,transport:this.transport}).writeContract({address:this.address,abi:s,functionName:"withdrawUnmapped",args:[e.recipient,e.id,e.dropKey,i,V(f(e.secret))],...this.transactionOverrides()});return await e.onSubmitted?.(o),await this.confirm("withdrawUnmapped",o),o}catch(t){throw L("withdrawUnmapped",t)}}async withdrawMapped(e){let t=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:s,functionName:"withdrawMapped",args:[e.dropKey],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:s,functionName:"withdrawMapped",args:[e.dropKey],account:t,chain:this.chain,...this.transactionOverrides()});return await e.onSubmitted?.(n),await this.confirm("withdrawMapped",n),n}catch(n){throw p("withdrawMapped",n)}}async batchWithdrawMapped(e){if(!Number.isSafeInteger(e.count)||e.count<=0)throw new d("INVALID_PARAM","count must be a positive safe integer");let t=this.batchTransactionOverrides(e.count),n=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:s,functionName:"batchWithdrawMapped",args:[BigInt(e.count)],account:n});let i=await this.walletClient.writeContract({address:this.address,abi:s,functionName:"batchWithdrawMapped",args:[BigInt(e.count)],account:n,chain:this.chain,...t});return await this.confirm("batchWithdrawMapped",i),i}catch(i){throw p("batchWithdrawMapped",i)}}async batchWithdrawMappedByKeys(e){if(!e.dropKeys.length)throw new d("INVALID_PARAM","dropKeys must not be empty");let t=this.batchTransactionOverrides(e.dropKeys.length),n=this.requireAccount(),i=[e.dropKeys];try{await this.publicClient.simulateContract({address:this.address,abi:s,functionName:"batchWithdrawMapped",args:i,account:n});let a=await this.walletClient.writeContract({address:this.address,abi:s,functionName:"batchWithdrawMapped",args:i,account:n,chain:this.chain,...t});return await this.confirm("batchWithdrawMapped",a),a}catch(a){throw p("batchWithdrawMapped",a)}}async withdrawUnmappedBatchByKeys(e){let t=e.dropKeys.filter(a=>a.toLowerCase()!==e.anchorDropKey.toLowerCase()),n=this.batchTransactionOverrides(t.length+1),i=this.requireAccount();try{let a=await this.publicClient.readContract({address:this.address,abi:s,functionName:"anchorClaimDigest",args:[e.recipient,e.id,e.anchorDropKey]}),o=_(await F({hash:a,privateKey:e.claimKey})),y=await this.walletClient.writeContract({address:this.address,abi:s,functionName:"withdrawUnmappedBatchByKeys",args:[e.recipient,e.id,e.anchorDropKey,o,V(f(e.secret)),e.nonce,e.deadline,e.executor,t,e.validatorSignature],account:i,chain:this.chain,...n});return await this.confirm("withdrawUnmappedBatchByKeys",y),y}catch(a){throw L("withdrawUnmappedBatchByKeys",a)}}async getValidatorNonce(e){try{return await this.publicClient.readContract({address:this.address,abi:g,functionName:"validatorNonceById",args:[I(f(e.id))]})}catch(t){throw p("validatorNonceById",t)}}async getValidatorClaimDigest(e){try{return await this.publicClient.readContract({address:this.address,abi:g,functionName:"validatorClaimDigest",args:[e.executor,e.recipient,e.id,e.nonce,e.deadline]})}catch(t){throw p("validatorClaimDigest",t)}}async getValidator(){try{return await this.publicClient.readContract({address:this.address,abi:g,functionName:"validator"})}catch(e){throw p("validator",e)}}async getClaimedRecipient(e){try{return await this.publicClient.readContract({address:this.address,abi:s,functionName:"claimedRecipientOf",args:[e.id]})}catch(t){throw p("claimedRecipientOf",t)}}async refundByKey(e){let t=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:s,functionName:"refund",args:[e.dropKey],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:s,functionName:"refund",args:[e.dropKey],account:t,chain:this.chain,...this.transactionOverrides()});return await this.confirm("refund",n),n}catch(n){throw p("refund",n)}}async getChangeNonce(e){try{return await this.publicClient.readContract({address:this.address,abi:s,functionName:"changeNonceById",args:[I(f(e.id))]})}catch(t){throw p("changeNonceById",t)}}async getPendingRecipientChange(e){try{return await this.publicClient.readContract({address:this.address,abi:s,functionName:"pendingRecipientChange",args:[I(f(e.id))]})}catch(t){throw p("pendingRecipientChange",t)}}async requestRecipientChange(e){return this.currentContractWrite("requestRecipientChange",[e.id,e.newRecipient])}async completeRecipientChange(e){return this.currentContractWrite("completeRecipientChange",[e.id,e.nonce,e.deadline,e.signature])}async cancelRecipientChange(e){return this.currentContractWrite("cancelRecipientChange",[e.id])}async resetRecipient(e){let t=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:s,functionName:"resetRecipient",args:[e.id,e.nonce,e.deadline,e.signature],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:s,functionName:"resetRecipient",args:[e.id,e.nonce,e.deadline,e.signature],account:t,chain:this.chain,...this.transactionOverrides()});return await this.confirm("resetRecipient",n),n}catch(n){throw p("resetRecipient",n)}}async currentContractWrite(e,t){let n=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:s,functionName:e,args:t,account:n});let i=await this.walletClient.writeContract({address:this.address,abi:s,functionName:e,args:t,account:n,chain:this.chain,...this.transactionOverrides()});return await this.confirm(e,i),i}catch(i){throw p(e,i)}}transactionOverrides(e=this.transactionFees.gas){return{type:"eip1559",gas:e,maxFeePerGas:this.transactionFees.maxFeePerGas,maxPriorityFeePerGas:this.transactionFees.maxPriorityFeePerGas}}batchTransactionOverrides(e){if(!Number.isSafeInteger(e)||e<=0)throw new d("INVALID_PARAM","batch count must be a positive safe integer");let t=this.transactionFees.batchBaseGas+this.transactionFees.batchGasPerDrop*BigInt(e);if(t>this.transactionFees.maxBatchGas)throw new d("INVALID_PARAM","batch gas exceeds maxBatchGas",{count:e,gas:t.toString(),maxBatchGas:this.transactionFees.maxBatchGas.toString()});return this.transactionOverrides(t)}async sponsorWrite(e,t){try{let n=await t();return await this.confirm(e,n),n}catch(n){throw p(e,n)}}depositedDropKey(e,t,n,i,a){let o=le({abi:s,eventName:"Deposited",logs:[...e]}).find(({address:y,args:u})=>y.toLowerCase()===this.address.toLowerCase()&&u.sponsor.toLowerCase()===t.toLowerCase()&&u.amount===n&&u.id===i);if(!o)throw new d("CHAIN_ERROR","deposit receipt omitted the Deposited event",{txHash:a});return o.args.dropKey}async confirm(e,t){let n=await this.publicClient.waitForTransactionReceipt({hash:t});if(n.status!=="success"){let i=await this.recoverRevertName(t,n.blockNumber),a=i?`SafeDrop.${e} reverted: ${i}`:`transaction reverted: ${t}`;throw new d("CHAIN_ERROR",a,{revertName:i,txHash:t})}return n}async recoverRevertName(e,t){try{let n=await this.publicClient.getTransaction({hash:e});await this.publicClient.call({account:n.from,to:n.to??void 0,data:n.input,value:n.value,blockNumber:t});return}catch(n){return O(n)}}requireAccount(){let e=this.walletClient.account;if(!e)throw new d("CHAIN_ERROR","walletClient has no account (connect a wallet first)");return e}};function M(r,e){return{dropKey:r,sponsor:e.sponsor,amount:e.amount,claimAddress:e.claimAddr,recipient:e.recipient,secretHash:e.secretHash,id:e.id}}function p(r,e){if(e instanceof d)return e;let t=O(e),n=e instanceof Error?e.message:String(e),i=t?`SafeDrop.${r} reverted: ${t}`:`SafeDrop.${r} failed`;return new d("CHAIN_ERROR",i,{cause:n,revertName:t})}function L(r,e){if(e instanceof d)return e;let t=O(e),n=e instanceof G?e.walk(o=>{let y=o;return typeof y.code=="number"||y.data!==void 0}):void 0,i={revertName:t};typeof n?.code=="number"&&(i.rpcCode=n.code),typeof n?.details=="string"&&(i.rpcMessage=n.details),typeof n?.data=="string"&&(i.rpcData=n.data);let a=t?`SafeDrop.${r} reverted: ${t}`:`SafeDrop.${r} failed`;return new d("CHAIN_ERROR",a,i)}function O(r){if(!(r instanceof G))return;let e=r.walk(t=>t instanceof K);if(e instanceof K)return e.data?.errorName??e.reason??void 0}var W=[{type:"constructor",inputs:[{name:"token_",type:"address",internalType:"contract IERC20"},{name:"validator_",type:"address",internalType:"address"},{name:"sbt_",type:"address",internalType:"contract ISoulboundToken"},{name:"feeRecipient_",type:"address",internalType:"address"},{name:"minDeposit_",type:"uint256",internalType:"uint256"}],stateMutability:"nonpayable"},{type:"function",name:"FEE_BPS",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"MAX_PENDING_PER_SPONSOR_ID",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"activeDropOf",inputs:[{name:"sponsor",type:"address",internalType:"address"},{name:"claimAddr",type:"address",internalType:"address"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"anchorClaimDigest",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"dropKey",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"batchWithdrawMapped",inputs:[{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"batchWithdrawMapped",inputs:[{name:"count",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"cancelRecipientChange",inputs:[{name:"id",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"changeNonceById",inputs:[{name:"idKey",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"changeRecipientDigest",inputs:[{name:"id",type:"string",internalType:"string"},{name:"newRecipient",type:"address",internalType:"address"},{name:"nonce",type:"uint256",internalType:"uint256"},{name:"deadline",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"claimDigest",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"dropKey",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"claimedRecipientOf",inputs:[{name:"id",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"completeRecipientChange",inputs:[{name:"id",type:"string",internalType:"string"},{name:"nonce",type:"uint256",internalType:"uint256"},{name:"deadline",type:"uint256",internalType:"uint256"},{name:"validatorSignature",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"deposit",inputs:[{name:"claimAddr",type:"address",internalType:"address"},{name:"amount",type:"uint256",internalType:"uint256"},{name:"id",type:"string",internalType:"string"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"permitDeadline",type:"uint256",internalType:"uint256"},{name:"v",type:"uint8",internalType:"uint8"},{name:"r",type:"bytes32",internalType:"bytes32"},{name:"s",type:"bytes32",internalType:"bytes32"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"depositMapped",inputs:[{name:"amount",type:"uint256",internalType:"uint256"},{name:"id",type:"string",internalType:"string"},{name:"permitDeadline",type:"uint256",internalType:"uint256"},{name:"v",type:"uint8",internalType:"uint8"},{name:"r",type:"bytes32",internalType:"bytes32"},{name:"s",type:"bytes32",internalType:"bytes32"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"drops",inputs:[{name:"dropKey",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"sponsor",type:"address",internalType:"address"},{name:"amount",type:"uint96",internalType:"uint96"},{name:"claimAddr",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"eip712Domain",inputs:[],outputs:[{name:"fields",type:"bytes1",internalType:"bytes1"},{name:"name",type:"string",internalType:"string"},{name:"version",type:"string",internalType:"string"},{name:"chainId",type:"uint256",internalType:"uint256"},{name:"verifyingContract",type:"address",internalType:"address"},{name:"salt",type:"bytes32",internalType:"bytes32"},{name:"extensions",type:"uint256[]",internalType:"uint256[]"}],stateMutability:"view"},{type:"function",name:"feeRecipient",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"minDeposit",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"pendingCountOf",inputs:[{name:"sponsor",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"pendingCountOf",inputs:[{name:"sponsor",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"pendingDropsByRecipient",inputs:[{name:"recipient",type:"address",internalType:"address"}],outputs:[{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"records",type:"tuple[]",internalType:"struct ONEpop.Drop[]",components:[{name:"sponsor",type:"address",internalType:"address"},{name:"amount",type:"uint96",internalType:"uint96"},{name:"claimAddr",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]}],stateMutability:"view"},{type:"function",name:"pendingDropsByRecipient",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"offset",type:"uint256",internalType:"uint256"},{name:"limit",type:"uint256",internalType:"uint256"}],outputs:[{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"records",type:"tuple[]",internalType:"struct ONEpop.Drop[]",components:[{name:"sponsor",type:"address",internalType:"address"},{name:"amount",type:"uint96",internalType:"uint96"},{name:"claimAddr",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]},{name:"total",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"pendingDropsByXid",inputs:[{name:"id",type:"string",internalType:"string"}],outputs:[{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"records",type:"tuple[]",internalType:"struct ONEpop.Drop[]",components:[{name:"sponsor",type:"address",internalType:"address"},{name:"amount",type:"uint96",internalType:"uint96"},{name:"claimAddr",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]}],stateMutability:"view"},{type:"function",name:"pendingDropsByXid",inputs:[{name:"id",type:"string",internalType:"string"},{name:"offset",type:"uint256",internalType:"uint256"},{name:"limit",type:"uint256",internalType:"uint256"}],outputs:[{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"records",type:"tuple[]",internalType:"struct ONEpop.Drop[]",components:[{name:"sponsor",type:"address",internalType:"address"},{name:"amount",type:"uint96",internalType:"uint96"},{name:"claimAddr",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]},{name:"total",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"pendingDropsOf",inputs:[{name:"sponsor",type:"address",internalType:"address"}],outputs:[{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"records",type:"tuple[]",internalType:"struct ONEpop.Drop[]",components:[{name:"sponsor",type:"address",internalType:"address"},{name:"amount",type:"uint96",internalType:"uint96"},{name:"claimAddr",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]}],stateMutability:"view"},{type:"function",name:"pendingDropsOf",inputs:[{name:"sponsor",type:"address",internalType:"address"},{name:"offset",type:"uint256",internalType:"uint256"},{name:"limit",type:"uint256",internalType:"uint256"}],outputs:[{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"records",type:"tuple[]",internalType:"struct ONEpop.Drop[]",components:[{name:"sponsor",type:"address",internalType:"address"},{name:"amount",type:"uint96",internalType:"uint96"},{name:"claimAddr",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]},{name:"total",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"pendingRecipientChange",inputs:[{name:"idKey",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"newRecipient",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"refund",inputs:[{name:"dropKey",type:"bytes32",internalType:"bytes32"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"requestRecipientChange",inputs:[{name:"id",type:"string",internalType:"string"},{name:"newRecipient",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"resetRecipient",inputs:[{name:"id",type:"string",internalType:"string"},{name:"nonce",type:"uint256",internalType:"uint256"},{name:"deadline",type:"uint256",internalType:"uint256"},{name:"validatorSignature",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"resetRecipientDigest",inputs:[{name:"id",type:"string",internalType:"string"},{name:"nonce",type:"uint256",internalType:"uint256"},{name:"deadline",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"sbt",inputs:[],outputs:[{name:"",type:"address",internalType:"contract ISoulboundToken"}],stateMutability:"view"},{type:"function",name:"settledCountOf",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"token",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IERC20"}],stateMutability:"view"},{type:"function",name:"validator",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"validatorClaimDigest",inputs:[{name:"executor",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"nonce",type:"uint256",internalType:"uint256"},{name:"deadline",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"validatorNonceById",inputs:[{name:"idKey",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"withdrawMapped",inputs:[{name:"dropKey",type:"bytes32",internalType:"bytes32"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"withdrawUnmapped",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"dropKey",type:"bytes32",internalType:"bytes32"},{name:"signature",type:"bytes",internalType:"bytes"},{name:"secret",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"withdrawUnmappedBatch",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"anchorDropKey",type:"bytes32",internalType:"bytes32"},{name:"signature",type:"bytes",internalType:"bytes"},{name:"secret",type:"bytes",internalType:"bytes"},{name:"nonce",type:"uint256",internalType:"uint256"},{name:"deadline",type:"uint256",internalType:"uint256"},{name:"executor",type:"address",internalType:"address"},{name:"payCount",type:"uint256",internalType:"uint256"},{name:"moveCount",type:"uint256",internalType:"uint256"},{name:"validatorSignature",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"withdrawUnmappedBatchByKeys",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"anchorDropKey",type:"bytes32",internalType:"bytes32"},{name:"signature",type:"bytes",internalType:"bytes"},{name:"secret",type:"bytes",internalType:"bytes"},{name:"nonce",type:"uint256",internalType:"uint256"},{name:"deadline",type:"uint256",internalType:"uint256"},{name:"executor",type:"address",internalType:"address"},{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"validatorSignature",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"Deposited",inputs:[{name:"addr",type:"address",indexed:!0,internalType:"address"},{name:"sponsor",type:"address",indexed:!0,internalType:"address"},{name:"dropKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"id",type:"string",indexed:!1,internalType:"string"},{name:"secretHash",type:"bytes32",indexed:!1,internalType:"bytes32"},{name:"token",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"EIP712DomainChanged",inputs:[],anonymous:!1},{type:"event",name:"FeeCharged",inputs:[{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"gross",type:"uint256",indexed:!1,internalType:"uint256"},{name:"fee",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"Moved",inputs:[{name:"claimAddr",type:"address",indexed:!0,internalType:"address"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"dropKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"sponsor",type:"address",indexed:!1,internalType:"address"},{name:"id",type:"string",indexed:!1,internalType:"string"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"RecipientChangeCancelled",inputs:[{name:"idKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RecipientChangeRequested",inputs:[{name:"idKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RecipientChanged",inputs:[{name:"idKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RecipientMapped",inputs:[{name:"idKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RecipientReset",inputs:[{name:"idKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"Refunded",inputs:[{name:"claimAddr",type:"address",indexed:!0,internalType:"address"},{name:"sponsor",type:"address",indexed:!0,internalType:"address"},{name:"dropKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"id",type:"string",indexed:!1,internalType:"string"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"Withdrawn",inputs:[{name:"claimAddr",type:"address",indexed:!0,internalType:"address"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"sponsor",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"string",indexed:!1,internalType:"string"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token",type:"address",indexed:!1,internalType:"address"},{name:"sbtTokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"dropKey",type:"bytes32",indexed:!1,internalType:"bytes32"}],anonymous:!1},{type:"error",name:"AlreadyMapped",inputs:[]},{type:"error",name:"AmountOverflow",inputs:[]},{type:"error",name:"BelowMinDeposit",inputs:[]},{type:"error",name:"ChangeAlreadyRequested",inputs:[]},{type:"error",name:"ChangeInProgress",inputs:[]},{type:"error",name:"CountExceedsPending",inputs:[]},{type:"error",name:"DropAlreadyExists",inputs:[]},{type:"error",name:"DropNotFound",inputs:[]},{type:"error",name:"ECDSAInvalidSignature",inputs:[]},{type:"error",name:"ECDSAInvalidSignatureLength",inputs:[{name:"length",type:"uint256",internalType:"uint256"}]},{type:"error",name:"ECDSAInvalidSignatureS",inputs:[{name:"s",type:"bytes32",internalType:"bytes32"}]},{type:"error",name:"EmptyId",inputs:[]},{type:"error",name:"IdMismatch",inputs:[]},{type:"error",name:"IdNotMapped",inputs:[]},{type:"error",name:"InvalidClaimSignature",inputs:[]},{type:"error",name:"InvalidExecutor",inputs:[]},{type:"error",name:"InvalidShortString",inputs:[]},{type:"error",name:"InvalidValidatorNonce",inputs:[]},{type:"error",name:"InvalidValidatorSignature",inputs:[]},{type:"error",name:"NoPendingChange",inputs:[]},{type:"error",name:"NotRecipient",inputs:[]},{type:"error",name:"NotSponsor",inputs:[]},{type:"error",name:"PendingLimitExceeded",inputs:[]},{type:"error",name:"RecipientNotEmpty",inputs:[]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]},{type:"error",name:"SameRecipient",inputs:[]},{type:"error",name:"SecretMismatch",inputs:[]},{type:"error",name:"StringTooLong",inputs:[{name:"str",type:"string",internalType:"string"}]},{type:"error",name:"TokenNotEighteenDecimals",inputs:[]},{type:"error",name:"ValidatorSigExpired",inputs:[]},{type:"error",name:"ZeroAmount",inputs:[]},{type:"error",name:"ZeroClaimAddress",inputs:[]},{type:"error",name:"ZeroCount",inputs:[]},{type:"error",name:"ZeroFeeRecipient",inputs:[]},{type:"error",name:"ZeroRecipient",inputs:[]},{type:"error",name:"ZeroSbt",inputs:[]},{type:"error",name:"ZeroSecretHash",inputs:[]},{type:"error",name:"ZeroToken",inputs:[]},{type:"error",name:"ZeroValidator",inputs:[]}];var Te=W;function Ce(r){let e=r.apiPort??new P(r.api),t=new w({address:r.contractAddress??D().onePop,publicClient:r.publicClient,walletClient:r.walletClient,chain:r.chain,transport:r.transport,withdrawFees:r.withdrawFees,transactionFees:r.transactionFees});return N({claimBaseUrl:r.claimBaseUrl},{api:e,chain:t,signer:new h,crypto:new l})}export{Q as CrossAuthClient,X as DEFAULT_POP_API_PATHS,P as HttpSafeDropApiAdapter,ne as HttpXAuthAdapter,s as ONEPOP_ABI,q as ONE_POP_BPS_DENOMINATOR,$ as ONE_POP_DEPLOYMENTS,Z as ONE_POP_FEE_BPS,Te as SAFEDROP_ABI,g as SAFEDROP_VALIDATOR_ABI,h as ViemClaimSignerAdapter,l as ViemCryptoAdapter,w as ViemSafeDropChainAdapter,ie as XAuthClient,Ce as createSafeDropClient,ee as generatePkce,te as generateState,J as getCrossAuthBaseUrl,z as getOnePopApiBaseUrl,D as getOnePopContracts,Y as getOnePopDeployment,j as getPopEnvironment};
1
+ import{i as K}from"../chunk-SOKYXF6V.js";import{a as $,b as X,c as j,d as Y,e as z,g as J,h as S,i as Q,j as ee,k as R,l as te,m as ne,n as ie,o as ae,p as se}from"../chunk-C54CAUVA.js";import{a as d,b as c}from"../chunk-PV4F2RR3.js";import{bytesToHex as re,keccak256 as pe,recoverAddress as de,toBytes as oe}from"viem";var h=class{keccak256(e){return pe(oe(e))}randomSecret(){let e=new Uint8Array(32);return ye().getRandomValues(e),re(e).slice(2)}recoverAddress(e){return de({hash:e.digest,signature:e.signature})}};function ye(){let r=globalThis.crypto;if(!r||typeof r.getRandomValues!="function")throw new Error("Secure crypto RNG (globalThis.crypto.getRandomValues) is unavailable");return r}import{serializeSignature as ce,sign as ue}from"viem/accounts";var b=class{async signDigest(e){try{let t=await ue({hash:e.digest,privateKey:e.claimKey});return ce(t)}catch(t){throw new d("SIGN_FAILED","Failed to sign claim digest with temp key",{cause:t instanceof Error?t.message:String(t)})}}};import{BaseError as U,ContractFunctionRevertedError as V,createWalletClient as le,http as he,keccak256 as O,parseEventLogs as be,parseSignature as _,toBytes as w,toHex as F}from"viem";import{privateKeyToAccount as ge,serializeSignature as k,sign as L}from"viem/accounts";var B=[{name:"sponsor",type:"address"},{name:"amount",type:"uint96"},{name:"claimAddr",type:"address"},{name:"recipient",type:"address"},{name:"secretHash",type:"bytes32"},{name:"id",type:"string"}],H=[{name:"dropKeys",type:"bytes32[]"},{name:"records",type:"tuple[]",components:B}],me=["AlreadyMapped","AmountOverflow","BelowMinDeposit","ChangeAlreadyRequested","ChangeInProgress","CountExceedsPending","DropAlreadyExists","DropNotFound","ECDSAInvalidSignature","EmptyId","IdMismatch","IdNotMapped","InvalidClaimSignature","InvalidExecutor","InvalidShortString","InvalidValidatorNonce","InvalidValidatorSignature","NoPendingChange","NotRecipient","NotSponsor","PendingLimitExceeded","RecipientNotEmpty","ReentrancyGuardReentrantCall","SameRecipient","SecretMismatch","TokenNotEighteenDecimals","ValidatorSigExpired","ZeroAmount","ZeroClaimAddress","ZeroCount","ZeroFeeRecipient","ZeroRecipient","ZeroSbt","ZeroSecretHash","ZeroToken","ZeroValidator"],I=[...me.map(r=>({type:"error",name:r,inputs:[]})),{type:"error",name:"ECDSAInvalidSignatureLength",inputs:[{name:"length",type:"uint256"}]},{type:"error",name:"ECDSAInvalidSignatureS",inputs:[{name:"s",type:"bytes32"}]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address"}]},{type:"error",name:"StringTooLong",inputs:[{name:"str",type:"string"}]}],s=[{type:"event",name:"Deposited",inputs:[{name:"addr",type:"address",indexed:!0},{name:"sponsor",type:"address",indexed:!0},{name:"dropKey",type:"bytes32",indexed:!0},{name:"amount",type:"uint256",indexed:!1},{name:"id",type:"string",indexed:!1},{name:"secretHash",type:"bytes32",indexed:!1},{name:"token",type:"address",indexed:!1}],anonymous:!1},{type:"function",name:"activeDropOf",stateMutability:"view",inputs:[{name:"sponsor",type:"address"},{name:"claimAddr",type:"address"}],outputs:[{type:"bytes32"}]},{type:"function",name:"drops",stateMutability:"view",inputs:[{name:"dropKey",type:"bytes32"}],outputs:B},{type:"function",name:"token",stateMutability:"view",inputs:[],outputs:[{type:"address"}]},{type:"function",name:"claimDigest",stateMutability:"view",inputs:[{name:"recipient",type:"address"},{name:"id",type:"string"},{name:"dropKey",type:"bytes32"}],outputs:[{type:"bytes32"}]},{type:"function",name:"anchorClaimDigest",stateMutability:"view",inputs:[{name:"recipient",type:"address"},{name:"id",type:"string"},{name:"dropKey",type:"bytes32"}],outputs:[{type:"bytes32"}]},{type:"function",name:"claimedRecipientOf",stateMutability:"view",inputs:[{name:"id",type:"string"}],outputs:[{type:"address"}]},{type:"function",name:"pendingDropsByXid",stateMutability:"view",inputs:[{name:"id",type:"string"}],outputs:H},{type:"function",name:"pendingDropsByRecipient",stateMutability:"view",inputs:[{name:"recipient",type:"address"}],outputs:H},{type:"function",name:"pendingDropsOf",stateMutability:"view",inputs:[{name:"sponsor",type:"address"}],outputs:H},{type:"function",name:"depositMapped",stateMutability:"nonpayable",inputs:[{name:"amount",type:"uint256"},{name:"id",type:"string"},{name:"permitDeadline",type:"uint256"},{name:"v",type:"uint8"},{name:"r",type:"bytes32"},{name:"s",type:"bytes32"}],outputs:[]},{type:"function",name:"withdrawUnmapped",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"id",type:"string"},{name:"dropKey",type:"bytes32"},{name:"signature",type:"bytes"},{name:"secret",type:"bytes"}],outputs:[]},{type:"function",name:"withdrawUnmappedBatchByKeys",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"id",type:"string"},{name:"anchorDropKey",type:"bytes32"},{name:"signature",type:"bytes"},{name:"secret",type:"bytes"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"executor",type:"address"},{name:"dropKeys",type:"bytes32[]"},{name:"validatorSignature",type:"bytes"}],outputs:[]},{type:"function",name:"withdrawMapped",stateMutability:"nonpayable",inputs:[{name:"dropKey",type:"bytes32"}],outputs:[]},{type:"function",name:"batchWithdrawMapped",stateMutability:"nonpayable",inputs:[{name:"count",type:"uint256"}],outputs:[]},{type:"function",name:"batchWithdrawMapped",stateMutability:"nonpayable",inputs:[{name:"dropKeys",type:"bytes32[]"}],outputs:[]},{type:"function",name:"refund",stateMutability:"nonpayable",inputs:[{name:"dropKey",type:"bytes32"}],outputs:[]},{type:"function",name:"changeNonceById",stateMutability:"view",inputs:[{name:"idKey",type:"bytes32"}],outputs:[{type:"uint256"}]},{type:"function",name:"pendingRecipientChange",stateMutability:"view",inputs:[{name:"idKey",type:"bytes32"}],outputs:[{name:"newRecipient",type:"address"}]},{type:"function",name:"requestRecipientChange",stateMutability:"nonpayable",inputs:[{name:"id",type:"string"},{name:"newRecipient",type:"address"}],outputs:[]},{type:"function",name:"completeRecipientChange",stateMutability:"nonpayable",inputs:[{name:"id",type:"string"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"validatorSignature",type:"bytes"}],outputs:[]},{type:"function",name:"cancelRecipientChange",stateMutability:"nonpayable",inputs:[{name:"id",type:"string"}],outputs:[]},{type:"function",name:"resetRecipient",stateMutability:"nonpayable",inputs:[{name:"id",type:"string"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"validatorSignature",type:"bytes"}],outputs:[]},...I];var C=[{type:"function",name:"deposit",stateMutability:"nonpayable",inputs:[{name:"claimAddr",type:"address"},{name:"amount",type:"uint256"},{name:"id",type:"string"},{name:"secretHash",type:"bytes32"},{name:"deadline",type:"uint256"},{name:"v",type:"uint8"},{name:"r",type:"bytes32"},{name:"s",type:"bytes32"}],outputs:[]},{type:"function",name:"token",stateMutability:"view",inputs:[],outputs:[{type:"address"}]},...I],g=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"nonces",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"eip712Domain",stateMutability:"view",inputs:[],outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}]}],M={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]};var f=[{type:"function",name:"validator",stateMutability:"view",inputs:[],outputs:[{type:"address"}]},{type:"function",name:"validatorClaimDigest",stateMutability:"view",inputs:[{name:"executor",type:"address"},{name:"recipient",type:"address"},{name:"id",type:"string"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}],outputs:[{type:"bytes32"}]},{type:"function",name:"validatorNonceById",stateMutability:"view",inputs:[{name:"idHash",type:"bytes32"}],outputs:[{type:"uint256"}]},{type:"function",name:"claimedRecipientOf",stateMutability:"view",inputs:[{name:"id",type:"string"}],outputs:[{type:"address"}]},{type:"error",name:"ValidatorSigExpired",inputs:[]},{type:"error",name:"InvalidValidatorNonce",inputs:[]}];var fe="0x0000000000000000000000000000000000000000",we=`0x${"00".repeat(32)}`,Te={gas:BigInt(1e6),batchBaseGas:BigInt(1e6),batchGasPerDrop:BigInt(75e4),maxBatchGas:BigInt(3e7),maxFeePerGas:BigInt(4e9),maxPriorityFeePerGas:BigInt(1e9)},G=BigInt(1800),T=class{constructor(e){if(this.address=e.address,this.publicClient=e.publicClient,this.walletClient=e.walletClient,this.chain=e.chain,this.transport=e.transport??he(),this.transactionFees={...Te,...e.withdrawFees,...e.transactionFees},this.transactionFees.gas<=BigInt(0)||this.transactionFees.batchBaseGas<=BigInt(0)||this.transactionFees.batchGasPerDrop<=BigInt(0)||this.transactionFees.maxBatchGas<=BigInt(0)||this.transactionFees.maxFeePerGas<=BigInt(0)||this.transactionFees.maxPriorityFeePerGas<=BigInt(0)||this.transactionFees.maxPriorityFeePerGas>this.transactionFees.maxFeePerGas)throw new d("INVALID_PARAM","invalid EIP-1559 gas configuration");this.depositWithPermit=t=>this.permitDeposit(t)}async getDropByKey(e){try{let[t,n,i,a,o,y]=await this.publicClient.readContract({address:this.address,abi:s,functionName:"drops",args:[e]});return t.toLowerCase()===fe?null:{dropKey:e,sponsor:t,amount:n,claimAddress:i,recipient:a,secretHash:o,id:y}}catch(t){throw p("drops",t)}}async getDropKeyByClaimAddress(e,t){try{let n=await this.publicClient.readContract({address:this.address,abi:s,functionName:"activeDropOf",args:[t,e]});return n===we?null:n}catch(n){throw p("activeDropOf",n)}}async getPendingDropsById(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:s,functionName:"pendingDropsByXid",args:[c(e.id)]});return n.map((i,a)=>N(t[a],i))}catch(t){throw p("pendingDropsByXid",t)}}async getPendingDropsByRecipient(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:s,functionName:"pendingDropsByRecipient",args:[e.recipient]});return n.map((i,a)=>N(t[a],i))}catch(t){throw p("pendingDropsByRecipient",t)}}async getPendingDropsBySponsor(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:s,functionName:"pendingDropsOf",args:[e.sponsor]});return n.map((i,a)=>N(t[a],i))}catch(t){throw p("pendingDropsOf",t)}}async getDrop(e,t){let n=await this.getDropKeyByClaimAddress(e,t);if(!n)return null;let[i,a]=await Promise.all([this.getDropByKey(n),this.escrowToken()]);return i&&a?{...i,token:a}:null}async escrowToken(){try{return await this.publicClient.readContract({address:this.address,abi:C,functionName:"token"})}catch{throw new d("CHAIN_ERROR","token() failed")}}async getClaimDigest(e){try{return await this.publicClient.readContract({address:this.address,abi:s,functionName:"claimDigest",args:[e.recipient,c(e.id),e.dropKey]})}catch(t){throw p("claimDigest",t)}}async permitDeposit(e){let t=c(e.id);try{let n=this.requireAccount(),i=e.token,[a,o,y]=await Promise.all([this.publicClient.readContract({address:this.address,abi:C,functionName:"token"}),this.publicClient.readContract({address:i,abi:g,functionName:"nonces",args:[n.address]}),this.permitDomain(i)]);if(a.toLowerCase()!==i.toLowerCase())throw new d("INVALID_TOKEN","token does not match the escrow token",{expected:a,received:e.token});let u=BigInt(Math.floor(Date.now()/1e3))+G,x=await this.walletClient.signTypedData({account:n,domain:{...y,chainId:this.chain.id,verifyingContract:i},types:M,primaryType:"Permit",message:{owner:n.address,spender:this.address,value:e.amount,nonce:o,deadline:u}}),{r:A,s:v,v:D,yParity:P}=_(x),m=await this.walletClient.writeContract({address:this.address,abi:C,functionName:"deposit",args:[e.claimAddress,e.amount,t,e.secretHash,u,Number(D??BigInt(P+27)),A,v],account:n,chain:this.chain,...this.transactionOverrides()});await e.onSubmitted?.(m);let l=await this.confirm("depositWithPermit",m);return{txHash:m,dropKey:this.depositedDropKey(l.logs,n.address,e.amount,t,m)}}catch(n){throw p("depositWithPermit",n)}}async depositMapped(e){let t=c(e.id);try{let n=this.requireAccount(),i=e.token,[a,o,y]=await Promise.all([this.publicClient.readContract({address:this.address,abi:s,functionName:"token"}),this.publicClient.readContract({address:i,abi:g,functionName:"nonces",args:[n.address]}),this.permitDomain(i)]);if(a.toLowerCase()!==i.toLowerCase())throw new d("INVALID_TOKEN","token does not match the escrow token",{expected:a,received:e.token});let u=BigInt(Math.floor(Date.now()/1e3))+G,x=await this.walletClient.signTypedData({account:n,domain:{...y,chainId:this.chain.id,verifyingContract:i},types:M,primaryType:"Permit",message:{owner:n.address,spender:this.address,value:e.amount,nonce:o,deadline:u}}),{r:A,s:v,v:D,yParity:P}=_(x),m=[e.amount,t,u,Number(D??BigInt(P+27)),A,v];await this.publicClient.simulateContract({address:this.address,abi:s,functionName:"depositMapped",args:m,account:n});let l=await this.walletClient.writeContract({address:this.address,abi:s,functionName:"depositMapped",args:m,account:n,chain:this.chain,...this.transactionOverrides()});await e.onSubmitted?.(l);let q=await this.confirm("depositMapped",l);return{txHash:l,dropKey:this.depositedDropKey(q.logs,n.address,e.amount,t,l)}}catch(n){throw p("depositMapped",n)}}async permitDomain(e){try{let t=await this.publicClient.readContract({address:e,abi:g,functionName:"eip712Domain"});return{name:t[1],version:t[2]}}catch{return{name:await this.publicClient.readContract({address:e,abi:g,functionName:"name"}),version:"1"}}}async withdrawUnmapped(e){let t=c(e.id);try{let n=ge(e.claimKey),i=await this.publicClient.readContract({address:this.address,abi:s,functionName:"claimDigest",args:[e.recipient,t,e.dropKey]}),a=e.signature??k(await L({hash:i,privateKey:e.claimKey})),y=await le({account:n,chain:this.chain,transport:this.transport}).writeContract({address:this.address,abi:s,functionName:"withdrawUnmapped",args:[e.recipient,t,e.dropKey,a,F(w(e.secret))],...this.transactionOverrides()});return await e.onSubmitted?.(y),await this.confirm("withdrawUnmapped",y),y}catch(n){throw W("withdrawUnmapped",n)}}async withdrawMapped(e){let t=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:s,functionName:"withdrawMapped",args:[e.dropKey],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:s,functionName:"withdrawMapped",args:[e.dropKey],account:t,chain:this.chain,...this.transactionOverrides()});return await e.onSubmitted?.(n),await this.confirm("withdrawMapped",n),n}catch(n){throw p("withdrawMapped",n)}}async batchWithdrawMapped(e){if(!Number.isSafeInteger(e.count)||e.count<=0)throw new d("INVALID_PARAM","count must be a positive safe integer");let t=this.batchTransactionOverrides(e.count),n=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:s,functionName:"batchWithdrawMapped",args:[BigInt(e.count)],account:n});let i=await this.walletClient.writeContract({address:this.address,abi:s,functionName:"batchWithdrawMapped",args:[BigInt(e.count)],account:n,chain:this.chain,...t});return await this.confirm("batchWithdrawMapped",i),i}catch(i){throw p("batchWithdrawMapped",i)}}async batchWithdrawMappedByKeys(e){if(!e.dropKeys.length)throw new d("INVALID_PARAM","dropKeys must not be empty");let t=this.batchTransactionOverrides(e.dropKeys.length),n=this.requireAccount(),i=[e.dropKeys];try{await this.publicClient.simulateContract({address:this.address,abi:s,functionName:"batchWithdrawMapped",args:i,account:n});let a=await this.walletClient.writeContract({address:this.address,abi:s,functionName:"batchWithdrawMapped",args:i,account:n,chain:this.chain,...t});return await this.confirm("batchWithdrawMapped",a),a}catch(a){throw p("batchWithdrawMapped",a)}}async withdrawUnmappedBatchByKeys(e){let t=c(e.id),n=e.dropKeys.filter(o=>o.toLowerCase()!==e.anchorDropKey.toLowerCase()),i=this.batchTransactionOverrides(n.length+1),a=this.requireAccount();try{let o=await this.publicClient.readContract({address:this.address,abi:s,functionName:"anchorClaimDigest",args:[e.recipient,t,e.anchorDropKey]}),y=k(await L({hash:o,privateKey:e.claimKey})),u=await this.walletClient.writeContract({address:this.address,abi:s,functionName:"withdrawUnmappedBatchByKeys",args:[e.recipient,t,e.anchorDropKey,y,F(w(e.secret)),e.nonce,e.deadline,e.executor,n,e.validatorSignature],account:a,chain:this.chain,...i});return await this.confirm("withdrawUnmappedBatchByKeys",u),u}catch(o){throw W("withdrawUnmappedBatchByKeys",o)}}async getValidatorNonce(e){try{return await this.publicClient.readContract({address:this.address,abi:f,functionName:"validatorNonceById",args:[O(w(c(e.id)))]})}catch(t){throw p("validatorNonceById",t)}}async getValidatorClaimDigest(e){try{return await this.publicClient.readContract({address:this.address,abi:f,functionName:"validatorClaimDigest",args:[e.executor,e.recipient,c(e.id),e.nonce,e.deadline]})}catch(t){throw p("validatorClaimDigest",t)}}async getValidator(){try{return await this.publicClient.readContract({address:this.address,abi:f,functionName:"validator"})}catch(e){throw p("validator",e)}}async getClaimedRecipient(e){try{return await this.publicClient.readContract({address:this.address,abi:s,functionName:"claimedRecipientOf",args:[c(e.id)]})}catch(t){throw p("claimedRecipientOf",t)}}async refundByKey(e){let t=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:s,functionName:"refund",args:[e.dropKey],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:s,functionName:"refund",args:[e.dropKey],account:t,chain:this.chain,...this.transactionOverrides()});return await this.confirm("refund",n),n}catch(n){throw p("refund",n)}}async getChangeNonce(e){try{return await this.publicClient.readContract({address:this.address,abi:s,functionName:"changeNonceById",args:[O(w(c(e.id)))]})}catch(t){throw p("changeNonceById",t)}}async getPendingRecipientChange(e){try{return await this.publicClient.readContract({address:this.address,abi:s,functionName:"pendingRecipientChange",args:[O(w(c(e.id)))]})}catch(t){throw p("pendingRecipientChange",t)}}async requestRecipientChange(e){return this.currentContractWrite("requestRecipientChange",[c(e.id),e.newRecipient])}async completeRecipientChange(e){return this.currentContractWrite("completeRecipientChange",[c(e.id),e.nonce,e.deadline,e.signature])}async cancelRecipientChange(e){return this.currentContractWrite("cancelRecipientChange",[c(e.id)])}async resetRecipient(e){let t=c(e.id),n=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:s,functionName:"resetRecipient",args:[t,e.nonce,e.deadline,e.signature],account:n});let i=await this.walletClient.writeContract({address:this.address,abi:s,functionName:"resetRecipient",args:[t,e.nonce,e.deadline,e.signature],account:n,chain:this.chain,...this.transactionOverrides()});return await this.confirm("resetRecipient",i),i}catch(i){throw p("resetRecipient",i)}}async currentContractWrite(e,t){let n=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:s,functionName:e,args:t,account:n});let i=await this.walletClient.writeContract({address:this.address,abi:s,functionName:e,args:t,account:n,chain:this.chain,...this.transactionOverrides()});return await this.confirm(e,i),i}catch(i){throw p(e,i)}}transactionOverrides(e=this.transactionFees.gas){return{type:"eip1559",gas:e,maxFeePerGas:this.transactionFees.maxFeePerGas,maxPriorityFeePerGas:this.transactionFees.maxPriorityFeePerGas}}batchTransactionOverrides(e){if(!Number.isSafeInteger(e)||e<=0)throw new d("INVALID_PARAM","batch count must be a positive safe integer");let t=this.transactionFees.batchBaseGas+this.transactionFees.batchGasPerDrop*BigInt(e);if(t>this.transactionFees.maxBatchGas)throw new d("INVALID_PARAM","batch gas exceeds maxBatchGas",{count:e,gas:t.toString(),maxBatchGas:this.transactionFees.maxBatchGas.toString()});return this.transactionOverrides(t)}async sponsorWrite(e,t){try{let n=await t();return await this.confirm(e,n),n}catch(n){throw p(e,n)}}depositedDropKey(e,t,n,i,a){let o=be({abi:s,eventName:"Deposited",logs:[...e]}).find(({address:y,args:u})=>y.toLowerCase()===this.address.toLowerCase()&&u.sponsor.toLowerCase()===t.toLowerCase()&&u.amount===n&&u.id===i);if(!o)throw new d("CHAIN_ERROR","deposit receipt omitted the Deposited event",{txHash:a});return o.args.dropKey}async confirm(e,t){let n=await this.publicClient.waitForTransactionReceipt({hash:t});if(n.status!=="success"){let i=await this.recoverRevertName(t,n.blockNumber),a=i?`SafeDrop.${e} reverted: ${i}`:`transaction reverted: ${t}`;throw new d("CHAIN_ERROR",a,{revertName:i,txHash:t})}return n}async recoverRevertName(e,t){try{let n=await this.publicClient.getTransaction({hash:e});await this.publicClient.call({account:n.from,to:n.to??void 0,data:n.input,value:n.value,blockNumber:t});return}catch(n){return E(n)}}requireAccount(){let e=this.walletClient.account;if(!e)throw new d("CHAIN_ERROR","walletClient has no account (connect a wallet first)");return e}};function N(r,e){return{dropKey:r,sponsor:e.sponsor,amount:e.amount,claimAddress:e.claimAddr,recipient:e.recipient,secretHash:e.secretHash,id:e.id}}function p(r,e){if(e instanceof d)return e;let t=E(e),n=e instanceof Error?e.message:String(e),i=t?`SafeDrop.${r} reverted: ${t}`:`SafeDrop.${r} failed`;return new d("CHAIN_ERROR",i,{cause:n,revertName:t})}function W(r,e){if(e instanceof d)return e;let t=E(e),n=e instanceof U?e.walk(o=>{let y=o;return typeof y.code=="number"||y.data!==void 0}):void 0,i={revertName:t};typeof n?.code=="number"&&(i.rpcCode=n.code),typeof n?.details=="string"&&(i.rpcMessage=n.details),typeof n?.data=="string"&&(i.rpcData=n.data);let a=t?`SafeDrop.${r} reverted: ${t}`:`SafeDrop.${r} failed`;return new d("CHAIN_ERROR",a,i)}function E(r){if(!(r instanceof U))return;let e=r.walk(t=>t instanceof V);if(e instanceof V)return e.data?.errorName??e.reason??void 0}var Z=[{type:"constructor",inputs:[{name:"token_",type:"address",internalType:"contract IERC20"},{name:"validator_",type:"address",internalType:"address"},{name:"sbt_",type:"address",internalType:"contract ISoulboundToken"},{name:"feeRecipient_",type:"address",internalType:"address"},{name:"minDeposit_",type:"uint256",internalType:"uint256"}],stateMutability:"nonpayable"},{type:"function",name:"FEE_BPS",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"MAX_PENDING_PER_SPONSOR_ID",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"activeDropOf",inputs:[{name:"sponsor",type:"address",internalType:"address"},{name:"claimAddr",type:"address",internalType:"address"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"anchorClaimDigest",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"dropKey",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"batchWithdrawMapped",inputs:[{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"batchWithdrawMapped",inputs:[{name:"count",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"cancelRecipientChange",inputs:[{name:"id",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"changeNonceById",inputs:[{name:"idKey",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"changeRecipientDigest",inputs:[{name:"id",type:"string",internalType:"string"},{name:"newRecipient",type:"address",internalType:"address"},{name:"nonce",type:"uint256",internalType:"uint256"},{name:"deadline",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"claimDigest",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"dropKey",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"claimedRecipientOf",inputs:[{name:"id",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"completeRecipientChange",inputs:[{name:"id",type:"string",internalType:"string"},{name:"nonce",type:"uint256",internalType:"uint256"},{name:"deadline",type:"uint256",internalType:"uint256"},{name:"validatorSignature",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"deposit",inputs:[{name:"claimAddr",type:"address",internalType:"address"},{name:"amount",type:"uint256",internalType:"uint256"},{name:"id",type:"string",internalType:"string"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"permitDeadline",type:"uint256",internalType:"uint256"},{name:"v",type:"uint8",internalType:"uint8"},{name:"r",type:"bytes32",internalType:"bytes32"},{name:"s",type:"bytes32",internalType:"bytes32"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"depositMapped",inputs:[{name:"amount",type:"uint256",internalType:"uint256"},{name:"id",type:"string",internalType:"string"},{name:"permitDeadline",type:"uint256",internalType:"uint256"},{name:"v",type:"uint8",internalType:"uint8"},{name:"r",type:"bytes32",internalType:"bytes32"},{name:"s",type:"bytes32",internalType:"bytes32"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"drops",inputs:[{name:"dropKey",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"sponsor",type:"address",internalType:"address"},{name:"amount",type:"uint96",internalType:"uint96"},{name:"claimAddr",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"eip712Domain",inputs:[],outputs:[{name:"fields",type:"bytes1",internalType:"bytes1"},{name:"name",type:"string",internalType:"string"},{name:"version",type:"string",internalType:"string"},{name:"chainId",type:"uint256",internalType:"uint256"},{name:"verifyingContract",type:"address",internalType:"address"},{name:"salt",type:"bytes32",internalType:"bytes32"},{name:"extensions",type:"uint256[]",internalType:"uint256[]"}],stateMutability:"view"},{type:"function",name:"feeRecipient",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"minDeposit",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"pendingCountOf",inputs:[{name:"sponsor",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"pendingCountOf",inputs:[{name:"sponsor",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"pendingDropsByRecipient",inputs:[{name:"recipient",type:"address",internalType:"address"}],outputs:[{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"records",type:"tuple[]",internalType:"struct ONEpop.Drop[]",components:[{name:"sponsor",type:"address",internalType:"address"},{name:"amount",type:"uint96",internalType:"uint96"},{name:"claimAddr",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]}],stateMutability:"view"},{type:"function",name:"pendingDropsByRecipient",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"offset",type:"uint256",internalType:"uint256"},{name:"limit",type:"uint256",internalType:"uint256"}],outputs:[{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"records",type:"tuple[]",internalType:"struct ONEpop.Drop[]",components:[{name:"sponsor",type:"address",internalType:"address"},{name:"amount",type:"uint96",internalType:"uint96"},{name:"claimAddr",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]},{name:"total",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"pendingDropsByXid",inputs:[{name:"id",type:"string",internalType:"string"}],outputs:[{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"records",type:"tuple[]",internalType:"struct ONEpop.Drop[]",components:[{name:"sponsor",type:"address",internalType:"address"},{name:"amount",type:"uint96",internalType:"uint96"},{name:"claimAddr",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]}],stateMutability:"view"},{type:"function",name:"pendingDropsByXid",inputs:[{name:"id",type:"string",internalType:"string"},{name:"offset",type:"uint256",internalType:"uint256"},{name:"limit",type:"uint256",internalType:"uint256"}],outputs:[{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"records",type:"tuple[]",internalType:"struct ONEpop.Drop[]",components:[{name:"sponsor",type:"address",internalType:"address"},{name:"amount",type:"uint96",internalType:"uint96"},{name:"claimAddr",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]},{name:"total",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"pendingDropsOf",inputs:[{name:"sponsor",type:"address",internalType:"address"}],outputs:[{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"records",type:"tuple[]",internalType:"struct ONEpop.Drop[]",components:[{name:"sponsor",type:"address",internalType:"address"},{name:"amount",type:"uint96",internalType:"uint96"},{name:"claimAddr",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]}],stateMutability:"view"},{type:"function",name:"pendingDropsOf",inputs:[{name:"sponsor",type:"address",internalType:"address"},{name:"offset",type:"uint256",internalType:"uint256"},{name:"limit",type:"uint256",internalType:"uint256"}],outputs:[{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"records",type:"tuple[]",internalType:"struct ONEpop.Drop[]",components:[{name:"sponsor",type:"address",internalType:"address"},{name:"amount",type:"uint96",internalType:"uint96"},{name:"claimAddr",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]},{name:"total",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"pendingRecipientChange",inputs:[{name:"idKey",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"newRecipient",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"refund",inputs:[{name:"dropKey",type:"bytes32",internalType:"bytes32"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"requestRecipientChange",inputs:[{name:"id",type:"string",internalType:"string"},{name:"newRecipient",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"resetRecipient",inputs:[{name:"id",type:"string",internalType:"string"},{name:"nonce",type:"uint256",internalType:"uint256"},{name:"deadline",type:"uint256",internalType:"uint256"},{name:"validatorSignature",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"resetRecipientDigest",inputs:[{name:"id",type:"string",internalType:"string"},{name:"nonce",type:"uint256",internalType:"uint256"},{name:"deadline",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"sbt",inputs:[],outputs:[{name:"",type:"address",internalType:"contract ISoulboundToken"}],stateMutability:"view"},{type:"function",name:"settledCountOf",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"token",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IERC20"}],stateMutability:"view"},{type:"function",name:"validator",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"validatorClaimDigest",inputs:[{name:"executor",type:"address",internalType:"address"},{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"nonce",type:"uint256",internalType:"uint256"},{name:"deadline",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"validatorNonceById",inputs:[{name:"idKey",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"withdrawMapped",inputs:[{name:"dropKey",type:"bytes32",internalType:"bytes32"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"withdrawUnmapped",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"dropKey",type:"bytes32",internalType:"bytes32"},{name:"signature",type:"bytes",internalType:"bytes"},{name:"secret",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"withdrawUnmappedBatch",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"anchorDropKey",type:"bytes32",internalType:"bytes32"},{name:"signature",type:"bytes",internalType:"bytes"},{name:"secret",type:"bytes",internalType:"bytes"},{name:"nonce",type:"uint256",internalType:"uint256"},{name:"deadline",type:"uint256",internalType:"uint256"},{name:"executor",type:"address",internalType:"address"},{name:"payCount",type:"uint256",internalType:"uint256"},{name:"moveCount",type:"uint256",internalType:"uint256"},{name:"validatorSignature",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"withdrawUnmappedBatchByKeys",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"anchorDropKey",type:"bytes32",internalType:"bytes32"},{name:"signature",type:"bytes",internalType:"bytes"},{name:"secret",type:"bytes",internalType:"bytes"},{name:"nonce",type:"uint256",internalType:"uint256"},{name:"deadline",type:"uint256",internalType:"uint256"},{name:"executor",type:"address",internalType:"address"},{name:"dropKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"validatorSignature",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"Deposited",inputs:[{name:"addr",type:"address",indexed:!0,internalType:"address"},{name:"sponsor",type:"address",indexed:!0,internalType:"address"},{name:"dropKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"id",type:"string",indexed:!1,internalType:"string"},{name:"secretHash",type:"bytes32",indexed:!1,internalType:"bytes32"},{name:"token",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"EIP712DomainChanged",inputs:[],anonymous:!1},{type:"event",name:"FeeCharged",inputs:[{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"gross",type:"uint256",indexed:!1,internalType:"uint256"},{name:"fee",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"Moved",inputs:[{name:"claimAddr",type:"address",indexed:!0,internalType:"address"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"dropKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"sponsor",type:"address",indexed:!1,internalType:"address"},{name:"id",type:"string",indexed:!1,internalType:"string"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"RecipientChangeCancelled",inputs:[{name:"idKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RecipientChangeRequested",inputs:[{name:"idKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RecipientChanged",inputs:[{name:"idKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RecipientMapped",inputs:[{name:"idKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RecipientReset",inputs:[{name:"idKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"Refunded",inputs:[{name:"claimAddr",type:"address",indexed:!0,internalType:"address"},{name:"sponsor",type:"address",indexed:!0,internalType:"address"},{name:"dropKey",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"id",type:"string",indexed:!1,internalType:"string"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"Withdrawn",inputs:[{name:"claimAddr",type:"address",indexed:!0,internalType:"address"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"sponsor",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"string",indexed:!1,internalType:"string"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token",type:"address",indexed:!1,internalType:"address"},{name:"sbtTokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"dropKey",type:"bytes32",indexed:!1,internalType:"bytes32"}],anonymous:!1},{type:"error",name:"AlreadyMapped",inputs:[]},{type:"error",name:"AmountOverflow",inputs:[]},{type:"error",name:"BelowMinDeposit",inputs:[]},{type:"error",name:"ChangeAlreadyRequested",inputs:[]},{type:"error",name:"ChangeInProgress",inputs:[]},{type:"error",name:"CountExceedsPending",inputs:[]},{type:"error",name:"DropAlreadyExists",inputs:[]},{type:"error",name:"DropNotFound",inputs:[]},{type:"error",name:"ECDSAInvalidSignature",inputs:[]},{type:"error",name:"ECDSAInvalidSignatureLength",inputs:[{name:"length",type:"uint256",internalType:"uint256"}]},{type:"error",name:"ECDSAInvalidSignatureS",inputs:[{name:"s",type:"bytes32",internalType:"bytes32"}]},{type:"error",name:"EmptyId",inputs:[]},{type:"error",name:"IdMismatch",inputs:[]},{type:"error",name:"IdNotMapped",inputs:[]},{type:"error",name:"InvalidClaimSignature",inputs:[]},{type:"error",name:"InvalidExecutor",inputs:[]},{type:"error",name:"InvalidShortString",inputs:[]},{type:"error",name:"InvalidValidatorNonce",inputs:[]},{type:"error",name:"InvalidValidatorSignature",inputs:[]},{type:"error",name:"NoPendingChange",inputs:[]},{type:"error",name:"NotRecipient",inputs:[]},{type:"error",name:"NotSponsor",inputs:[]},{type:"error",name:"PendingLimitExceeded",inputs:[]},{type:"error",name:"RecipientNotEmpty",inputs:[]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]},{type:"error",name:"SameRecipient",inputs:[]},{type:"error",name:"SecretMismatch",inputs:[]},{type:"error",name:"StringTooLong",inputs:[{name:"str",type:"string",internalType:"string"}]},{type:"error",name:"TokenNotEighteenDecimals",inputs:[]},{type:"error",name:"ValidatorSigExpired",inputs:[]},{type:"error",name:"ZeroAmount",inputs:[]},{type:"error",name:"ZeroClaimAddress",inputs:[]},{type:"error",name:"ZeroCount",inputs:[]},{type:"error",name:"ZeroFeeRecipient",inputs:[]},{type:"error",name:"ZeroRecipient",inputs:[]},{type:"error",name:"ZeroSbt",inputs:[]},{type:"error",name:"ZeroSecretHash",inputs:[]},{type:"error",name:"ZeroToken",inputs:[]},{type:"error",name:"ZeroValidator",inputs:[]}];var xe=Z;function Ae(r){let e=r.apiPort??new R(r.api),t=new T({address:r.contractAddress??S().onePop,publicClient:r.publicClient,walletClient:r.walletClient,chain:r.chain,transport:r.transport,withdrawFees:r.withdrawFees,transactionFees:r.transactionFees});return K({claimBaseUrl:r.claimBaseUrl},{api:e,chain:t,signer:new b,crypto:new h})}export{te as CrossAuthClient,Y as DEFAULT_POP_API_PATHS,R as HttpSafeDropApiAdapter,ae as HttpXAuthAdapter,s as ONEPOP_ABI,X as ONE_POP_BPS_DENOMINATOR,j as ONE_POP_DEPLOYMENTS,$ as ONE_POP_FEE_BPS,xe as SAFEDROP_ABI,f as SAFEDROP_VALIDATOR_ABI,b as ViemClaimSignerAdapter,h as ViemCryptoAdapter,T as ViemSafeDropChainAdapter,se as XAuthClient,Ae as createSafeDropClient,ne as generatePkce,ie as generateState,ee as getCrossAuthBaseUrl,Q as getOnePopApiBaseUrl,S as getOnePopContracts,J as getOnePopDeployment,z as getPopEnvironment};
@@ -1,3 +1,3 @@
1
- export { C as CrossAuthClient, a as CrossAuthClientOptions, D as DEFAULT_POP_API_PATHS, b as HttpSafeDropApiAdapter, H as HttpSafeDropApiAdapterOptions, c as HttpXAuthAdapter, d as HttpXAuthAdapterOptions, e as ONE_POP_DEPLOYMENTS, P as Pkce, g as PopApiPaths, h as PopContracts, i as PopDeployment, j as PopEnvironment, S as SessionStore, X as XAuthClient, k as XAuthClientOptions, l as generatePkce, m as generateState, n as getCrossAuthBaseUrl, o as getOnePopApiBaseUrl, s as resolvePopEnvironment } from '../index-DVeDD7Dp.js';
2
- import '../SafeDropApiPort-B7NfQOsb.js';
1
+ export { C as CrossAuthClient, a as CrossAuthClientOptions, D as DEFAULT_POP_API_PATHS, b as HttpSafeDropApiAdapter, H as HttpSafeDropApiAdapterOptions, c as HttpXAuthAdapter, d as HttpXAuthAdapterOptions, e as ONE_POP_DEPLOYMENTS, P as Pkce, g as PopApiPaths, h as PopContracts, i as PopDeployment, j as PopEnvironment, S as SessionStore, X as XAuthClient, k as XAuthClientOptions, l as generatePkce, m as generateState, n as getCrossAuthBaseUrl, o as getOnePopApiBaseUrl, s as resolvePopEnvironment } from '../index-CF1w6xbD.js';
2
+ import '../SafeDropApiPort-CsPo0Pmn.js';
3
3
  import '../XAuthPort-BNJePosj.js';
package/dist/api/index.js CHANGED
@@ -1 +1 @@
1
- import{c as t,d as e,f as p,i as o,j as r,k as n,l as A,m as s,n as P,o as i,p as a}from"../chunk-ENB6CCH7.js";import"../chunk-5DT3H2VX.js";export{A as CrossAuthClient,e as DEFAULT_POP_API_PATHS,n as HttpSafeDropApiAdapter,i as HttpXAuthAdapter,t as ONE_POP_DEPLOYMENTS,a as XAuthClient,s as generatePkce,P as generateState,r as getCrossAuthBaseUrl,o as getOnePopApiBaseUrl,p as resolvePopEnvironment};
1
+ import{c as t,d as e,f as p,i as o,j as r,k as n,l as A,m as s,n as P,o as i,p as a}from"../chunk-C54CAUVA.js";import"../chunk-PV4F2RR3.js";export{A as CrossAuthClient,e as DEFAULT_POP_API_PATHS,n as HttpSafeDropApiAdapter,i as HttpXAuthAdapter,t as ONE_POP_DEPLOYMENTS,a as XAuthClient,s as generatePkce,P as generateState,r as getCrossAuthBaseUrl,o as getOnePopApiBaseUrl,p as resolvePopEnvironment};
@@ -0,0 +1 @@
1
+ import{a as o,b as g}from"./chunk-PV4F2RR3.js";var f=BigInt(500),ee=BigInt(1e4),R={dev:{apiBaseUrl:"https://dev-one-pop-api.onechain.nexus/api",contracts:{onePop:"0xdC44AEF049Fb86Bd78CA887C330903cb2c031b7D",permitErc20:"0xFaDAB54449262178aE0562F5D8416bBeF4659714",nft:"0xc09f0E4B342e32ef32ca73306B5A29B3C8d01aE8",nftMinter:"0xdC44AEF049Fb86Bd78CA887C330903cb2c031b7D",validator:"0xF30d8e0544f0b92A6987522f4F696D3915B579b4",feeRecipient:"0xF30d8e0544f0b92A6987522f4F696D3915B579b4"}},stage:{apiBaseUrl:"https://stg-one-pop-api.onechain.nexus/api",contracts:{onePop:"0xb03B0C0d03E4Cbe91edD48fa3C4E6Bb1EEA65eDe",permitErc20:"0xFaDAB54449262178aE0562F5D8416bBeF4659714",nft:"0x0B35DaD70114663EC07d5b86763B15f3DaCd7C8D",nftMinter:"0x7a54205e47819344eC3b89D5637C779531346642",validator:"0xa953af3742345dFC2BdcA30cBa79D8313b0a3B61",feeRecipient:"0xa953af3742345dFC2BdcA30cBa79D8313b0a3B61"}},production:{apiBaseUrl:"https://one-pop-api.onechain.nexus/api"}},A={createWallet:"/wallets",dropMetadata:"/drops/metadata",retrievePrivateKey:"/wallets/private-key",drops:"/drops",rejectDrops:"/drops/reject",envelopes:"/envelopes",leaderboards:"/leaderboards",leaderboardMe:"/leaderboards/me",histories:"/histories",xConnections:"/x-connections",batchClaimSignature:"/batch-claim-signature",feedbacks:"/feedbacks",revealYou:"/reveal-you",recipientChangeSignature:"/recipient-change-signature",recipientResetSignature:"/recipient-reset-signature",eventsSubscribe:"/events/subscribe"},$="https://dev-cross-auth.crosstoken.io";function m(r){try{return import.meta.env?.[r]}catch{return}}function u(r){if(!(typeof process>"u"||!process.env))switch(r){case"NEXT_PUBLIC_ONE_POP_ENVIRONMENT":return process.env.NEXT_PUBLIC_ONE_POP_ENVIRONMENT;case"ONE_POP_ENVIRONMENT":return process.env.ONE_POP_ENVIRONMENT;case"NEXT_PUBLIC_ONE_POP_API_BASE_URL":return process.env.NEXT_PUBLIC_ONE_POP_API_BASE_URL;case"NEXT_PUBLIC_CROSS_AUTH_URL":return process.env.NEXT_PUBLIC_CROSS_AUTH_URL;default:return}}function w(){let r=m("VITE_ONE_POP_ENVIRONMENT")??u("NEXT_PUBLIC_ONE_POP_ENVIRONMENT")??u("ONE_POP_ENVIRONMENT");return F(r)}function F(r){switch(r?.toLowerCase()){case"dev":case"development":return"dev";case"stg":case"stage":case"staging":return"stage";case void 0:case"production":case"prod":return"production";default:throw new Error(`[pop] Invalid environment: ${r}`)}}function q(){return R[w()]}function te(){return V(w())}function V(r){let e=R[r].contracts;if(!e)throw new Error(`[pop] Contract addresses are not configured for ${r}`);return e}function I(){let e=m("VITE_ONE_POP_API_BASE_URL")??u("NEXT_PUBLIC_ONE_POP_API_BASE_URL")??q().apiBaseUrl;return S(e),e}function O(){let e=(m("VITE_CROSS_AUTH_URL")??u("NEXT_PUBLIC_CROSS_AUTH_URL")??$).replace(/\/+$/,"");return S(e),e}function S(r){let e;try{e=new URL(r)}catch{throw new Error(`[pop] Invalid base URL: ${r}`)}if(e.protocol==="https:")return;let t=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname.endsWith(".local");if(!(e.protocol==="http:"&&t))throw new Error(`[pop] base URL must be https (or http://localhost for dev). Got: ${r}`)}var j={INVALID_PARAM:"INVALID_PARAM",RATE_LIMITED:"RATE_LIMITED",INVALID_OAUTH_TOKEN:"INVALID_OAUTH_TOKEN",UNAUTHORIZED:"UNAUTHORIZED",WALLET_NOT_FOUND:"WALLET_NOT_FOUND",SEND_BLOCKED:"SEND_BLOCKED",ENVELOPE_NOT_FOUND:"ENVELOPE_NOT_FOUND",PENDING_LIMIT_EXCEEDED:"PENDING_LIMIT_EXCEEDED",DROP_NOT_FOUND:"DROP_NOT_FOUND",IDENTIFIER_NOT_MAPPED:"IDENTIFIER_NOT_MAPPED",X_CONNECTION_NOT_FOUND:"X_CONNECTION_NOT_FOUND",X_ALREADY_CONNECTED:"X_ALREADY_CONNECTED"},l=140,v=class{constructor(e={}){this.baseUrl=(e.baseUrl??I()).replace(/\/+$/,"");let t=e.fetchImpl??globalThis.fetch;if(!t)throw new Error("fetch is unavailable; provide options.fetchImpl");this.fetchImpl=t,this.getJwt=e.getJwt,this.paths={...A,...e.paths}}async createClaimWallet(e){let t=await this.request(this.paths.createWallet,{method:"POST",auth:!0,payload:{identifier:e.recipient.handle,oauth_type:e.recipient.provider,sender_address:e.sender}});if(!t?.address)throw new o("API_ERROR","createClaimWallet: missing address in response",{body:t});if(!t.identifier)throw new o("API_ERROR","createClaimWallet: missing identifier in response",{body:t});return{claimAddress:t.address,id:t.identifier,isMapped:t.is_mapped===!0}}async recordDropMetadata(e){if(e.message&&[...e.message].length>l)throw new o("INVALID_PARAM",`message must be <= ${l} runes`);await this.request(this.paths.dropMetadata,{method:"POST",auth:!0,query:{tx_hash:e.txHash},payload:{...e.message?{message:e.message}:{},...e.envelopeId?{envelope_id:e.envelopeId}:{}}})}async retrieveClaimKey(e){let t=await this.request(this.paths.retrievePrivateKey,{method:"POST",payload:{oauth_token:e.oauth.accessToken,oauth_type:e.oauth.provider,sender_address:e.senderAddress,address:e.claimAddress}});if(t?.private_key&&t.address){if(t.address.toLowerCase()!==e.claimAddress.toLowerCase())throw new o("API_ERROR","retrieveClaimKey: returned a different address");return{isMapped:!1,claimKey:t.private_key,claimAddress:t.address}}if(t?.is_mapped===!0)return{isMapped:!0};throw new o("API_ERROR","retrieveClaimKey: missing key/address in response",{body:t})}async listDrops(e){if(!e?.token)throw new o("INVALID_PARAM","listDrops requires a token address");let t=await this.request(this.paths.drops,{method:"GET",auth:!0,query:{token:e.token,drop_key:e.dropKey}});return{items:(t?.items??[]).map(K),count:t?.count??0,totalAmount:d(t?.total_amount,"drops.total_amount"),hasClaimedBefore:t?.has_claimed_before===!0,mappedRecipient:c(t?.mapped_recipient),pendingChangeTo:c(t?.pending_change_to),feeBps:t?.fee_bps??Number(f)}}async rejectDrops(e){if(!Array.isArray(e.dropIds)||e.dropIds.length===0||e.dropIds.length>100||e.dropIds.some(n=>!Number.isSafeInteger(n)||n<=0))throw new o("INVALID_PARAM","dropIds must contain 1-100 positive integers");return(await this.request(this.paths.rejectDrops,{method:"POST",auth:!0,payload:{drop_ids:e.dropIds}}))?.count??0}async listEnvelopes(e={}){return((await this.request(this.paths.envelopes,{method:"GET",query:{locale:e.locale}}))?.items??[]).map(n=>({id:s(n.id),name:s(n.name),imageUrl:s(n.image_url),badge:s(n.badge),sortOrder:Number(n.sort_order??0),layout:n.layout}))}async getLeaderboard(e){if(!e.token)throw new o("INVALID_PARAM","getLeaderboard requires a token address");let t=await this.request(this.paths.leaderboards,{method:"GET",query:{token:e.token,page:e.page,page_size:e.pageSize,identifier:e.identifier}});return{items:(t?.items??[]).map(N),page:t?.page??1,pageSize:t?.page_size??0,total:t?.total??0}}async getMyLeaderboardEntry(e){let t=await this.request(this.paths.leaderboardMe,{method:"GET",auth:!0,query:{token:e.token}});return{...N(t??{}),rank:U(t?.rank)}}async listHistories(e){if(!e?.type)throw new o("INVALID_PARAM","listHistories requires type");let t=await this.request(this.paths.histories,{method:"GET",auth:!0,query:{type:e.type,token:e.token,status:e.status,rejected:e.rejected===void 0?void 0:String(e.rejected),page:e.page,page_size:e.pageSize}});return{items:(t?.items??[]).map(n=>({id:Number(n.id??0),type:s(n.type),status:s(n.status),token:s(n.token),amount:d(n.amount,"history.amount"),claimAddress:s(n.claim_address),depositTxHash:s(n.deposit_tx_hash),depositedAt:s(n.deposited_at),resolvedTxHash:c(n.resolved_tx_hash),resolvedAt:c(n.resolved_at),message:s(n.message),feedback:c(n.feedback),envelopeId:s(n.envelope_id),rejected:n.rejected===!0,sender:C(n.sender),receiver:W(n.receiver)})),page:t?.page??1,pageSize:t?.page_size??0,total:t?.total??0,feeBps:t?.fee_bps??Number(f)}}async getXConnection(){let e=await this.request(this.paths.xConnections,{method:"GET",auth:!0,notFoundAsNull:!0});return e?T(e):null}async connectX(e){let t=await this.request(this.paths.xConnections,{method:"POST",auth:!0,payload:{oauth_token:e.oauth.accessToken}});return T(t??{})}async disconnectX(){await this.request(this.paths.xConnections,{method:"DELETE",auth:!0,notFoundAsNull:!0})}async submitFeedback(e){if(!Number.isSafeInteger(e.dropId)||e.dropId<=0)throw new o("INVALID_PARAM","dropId must be a positive integer");if(!e.message.trim()||[...e.message.trim()].length>l)throw new o("INVALID_PARAM",`message must be 1-${l} runes`);let t=await this.request(this.paths.feedbacks,{method:"PUT",auth:!0,query:{drop_id:e.dropId},payload:{message:e.message}});return s(t?.message)}async setRevealYou(e){return(await this.request(this.paths.revealYou,{method:"PUT",auth:!0,payload:{reveal_you:e.revealYou}}))?.reveal_you===!0}async requestRecipientChangeSignature(e){let t=await this.request(this.paths.recipientChangeSignature,{method:"POST",auth:!0,payload:_(e)});return{...k(t,e),newRecipient:s(t?.new_recipient)}}async requestRecipientResetSignature(e){let t=await this.request(this.paths.recipientResetSignature,{method:"POST",payload:_(e)});return k(t,e)}async requestBatchClaimSignature(e){let t=_(e),n=await this.request(this.paths.batchClaimSignature,{method:"POST",auth:!0,payload:t}),i=s(n?.signature);if(!i)throw new o("API_ERROR","requestBatchClaimSignature: missing signature",{body:n});return{id:s(n?.id)||t.id,recipient:s(n?.recipient),nonce:h(n?.nonce)?d(n?.nonce,"batchClaim.nonce"):e.nonce,deadline:h(n?.deadline)?d(n?.deadline,"batchClaim.deadline"):e.deadline,signature:i}}async request(e,t){let n={};if(t.payload&&(n["Content-Type"]="application/json"),t.auth){let a=await this.getJwt?.();if(!a)throw new o("UNAUTHORIZED",`${e} requires a SIWE JWT (options.getJwt)`);n.Authorization=`Bearer ${a}`}let i;try{i=await this.fetchImpl(`${this.baseUrl}${e}${z(t.query)}`,{method:t.method,headers:n,body:t.payload?JSON.stringify(t.payload):void 0})}catch(a){throw new o("API_ERROR",`Network error calling ${e}`,{cause:a instanceof Error?a.message:String(a)})}if(i.status===404&&t.notFoundAsNull)return null;if(!i.ok){let a=await i.json().catch(()=>{}),p=a?.code_name;throw new o((p?j[p]:void 0)??"API_ERROR",a?.message?`${e}: ${a.message}`:`${e} responded ${i.status}`,{status:i.status,code:a?.code,codeName:p})}return i.status===204?null:await i.json().catch(()=>null)}};function z(r){if(!r)return"";let e=new URLSearchParams;for(let[n,i]of Object.entries(r))i!==void 0&&i!==""&&e.set(n,String(i));let t=e.toString();return t?`?${t}`:""}function h(r){return r!=null&&r!==""}function s(r){return typeof r=="string"?r:""}function c(r){return typeof r=="string"&&r?r:null}function d(r,e){if(typeof r=="bigint")return r;if(typeof r=="number"){if(!Number.isSafeInteger(r))throw new o("API_ERROR",`${e} exceeds safe-integer precision as a JSON number`,{value:r});return BigInt(r)}let t=typeof r=="string"?r.trim():"";if(!t)return BigInt(0);try{return BigInt(t)}catch{throw new o("API_ERROR",`${e} is not a valid decimal string`,{value:r})}}function K(r){let e=r??{},t=e.sender??{};return{id:Number(e.id??0),dropKey:s(e.drop_key),claimAddress:s(e.claim_address),token:s(e.token),amount:d(e.amount,"drop.amount"),message:s(e.message),envelopeId:s(e.envelope_id),depositedAt:s(e.deposited_at),rejected:e.rejected===!0,sender:{address:s(t.address),handle:s(t.handle),displayName:s(t.display_name),profileImageUrl:s(t.profile_image_url)}}}function T(r){return{xUserId:s(r.x_user_id),handle:s(r.handle),displayHandle:s(r.display_handle),displayName:s(r.display_name),profileImageUrl:s(r.profile_image_url),walletAddress:s(r.wallet_address),revealYou:r.reveal_you===!0,onchainMapped:r.onchain_mapped===!0,mappedRecipient:c(r.mapped_recipient)}}function N(r){return{identifier:s(r.identifier),displayHandle:s(r.display_handle),balance:d(r.balance,"leaderboard.balance"),lastDepositAmount:d(r.last_deposit_amount,"leaderboard.last_deposit_amount"),rank:Number(r.rank??0),previousRank:U(r.previous_rank),profileImageUrl:s(r.profile_image_url)}}function U(r){return typeof r=="number"?r:null}function C(r){let e=r??{};return{address:s(e.address),handle:s(e.handle),displayHandle:s(e.display_handle),displayName:s(e.display_name),profileImageUrl:s(e.profile_image_url)}}function W(r){return{...C(r),address:c(r?.address)}}function _(r){return{id:g(r.id),oauth_token:r.oauth.accessToken,nonce:r.nonce.toString(),deadline:r.deadline.toString()}}function k(r,e){let t=s(r?.signature);if(!t)throw new o("API_ERROR","signature response is missing signature");return{id:s(r?.id)||g(e.id),nonce:h(r?.nonce)?d(r?.nonce,"signature.nonce"):e.nonce,deadline:h(r?.deadline)?d(r?.deadline,"signature.deadline"):e.deadline,signature:t}}var D=class{constructor(e={}){this.baseUrl=(e.baseUrl??O()).replace(/\/+$/,""),this.domain=e.domain??globalThis.location?.origin??"";let t=e.fetchImpl??globalThis.fetch;if(!t)throw new Error("fetch is unavailable; provide options.fetchImpl");this.fetchImpl=t}unsignedHash(e,t){return this.post("/login/unsigned-hash",{chain_id:e,address:t,domain:this.domain})}siweToken(e,t){return this.post("/login/token",{address:e,signature:t,domain:this.domain})}async post(e,t){let n;try{n=await this.fetchImpl(`${this.baseUrl}/cross-auth${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(a){throw new o("API_ERROR",`cross-auth network error calling ${e}`,{cause:a instanceof Error?a.message:String(a)})}let i=await n.json().catch(()=>({}));if(!n.ok||i.data==null)throw new o("API_ERROR",`cross-auth ${e} failed`,{code:i.code,message:i.message});return i.data}};async function x(){let r=P(B(32)),e=await G().digest("SHA-256",J(r)),t=P(new Uint8Array(e));return{verifier:r,challenge:t,method:"S256"}}function L(){return P(B(16))}function B(r){let e=globalThis.crypto;if(!e?.getRandomValues)throw new Error("crypto.getRandomValues unavailable");let t=new Uint8Array(r);return e.getRandomValues(t),t}function G(){let r=globalThis.crypto?.subtle;if(!r)throw new Error("crypto.subtle unavailable (needs https/secure context)");return r}function J(r){return new TextEncoder().encode(r)}function P(r){let e="";for(let n of r)e+=String.fromCharCode(n);let t=globalThis.btoa?.(e);if(t===void 0)throw new Error("btoa unavailable");return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var M=class{constructor(e={}){this.baseUrl=(e.baseUrl??"").replace(/\/+$/,""),this.tokenPath=e.tokenPath??"/api/x/token",this.mePath=e.mePath??"/api/x/me";let t=e.fetchImpl??globalThis.fetch;if(!t)throw new Error("fetch is unavailable; provide options.fetchImpl");this.fetchImpl=t}async exchangeCode(e){let n=await(await this.call(this.tokenPath,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:e.clientId,redirectUri:e.redirectUri,code:e.code,verifier:e.codeVerifier})})).json().catch(()=>({}));if(!n.access_token)throw new o("API_ERROR","X token exchange: missing access_token",{body:n});return{accessToken:n.access_token,scope:n.scope,expiresIn:n.expires_in,refreshToken:n.refresh_token}}async getHandle(e){let n=await(await this.call(this.mePath,{method:"GET",headers:{Authorization:`Bearer ${e}`}})).json().catch(()=>({})),i=n.data?.username??n.username;if(!i)throw new o("API_ERROR","X /me: missing username",{body:n});return{handle:i}}async call(e,t){let n;try{n=await this.fetchImpl(`${this.baseUrl}${e}`,t)}catch(i){throw new o("API_ERROR",`Network error calling ${e}`,{cause:i instanceof Error?i.message:String(i)})}if(!n.ok)throw new o("API_ERROR",`${e} responded ${n.status}`,{status:n.status});return n}};var y="pop.xauth.verifier",E="pop.xauth.state",Y="https://x.com/i/oauth2/authorize",Z="tweet.read users.read offline.access",H=class{constructor(e){this.opts={clientId:e.clientId,redirectUri:e.redirectUri,scope:e.scope??Z,authorizeUrl:e.authorizeUrl??Y,port:e.port,storage:e.storage??Q()}}async start(){let e=await x(),t=L();this.opts.storage.set(y,e.verifier),this.opts.storage.set(E,t);let n=new URLSearchParams({response_type:"code",client_id:this.opts.clientId,redirect_uri:this.opts.redirectUri,scope:this.opts.scope,state:t,code_challenge:e.challenge,code_challenge_method:"S256"});return{authorizeUrl:`${this.opts.authorizeUrl}?${n.toString()}`,state:t}}async complete(e){let t=new URL(e),n=t.searchParams.get("code"),i=t.searchParams.get("state");if(!n)throw new o("API_ERROR","X callback: missing authorization code",{error:t.searchParams.get("error")});let a=this.opts.storage.get(E);if(!i||!a||i!==a)throw new o("API_ERROR","X callback: state mismatch (possible CSRF)");let p=this.opts.storage.get(y);if(!p)throw new o("API_ERROR","X callback: missing PKCE verifier (expired session?)");let b=await this.opts.port.exchangeCode({clientId:this.opts.clientId,redirectUri:this.opts.redirectUri,code:n,codeVerifier:p}),{handle:X}=await this.opts.port.getHandle(b.accessToken);return this.opts.storage.remove(y),this.opts.storage.remove(E),{oauth:{provider:"x",accessToken:b.accessToken},handle:X}}};function Q(){let r=globalThis.sessionStorage;if(!r)throw new Error("sessionStorage unavailable; provide options.storage");return{get:e=>r.getItem(e),set:(e,t)=>r.setItem(e,t),remove:e=>r.removeItem(e)}}export{f as a,ee as b,R as c,A as d,w as e,F as f,q as g,te as h,I as i,O as j,v as k,D as l,x as m,L as n,M as o,H as p};
@@ -0,0 +1 @@
1
+ var r=class extends Error{constructor(t,s,d){super(s),this.name="SafeDropError",this.code=t,this.details=d}};function n(e){return e.trim().replace(/^@/,"").toLowerCase()}export{r as a,n as b};
@@ -0,0 +1 @@
1
+ import{a as o,b as D}from"./chunk-PV4F2RR3.js";function S(a){let e=a.baseUrl.replace(/\/$/,""),r=e.includes("?")?"&":"?",n=a.claimAddress?`&claim=${encodeURIComponent(a.claimAddress)}`:"",s=`${e}${r}sender=${encodeURIComponent(a.sender)}${n}`;return a.secret?`${s}#${encodeURIComponent(a.secret)}`:s}function E(a){let e=a.indexOf("#"),r=e===-1?a:a.slice(0,e),n=e===-1?"":a.slice(e+1),s=r.indexOf("?"),p=s===-1?"":r.slice(s+1);return{sender:b(p,"sender"),secret:n?decodeURIComponent(n):null}}function B(a){return`\u{1F381} You've received a one-pop drop! Claim your tokens here: ${a}`}function M(a,e){let r=[`text=${encodeURIComponent(a)}`];return e&&r.push(`recipient_id=${encodeURIComponent(e)}`),`https://x.com/messages/compose?${r.join("&")}`}function b(a,e){if(!a)return null;for(let r of a.split("&")){if(!r)continue;let n=r.indexOf("=");if(decodeURIComponent(n===-1?r:r.slice(0,n))===e)return decodeURIComponent(n===-1?"":r.slice(n+1))}return null}var g=class{constructor(e,r,n,s){this.chain=e;this.api=r;this.crypto=n;this.claimBaseUrl=s}async execute(e){if(!e.sender)throw new o("MISSING_SENDER","sender address is required");if(!e.recipient?.handle)throw new o("MISSING_RECIPIENT","recipient social handle is required");if(!e.token)throw new o("INVALID_TOKEN","token address is required (ERC20 only)");if(e.amount<=0n)throw new o("INVALID_AMOUNT","amount must be a positive BigInt");if(e.message&&[...e.message].length>140)throw new o("INVALID_PARAM","message must be <= 140 runes");let r=await this.api.createClaimWallet({sender:e.sender,recipient:e.recipient}),n=r.id,s=async c=>{if(this.api.recordDropMetadata)try{await this.api.recordDropMetadata({txHash:c,message:e.message,envelopeId:e.envelopeId})}catch(m){if(m instanceof o&&m.details?.codeName==="ENVELOPE_NOT_FOUND"&&e.envelopeId)try{await this.api.recordDropMetadata({txHash:c,message:e.message})}catch{}}};if(r.isMapped){let{txHash:c,dropKey:m}=await this.chain.depositMapped({token:e.token,amount:e.amount,id:n,onSubmitted:s});return{isMapped:!0,dropKey:m,depositTxHash:c}}let p=e.secret??this.crypto.randomSecret();if(!p)throw new o("MISSING_SECRET","secret is empty");let i=this.crypto.keccak256(p),t={claimAddress:r.claimAddress,token:e.token,amount:e.amount,id:n,secretHash:i,onSubmitted:s},{txHash:l,dropKey:u}=await this.chain.depositWithPermit(t);return{isMapped:!1,dropKey:u,claimAddress:r.claimAddress,secretHash:i,withdrawLink:S({baseUrl:this.claimBaseUrl,sender:e.sender,claimAddress:r.claimAddress,secret:p}),depositTxHash:l}}};var N=BigInt(1800),x=30,y=class{constructor(e,r,n,s=()=>Date.now()){this.chain=e;this.api=r;this.crypto=n;this.now=s}async execute(e){let r=e.id;if(!r)throw new o("MISSING_RECIPIENT","batchClaim requires an id");let n=D(r);if(!n)throw new o("MISSING_RECIPIENT","batchClaim requires an id");if(!e.claimAddress)throw new o("MISSING_CLAIM_ADDRESS","claim address is required");if(!e.sponsor)throw new o("MISSING_SENDER","sponsor address is required");if(!e.claimKey)throw new o("MISSING_CLAIM_KEY","claim key is required");if(!e.secret)throw new o("MISSING_SECRET","secret is required");if(!this.api.requestBatchClaimSignature)throw new o("API_ERROR","requestBatchClaimSignature is not implemented");if(!this.chain.getValidatorNonce||!this.chain.getValidatorClaimDigest||!this.chain.getValidator)throw new o("CHAIN_ERROR","validator reads are not implemented");let s=await this.chain.getDropKeyByClaimAddress(e.claimAddress,e.sponsor);if(!s)throw new o("DROP_NOT_FOUND","anchor drop not found");let p=await this.chain.getDropByKey(s);if(!p||p.id!==n)throw new o("DROP_NOT_FOUND","anchor drop id does not match");let i=await this.chain.getPendingDropsById({id:n});if(!i.length)throw new o("DROP_NOT_FOUND",`No pending drops for ${r}`);let t=e.maxCount??x;if(!Number.isSafeInteger(t)||t<=0)throw new o("INVALID_PARAM","maxCount must be a positive safe integer");let l=e.deadline??BigInt(Math.floor(this.now()/1e3))+(e.deadlineTtlSeconds??N),u=[],c="",m=BigInt(0);for(;i.length;){let R=await this.chain.getValidatorNonce({id:n}),h=await this.api.requestBatchClaimSignature({id:r,oauth:e.oauth,nonce:R,deadline:l});if(e.recipient&&e.recipient.toLowerCase()!==h.recipient.toLowerCase())throw new o("SIGN_FAILED","validator signature is bound to a different recipient");if(c&&c.toLowerCase()!==h.recipient.toLowerCase())throw new o("SIGN_FAILED","validator recipient changed between batches");c=h.recipient,u.length||(m=h.nonce);let I=await this.chain.getValidatorClaimDigest({executor:c,recipient:c,id:n,nonce:h.nonce,deadline:h.deadline});await this.assertSignedByValidator(I,h.signature);let A=i.length,C=await this.chain.withdrawUnmappedBatchByKeys({claimKey:e.claimKey,recipient:c,id:n,anchorDropKey:s,secret:e.secret,nonce:h.nonce,deadline:h.deadline,executor:c,dropKeys:i.slice(0,t).map(w=>w.dropKey).filter(w=>w.toLowerCase()!==s.toLowerCase()),validatorSignature:h.signature});if(u.push(C),i=await this.chain.getPendingDropsById({id:n}),i.length>=A)throw new o("CHAIN_ERROR","batch claim made no progress",{id:r,txHash:C})}return{txHashes:u,recipient:c,id:r,nonce:m,deadline:l}}async assertSignedByValidator(e,r){if(!this.crypto.recoverAddress||!this.chain.getValidator)return;let[n,s]=await Promise.all([this.crypto.recoverAddress({digest:e,signature:r}),this.chain.getValidator()]);if(n.toLowerCase()!==s.toLowerCase())throw new o("SIGN_FAILED","batch-claim signature does not recover to validator")}};var f=class{constructor(e,r){this.chain=e;this.signer=r}async execute(e){if(!e.recipient)throw new o("MISSING_RECIPIENT","recipient address is required");if(!e.claimAddress)throw new o("MISSING_CLAIM_ADDRESS","claim address is required");if(!e.secret)throw new o("MISSING_SECRET","secret is required");if(!e.claimKey)throw new o("MISSING_CLAIM_KEY","claim key is required");if(!e.sponsor)throw new o("MISSING_SENDER","sponsor address is required");let r=await this.chain.getDropKeyByClaimAddress(e.claimAddress,e.sponsor);if(!r)throw new o("DROP_NOT_FOUND",`No drop for claim address ${e.claimAddress}`);let n=await this.chain.getDropByKey(r);if(!n)throw new o("DROP_NOT_FOUND",`No drop for key ${r}`);let s=await this.chain.getClaimDigest({recipient:e.recipient,id:n.id,dropKey:r}),p=await this.signer.signDigest({claimKey:e.claimKey,digest:s});return{txHash:await this.chain.withdrawUnmapped({claimKey:e.claimKey,recipient:e.recipient,id:n.id,dropKey:r,signature:p,secret:e.secret})}}};var P=class{constructor(e){this.chain=e}async execute(e){if(!e.claimAddress)throw new o("MISSING_CLAIM_ADDRESS","claim address is required");if(!e.sponsor)throw new o("MISSING_SENDER","sponsor address is required");let r=await this.chain.getDropKeyByClaimAddress(e.claimAddress,e.sponsor);if(!r)throw new o("DROP_NOT_FOUND",`No drop for claim address ${e.claimAddress}`);return{txHash:await this.chain.refundByKey({dropKey:r})}}};function d(a,e){if(!a)throw new o("API_ERROR",`SafeDropApiPort.${e} is not implemented by the injected api adapter`);return a}function V(a,e){let r=new g(e.chain,e.api,e.crypto,a.claimBaseUrl),n=new f(e.chain,e.signer),s=new P(e.chain),p=new y(e.chain,e.api,e.crypto),{api:i}=e;return{config:a,deposit:t=>r.execute(t),retrieveClaimKey:t=>i.retrieveClaimKey(t),withdraw:t=>n.execute(t),refund:t=>s.execute(t),getDrop:(t,l)=>e.chain.getDrop(t,l),getDropByKey:t=>e.chain.getDropByKey(t),getDropKeyByClaimAddress:(t,l)=>e.chain.getDropKeyByClaimAddress(t,l),getClaimedRecipient:t=>e.chain.getClaimedRecipient({id:t}),getPendingDropsById:t=>e.chain.getPendingDropsById({id:t}),getPendingDropsByRecipient:t=>e.chain.getPendingDropsByRecipient({recipient:t}),getPendingDropsBySponsor:t=>e.chain.getPendingDropsBySponsor({sponsor:t}),withdrawUnmapped:t=>e.chain.withdrawUnmapped(t),withdrawMapped:t=>e.chain.withdrawMapped(t),batchWithdrawMapped:t=>e.chain.batchWithdrawMapped({count:t}),batchWithdrawMappedByKeys:t=>e.chain.batchWithdrawMappedByKeys({dropKeys:t}),refundByKey:t=>e.chain.refundByKey({dropKey:t}),getChangeNonce:t=>e.chain.getChangeNonce({id:t}),getPendingRecipientChange:t=>e.chain.getPendingRecipientChange({id:t}),requestRecipientChange:(t,l)=>e.chain.requestRecipientChange({id:t,newRecipient:l}),completeRecipientChange:t=>e.chain.completeRecipientChange(t),cancelRecipientChange:t=>e.chain.cancelRecipientChange({id:t}),resetRecipient:t=>e.chain.resetRecipient(t),listDrops:t=>d(i.listDrops,"listDrops").call(i,t),rejectDrops:t=>d(i.rejectDrops,"rejectDrops").call(i,{dropIds:t}),listEnvelopes:t=>d(i.listEnvelopes,"listEnvelopes").call(i,t),getLeaderboard:t=>d(i.getLeaderboard,"getLeaderboard").call(i,t),getMyLeaderboardEntry:t=>d(i.getMyLeaderboardEntry,"getMyLeaderboardEntry").call(i,t),listHistories:t=>d(i.listHistories,"listHistories").call(i,t),getXConnection:()=>d(i.getXConnection,"getXConnection").call(i),connectX:t=>d(i.connectX,"connectX").call(i,t),disconnectX:()=>d(i.disconnectX,"disconnectX").call(i),submitFeedback:t=>d(i.submitFeedback,"submitFeedback").call(i,t),setRevealYou:t=>d(i.setRevealYou,"setRevealYou").call(i,{revealYou:t}),requestRecipientChangeSignature:t=>d(i.requestRecipientChangeSignature,"requestRecipientChangeSignature").call(i,t),requestRecipientResetSignature:t=>d(i.requestRecipientResetSignature,"requestRecipientResetSignature").call(i,t),batchClaim:t=>p.execute(t),requestBatchClaimSignature:t=>d(i.requestBatchClaimSignature,"requestBatchClaimSignature").call(i,t)}}export{S as a,E as b,B as c,M as d,g as e,y as f,f as g,P as h,V as i};
@@ -1,4 +1,4 @@
1
- import { S as Secret, a as SecretHash, H as Hex, A as Address, I as Id, D as DepositParams, b as DepositResult, O as OAuthProof, W as WithdrawParams, c as WithdrawResult, R as RefundParams, d as RefundResult, e as DropInbox, E as Envelope, L as LeaderboardPage, M as MyLeaderboardEntry, f as HistoryType, g as HistoryStatus, h as HistoryPage, X as XConnection, i as RecipientChangeSignature, j as RecipientSignature, B as BatchClaimParams, k as BatchClaimResult, l as BatchClaimSignature, m as SafeDropApiPort } from './SafeDropApiPort-B7NfQOsb.js';
1
+ import { S as Secret, a as SecretHash, H as Hex, A as Address, I as Id, D as DepositParams, b as DepositResult, O as OAuthProof, W as WithdrawParams, c as WithdrawResult, R as RefundParams, d as RefundResult, e as DropInbox, E as Envelope, L as LeaderboardPage, M as MyLeaderboardEntry, f as HistoryType, g as HistoryStatus, h as HistoryPage, X as XConnection, i as RecipientChangeSignature, j as RecipientSignature, B as BatchClaimParams, k as BatchClaimResult, l as BatchClaimSignature, m as SafeDropApiPort } from './SafeDropApiPort-CsPo0Pmn.js';
2
2
 
3
3
  /**
4
4
  * 순수 계산이 아니라 외부 구현(해시 라이브러리/CSPRNG)이 필요한 암호 연산.
@@ -1,4 +1,4 @@
1
- import { m as SafeDropApiPort, A as Address, w as SocialIdentifier, I as Id, H as Hex, O as OAuthProof, e as DropInbox, E as Envelope, L as LeaderboardPage, M as MyLeaderboardEntry, f as HistoryType, g as HistoryStatus, h as HistoryPage, X as XConnection, i as RecipientChangeSignature, j as RecipientSignature, l as BatchClaimSignature } from './SafeDropApiPort-B7NfQOsb.js';
1
+ import { m as SafeDropApiPort, A as Address, w as SocialIdentifier, I as Id, H as Hex, O as OAuthProof, e as DropInbox, E as Envelope, L as LeaderboardPage, M as MyLeaderboardEntry, f as HistoryType, g as HistoryStatus, h as HistoryPage, X as XConnection, i as RecipientChangeSignature, j as RecipientSignature, l as BatchClaimSignature } from './SafeDropApiPort-CsPo0Pmn.js';
2
2
  import { X as XAuthPort, a as XTokenResult } from './XAuthPort-BNJePosj.js';
3
3
 
4
4
  /**
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { m as SafeDropApiPort, D as DepositParams, b as DepositResult, B as BatchClaimParams, k as BatchClaimResult, W as WithdrawParams, c as WithdrawResult, R as RefundParams, d as RefundResult, A as Address, S as Secret } from './SafeDropApiPort-B7NfQOsb.js';
2
- export { l as BatchClaimSignature, e as DropInbox, n as DropSender, E as Envelope, o as EnvelopeLayout, H as Hex, p as HistoryEntry, h as HistoryPage, q as HistoryParty, r as HistoryReceiverParty, g as HistoryStatus, f as HistoryType, I as Id, s as LeaderboardEntry, L as LeaderboardPage, t as MappedDepositResult, M as MyLeaderboardEntry, O as OAuthProof, P as PendingDrop, i as RecipientChangeSignature, j as RecipientSignature, u as SafeDropError, v as SafeDropErrorCode, a as SecretHash, w as SocialIdentifier, x as SocialProvider, U as UnmappedDepositResult, X as XConnection } from './SafeDropApiPort-B7NfQOsb.js';
3
- import { a as SafeDropChainPort, C as CryptoPort, b as ClaimSignerPort } from './createSafeDrop-BGoIQ4nK.js';
4
- export { D as DropState, O as OnePopDrop, S as SafeDrop, c as SafeDropConfig, d as SafeDropDeps, e as createSafeDrop } from './createSafeDrop-BGoIQ4nK.js';
1
+ import { m as SafeDropApiPort, D as DepositParams, b as DepositResult, B as BatchClaimParams, k as BatchClaimResult, W as WithdrawParams, c as WithdrawResult, R as RefundParams, d as RefundResult, A as Address, S as Secret } from './SafeDropApiPort-CsPo0Pmn.js';
2
+ export { l as BatchClaimSignature, e as DropInbox, n as DropSender, E as Envelope, o as EnvelopeLayout, H as Hex, p as HistoryEntry, h as HistoryPage, q as HistoryParty, r as HistoryReceiverParty, g as HistoryStatus, f as HistoryType, I as Id, s as LeaderboardEntry, L as LeaderboardPage, t as MappedDepositResult, M as MyLeaderboardEntry, O as OAuthProof, P as PendingDrop, i as RecipientChangeSignature, j as RecipientSignature, u as SafeDropError, v as SafeDropErrorCode, a as SecretHash, w as SocialIdentifier, x as SocialProvider, U as UnmappedDepositResult, X as XConnection } from './SafeDropApiPort-CsPo0Pmn.js';
3
+ import { a as SafeDropChainPort, C as CryptoPort, b as ClaimSignerPort } from './createSafeDrop-DCCWJRxc.js';
4
+ export { D as DropState, O as OnePopDrop, S as SafeDrop, c as SafeDropConfig, d as SafeDropDeps, e as createSafeDrop } from './createSafeDrop-DCCWJRxc.js';
5
5
  export { X as XAuthPort, a as XTokenResult } from './XAuthPort-BNJePosj.js';
6
6
 
7
7
  /**
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as e,b as o,c as t,d as p,e as a,f as s,g as i,h as f,i as n,j as m}from"./chunk-M7FFQCP2.js";import{a as r}from"./chunk-5DT3H2VX.js";export{i as BatchClaimUseCase,s as DepositUseCase,n as RefundUseCase,r as SafeDropError,f as WithdrawUseCase,a as buildComposeUrl,p as buildDmText,o as buildWithdrawLink,m as createSafeDrop,e as normalizeHandle,t as parseWithdrawLink};
1
+ import{a as e,b as o,c as t,d as p,e as a,f as i,g as f,h as n,i as m}from"./chunk-SOKYXF6V.js";import{a as r,b as s}from"./chunk-PV4F2RR3.js";export{i as BatchClaimUseCase,a as DepositUseCase,n as RefundUseCase,r as SafeDropError,f as WithdrawUseCase,p as buildComposeUrl,t as buildDmText,e as buildWithdrawLink,m as createSafeDrop,s as normalizeHandle,o as parseWithdrawLink};
@@ -1,7 +1,7 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { S as SafeDrop } from '../createSafeDrop-BGoIQ4nK.js';
4
- import '../SafeDropApiPort-B7NfQOsb.js';
3
+ import { S as SafeDrop } from '../createSafeDrop-DCCWJRxc.js';
4
+ import '../SafeDropApiPort-CsPo0Pmn.js';
5
5
 
6
6
  interface SafeDropProviderProps {
7
7
  client: SafeDrop;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nexus-cross/pop",
3
- "version": "1.4.1-beta.6",
3
+ "version": "1.4.1-beta.8",
4
4
  "description": "pop — framework-agnostic core + React adapter.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1 +0,0 @@
1
- var e=class extends Error{constructor(r,t,s){super(t),this.name="SafeDropError",this.code=r,this.details=s}};export{e as a};
@@ -1 +0,0 @@
1
- import{a as o}from"./chunk-5DT3H2VX.js";var g=BigInt(500),Q=BigInt(1e4),E={dev:{apiBaseUrl:"https://dev-one-pop-api.onechain.nexus/api",contracts:{onePop:"0xdC44AEF049Fb86Bd78CA887C330903cb2c031b7D",permitErc20:"0xFaDAB54449262178aE0562F5D8416bBeF4659714",nft:"0xc09f0E4B342e32ef32ca73306B5A29B3C8d01aE8",nftMinter:"0xdC44AEF049Fb86Bd78CA887C330903cb2c031b7D",validator:"0xF30d8e0544f0b92A6987522f4F696D3915B579b4",feeRecipient:"0xF30d8e0544f0b92A6987522f4F696D3915B579b4"}},stage:{apiBaseUrl:"https://stg-one-pop-api.onechain.nexus/api",contracts:{onePop:"0xb03B0C0d03E4Cbe91edD48fa3C4E6Bb1EEA65eDe",permitErc20:"0xFaDAB54449262178aE0562F5D8416bBeF4659714",nft:"0x0B35DaD70114663EC07d5b86763B15f3DaCd7C8D",nftMinter:"0x7a54205e47819344eC3b89D5637C779531346642",validator:"0xa953af3742345dFC2BdcA30cBa79D8313b0a3B61",feeRecipient:"0xa953af3742345dFC2BdcA30cBa79D8313b0a3B61"}},production:{apiBaseUrl:"https://one-pop-api.onechain.nexus/api"}},b={createWallet:"/wallets",dropMetadata:"/drops/metadata",retrievePrivateKey:"/wallets/private-key",drops:"/drops",rejectDrops:"/drops/reject",envelopes:"/envelopes",leaderboards:"/leaderboards",leaderboardMe:"/leaderboards/me",histories:"/histories",xConnections:"/x-connections",batchClaimSignature:"/batch-claim-signature",feedbacks:"/feedbacks",revealYou:"/reveal-you",recipientChangeSignature:"/recipient-change-signature",recipientResetSignature:"/recipient-reset-signature",eventsSubscribe:"/events/subscribe"},X="https://dev-cross-auth.crosstoken.io";function f(r){try{return import.meta.env?.[r]}catch{return}}function u(r){if(!(typeof process>"u"||!process.env))switch(r){case"NEXT_PUBLIC_ONE_POP_ENVIRONMENT":return process.env.NEXT_PUBLIC_ONE_POP_ENVIRONMENT;case"ONE_POP_ENVIRONMENT":return process.env.ONE_POP_ENVIRONMENT;case"NEXT_PUBLIC_ONE_POP_API_BASE_URL":return process.env.NEXT_PUBLIC_ONE_POP_API_BASE_URL;case"NEXT_PUBLIC_CROSS_AUTH_URL":return process.env.NEXT_PUBLIC_CROSS_AUTH_URL;default:return}}function R(){let r=f("VITE_ONE_POP_ENVIRONMENT")??u("NEXT_PUBLIC_ONE_POP_ENVIRONMENT")??u("ONE_POP_ENVIRONMENT");return $(r)}function $(r){switch(r?.toLowerCase()){case"dev":case"development":return"dev";case"stg":case"stage":case"staging":return"stage";case void 0:case"production":case"prod":return"production";default:throw new Error(`[pop] Invalid environment: ${r}`)}}function F(){return E[R()]}function ee(){return q(R())}function q(r){let e=E[r].contracts;if(!e)throw new Error(`[pop] Contract addresses are not configured for ${r}`);return e}function A(){let e=f("VITE_ONE_POP_API_BASE_URL")??u("NEXT_PUBLIC_ONE_POP_API_BASE_URL")??F().apiBaseUrl;return I(e),e}function w(){let e=(f("VITE_CROSS_AUTH_URL")??u("NEXT_PUBLIC_CROSS_AUTH_URL")??X).replace(/\/+$/,"");return I(e),e}function I(r){let e;try{e=new URL(r)}catch{throw new Error(`[pop] Invalid base URL: ${r}`)}if(e.protocol==="https:")return;let t=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname.endsWith(".local");if(!(e.protocol==="http:"&&t))throw new Error(`[pop] base URL must be https (or http://localhost for dev). Got: ${r}`)}var V={INVALID_PARAM:"INVALID_PARAM",RATE_LIMITED:"RATE_LIMITED",INVALID_OAUTH_TOKEN:"INVALID_OAUTH_TOKEN",UNAUTHORIZED:"UNAUTHORIZED",WALLET_NOT_FOUND:"WALLET_NOT_FOUND",SEND_BLOCKED:"SEND_BLOCKED",ENVELOPE_NOT_FOUND:"ENVELOPE_NOT_FOUND",PENDING_LIMIT_EXCEEDED:"PENDING_LIMIT_EXCEEDED",DROP_NOT_FOUND:"DROP_NOT_FOUND",IDENTIFIER_NOT_MAPPED:"IDENTIFIER_NOT_MAPPED",X_CONNECTION_NOT_FOUND:"X_CONNECTION_NOT_FOUND",X_ALREADY_CONNECTED:"X_ALREADY_CONNECTED"},l=140,O=class{constructor(e={}){this.baseUrl=(e.baseUrl??A()).replace(/\/+$/,"");let t=e.fetchImpl??globalThis.fetch;if(!t)throw new Error("fetch is unavailable; provide options.fetchImpl");this.fetchImpl=t,this.getJwt=e.getJwt,this.paths={...b,...e.paths}}async createClaimWallet(e){let t=await this.request(this.paths.createWallet,{method:"POST",auth:!0,payload:{identifier:e.recipient.handle,oauth_type:e.recipient.provider,sender_address:e.sender}});if(!t?.address)throw new o("API_ERROR","createClaimWallet: missing address in response",{body:t});if(!t.identifier)throw new o("API_ERROR","createClaimWallet: missing identifier in response",{body:t});return{claimAddress:t.address,id:t.identifier,isMapped:t.is_mapped===!0}}async recordDropMetadata(e){if(e.message&&[...e.message].length>l)throw new o("INVALID_PARAM",`message must be <= ${l} runes`);await this.request(this.paths.dropMetadata,{method:"POST",auth:!0,query:{tx_hash:e.txHash},payload:{...e.message?{message:e.message}:{},...e.envelopeId?{envelope_id:e.envelopeId}:{}}})}async retrieveClaimKey(e){let t=await this.request(this.paths.retrievePrivateKey,{method:"POST",payload:{oauth_token:e.oauth.accessToken,oauth_type:e.oauth.provider,sender_address:e.senderAddress,address:e.claimAddress}});if(t?.private_key&&t.address){if(t.address.toLowerCase()!==e.claimAddress.toLowerCase())throw new o("API_ERROR","retrieveClaimKey: returned a different address");return{isMapped:!1,claimKey:t.private_key,claimAddress:t.address}}if(t?.is_mapped===!0)return{isMapped:!0};throw new o("API_ERROR","retrieveClaimKey: missing key/address in response",{body:t})}async listDrops(e){if(!e?.token)throw new o("INVALID_PARAM","listDrops requires a token address");let t=await this.request(this.paths.drops,{method:"GET",auth:!0,query:{token:e.token,drop_key:e.dropKey}});return{items:(t?.items??[]).map(z),count:t?.count??0,totalAmount:d(t?.total_amount,"drops.total_amount"),hasClaimedBefore:t?.has_claimed_before===!0,mappedRecipient:c(t?.mapped_recipient),pendingChangeTo:c(t?.pending_change_to),feeBps:t?.fee_bps??Number(g)}}async rejectDrops(e){if(!Array.isArray(e.dropIds)||e.dropIds.length===0||e.dropIds.length>100||e.dropIds.some(n=>!Number.isSafeInteger(n)||n<=0))throw new o("INVALID_PARAM","dropIds must contain 1-100 positive integers");return(await this.request(this.paths.rejectDrops,{method:"POST",auth:!0,payload:{drop_ids:e.dropIds}}))?.count??0}async listEnvelopes(e={}){return((await this.request(this.paths.envelopes,{method:"GET",query:{locale:e.locale}}))?.items??[]).map(n=>({id:s(n.id),name:s(n.name),imageUrl:s(n.image_url),badge:s(n.badge),sortOrder:Number(n.sort_order??0),layout:n.layout}))}async getLeaderboard(e){if(!e.token)throw new o("INVALID_PARAM","getLeaderboard requires a token address");let t=await this.request(this.paths.leaderboards,{method:"GET",query:{token:e.token,page:e.page,page_size:e.pageSize,identifier:e.identifier}});return{items:(t?.items??[]).map(T),page:t?.page??1,pageSize:t?.page_size??0,total:t?.total??0}}async getMyLeaderboardEntry(e){let t=await this.request(this.paths.leaderboardMe,{method:"GET",auth:!0,query:{token:e.token}});return{...T(t??{}),rank:k(t?.rank)}}async listHistories(e){if(!e?.type)throw new o("INVALID_PARAM","listHistories requires type");let t=await this.request(this.paths.histories,{method:"GET",auth:!0,query:{type:e.type,token:e.token,status:e.status,rejected:e.rejected===void 0?void 0:String(e.rejected),page:e.page,page_size:e.pageSize}});return{items:(t?.items??[]).map(n=>({id:Number(n.id??0),type:s(n.type),status:s(n.status),token:s(n.token),amount:d(n.amount,"history.amount"),claimAddress:s(n.claim_address),depositTxHash:s(n.deposit_tx_hash),depositedAt:s(n.deposited_at),resolvedTxHash:c(n.resolved_tx_hash),resolvedAt:c(n.resolved_at),message:s(n.message),feedback:c(n.feedback),envelopeId:s(n.envelope_id),rejected:n.rejected===!0,sender:U(n.sender),receiver:K(n.receiver)})),page:t?.page??1,pageSize:t?.page_size??0,total:t?.total??0,feeBps:t?.fee_bps??Number(g)}}async getXConnection(){let e=await this.request(this.paths.xConnections,{method:"GET",auth:!0,notFoundAsNull:!0});return e?S(e):null}async connectX(e){let t=await this.request(this.paths.xConnections,{method:"POST",auth:!0,payload:{oauth_token:e.oauth.accessToken}});return S(t??{})}async disconnectX(){await this.request(this.paths.xConnections,{method:"DELETE",auth:!0,notFoundAsNull:!0})}async submitFeedback(e){if(!Number.isSafeInteger(e.dropId)||e.dropId<=0)throw new o("INVALID_PARAM","dropId must be a positive integer");if(!e.message.trim()||[...e.message.trim()].length>l)throw new o("INVALID_PARAM",`message must be 1-${l} runes`);let t=await this.request(this.paths.feedbacks,{method:"PUT",auth:!0,query:{drop_id:e.dropId},payload:{message:e.message}});return s(t?.message)}async setRevealYou(e){return(await this.request(this.paths.revealYou,{method:"PUT",auth:!0,payload:{reveal_you:e.revealYou}}))?.reveal_you===!0}async requestRecipientChangeSignature(e){let t=await this.request(this.paths.recipientChangeSignature,{method:"POST",auth:!0,payload:v(e)});return{...N(t,e),newRecipient:s(t?.new_recipient)}}async requestRecipientResetSignature(e){let t=await this.request(this.paths.recipientResetSignature,{method:"POST",payload:v(e)});return N(t,e)}async requestBatchClaimSignature(e){let t=await this.request(this.paths.batchClaimSignature,{method:"POST",auth:!0,payload:{id:e.id,oauth_token:e.oauth.accessToken,nonce:e.nonce.toString(),deadline:e.deadline.toString()}}),n=s(t?.signature);if(!n)throw new o("API_ERROR","requestBatchClaimSignature: missing signature",{body:t});return{id:s(t?.id)||e.id,recipient:s(t?.recipient),nonce:h(t?.nonce)?d(t?.nonce,"batchClaim.nonce"):e.nonce,deadline:h(t?.deadline)?d(t?.deadline,"batchClaim.deadline"):e.deadline,signature:n}}async request(e,t){let n={};if(t.payload&&(n["Content-Type"]="application/json"),t.auth){let a=await this.getJwt?.();if(!a)throw new o("UNAUTHORIZED",`${e} requires a SIWE JWT (options.getJwt)`);n.Authorization=`Bearer ${a}`}let i;try{i=await this.fetchImpl(`${this.baseUrl}${e}${j(t.query)}`,{method:t.method,headers:n,body:t.payload?JSON.stringify(t.payload):void 0})}catch(a){throw new o("API_ERROR",`Network error calling ${e}`,{cause:a instanceof Error?a.message:String(a)})}if(i.status===404&&t.notFoundAsNull)return null;if(!i.ok){let a=await i.json().catch(()=>{}),p=a?.code_name;throw new o((p?V[p]:void 0)??"API_ERROR",a?.message?`${e}: ${a.message}`:`${e} responded ${i.status}`,{status:i.status,code:a?.code,codeName:p})}return i.status===204?null:await i.json().catch(()=>null)}};function j(r){if(!r)return"";let e=new URLSearchParams;for(let[n,i]of Object.entries(r))i!==void 0&&i!==""&&e.set(n,String(i));let t=e.toString();return t?`?${t}`:""}function h(r){return r!=null&&r!==""}function s(r){return typeof r=="string"?r:""}function c(r){return typeof r=="string"&&r?r:null}function d(r,e){if(typeof r=="bigint")return r;if(typeof r=="number"){if(!Number.isSafeInteger(r))throw new o("API_ERROR",`${e} exceeds safe-integer precision as a JSON number`,{value:r});return BigInt(r)}let t=typeof r=="string"?r.trim():"";if(!t)return BigInt(0);try{return BigInt(t)}catch{throw new o("API_ERROR",`${e} is not a valid decimal string`,{value:r})}}function z(r){let e=r??{},t=e.sender??{};return{id:Number(e.id??0),dropKey:s(e.drop_key),claimAddress:s(e.claim_address),token:s(e.token),amount:d(e.amount,"drop.amount"),message:s(e.message),envelopeId:s(e.envelope_id),depositedAt:s(e.deposited_at),rejected:e.rejected===!0,sender:{address:s(t.address),handle:s(t.handle),displayName:s(t.display_name),profileImageUrl:s(t.profile_image_url)}}}function S(r){return{xUserId:s(r.x_user_id),handle:s(r.handle),displayHandle:s(r.display_handle),displayName:s(r.display_name),profileImageUrl:s(r.profile_image_url),walletAddress:s(r.wallet_address),revealYou:r.reveal_you===!0,onchainMapped:r.onchain_mapped===!0,mappedRecipient:c(r.mapped_recipient)}}function T(r){return{identifier:s(r.identifier),displayHandle:s(r.display_handle),balance:d(r.balance,"leaderboard.balance"),lastDepositAmount:d(r.last_deposit_amount,"leaderboard.last_deposit_amount"),rank:Number(r.rank??0),previousRank:k(r.previous_rank),profileImageUrl:s(r.profile_image_url)}}function k(r){return typeof r=="number"?r:null}function U(r){let e=r??{};return{address:s(e.address),handle:s(e.handle),displayHandle:s(e.display_handle),displayName:s(e.display_name),profileImageUrl:s(e.profile_image_url)}}function K(r){return{...U(r),address:c(r?.address)}}function v(r){return{id:r.id,oauth_token:r.oauth.accessToken,nonce:r.nonce.toString(),deadline:r.deadline.toString()}}function N(r,e){let t=s(r?.signature);if(!t)throw new o("API_ERROR","signature response is missing signature");return{id:s(r?.id)||e.id,nonce:h(r?.nonce)?d(r?.nonce,"signature.nonce"):e.nonce,deadline:h(r?.deadline)?d(r?.deadline,"signature.deadline"):e.deadline,signature:t}}var C=class{constructor(e={}){this.baseUrl=(e.baseUrl??w()).replace(/\/+$/,""),this.domain=e.domain??globalThis.location?.origin??"";let t=e.fetchImpl??globalThis.fetch;if(!t)throw new Error("fetch is unavailable; provide options.fetchImpl");this.fetchImpl=t}unsignedHash(e,t){return this.post("/login/unsigned-hash",{chain_id:e,address:t,domain:this.domain})}siweToken(e,t){return this.post("/login/token",{address:e,signature:t,domain:this.domain})}async post(e,t){let n;try{n=await this.fetchImpl(`${this.baseUrl}/cross-auth${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(a){throw new o("API_ERROR",`cross-auth network error calling ${e}`,{cause:a instanceof Error?a.message:String(a)})}let i=await n.json().catch(()=>({}));if(!n.ok||i.data==null)throw new o("API_ERROR",`cross-auth ${e} failed`,{code:i.code,message:i.message});return i.data}};async function D(){let r=m(L(32)),e=await W().digest("SHA-256",G(r)),t=m(new Uint8Array(e));return{verifier:r,challenge:t,method:"S256"}}function x(){return m(L(16))}function L(r){let e=globalThis.crypto;if(!e?.getRandomValues)throw new Error("crypto.getRandomValues unavailable");let t=new Uint8Array(r);return e.getRandomValues(t),t}function W(){let r=globalThis.crypto?.subtle;if(!r)throw new Error("crypto.subtle unavailable (needs https/secure context)");return r}function G(r){return new TextEncoder().encode(r)}function m(r){let e="";for(let n of r)e+=String.fromCharCode(n);let t=globalThis.btoa?.(e);if(t===void 0)throw new Error("btoa unavailable");return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var B=class{constructor(e={}){this.baseUrl=(e.baseUrl??"").replace(/\/+$/,""),this.tokenPath=e.tokenPath??"/api/x/token",this.mePath=e.mePath??"/api/x/me";let t=e.fetchImpl??globalThis.fetch;if(!t)throw new Error("fetch is unavailable; provide options.fetchImpl");this.fetchImpl=t}async exchangeCode(e){let n=await(await this.call(this.tokenPath,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:e.clientId,redirectUri:e.redirectUri,code:e.code,verifier:e.codeVerifier})})).json().catch(()=>({}));if(!n.access_token)throw new o("API_ERROR","X token exchange: missing access_token",{body:n});return{accessToken:n.access_token,scope:n.scope,expiresIn:n.expires_in,refreshToken:n.refresh_token}}async getHandle(e){let n=await(await this.call(this.mePath,{method:"GET",headers:{Authorization:`Bearer ${e}`}})).json().catch(()=>({})),i=n.data?.username??n.username;if(!i)throw new o("API_ERROR","X /me: missing username",{body:n});return{handle:i}}async call(e,t){let n;try{n=await this.fetchImpl(`${this.baseUrl}${e}`,t)}catch(i){throw new o("API_ERROR",`Network error calling ${e}`,{cause:i instanceof Error?i.message:String(i)})}if(!n.ok)throw new o("API_ERROR",`${e} responded ${n.status}`,{status:n.status});return n}};var _="pop.xauth.verifier",P="pop.xauth.state",J="https://x.com/i/oauth2/authorize",Y="tweet.read users.read offline.access",M=class{constructor(e){this.opts={clientId:e.clientId,redirectUri:e.redirectUri,scope:e.scope??Y,authorizeUrl:e.authorizeUrl??J,port:e.port,storage:e.storage??Z()}}async start(){let e=await D(),t=x();this.opts.storage.set(_,e.verifier),this.opts.storage.set(P,t);let n=new URLSearchParams({response_type:"code",client_id:this.opts.clientId,redirect_uri:this.opts.redirectUri,scope:this.opts.scope,state:t,code_challenge:e.challenge,code_challenge_method:"S256"});return{authorizeUrl:`${this.opts.authorizeUrl}?${n.toString()}`,state:t}}async complete(e){let t=new URL(e),n=t.searchParams.get("code"),i=t.searchParams.get("state");if(!n)throw new o("API_ERROR","X callback: missing authorization code",{error:t.searchParams.get("error")});let a=this.opts.storage.get(P);if(!i||!a||i!==a)throw new o("API_ERROR","X callback: state mismatch (possible CSRF)");let p=this.opts.storage.get(_);if(!p)throw new o("API_ERROR","X callback: missing PKCE verifier (expired session?)");let y=await this.opts.port.exchangeCode({clientId:this.opts.clientId,redirectUri:this.opts.redirectUri,code:n,codeVerifier:p}),{handle:H}=await this.opts.port.getHandle(y.accessToken);return this.opts.storage.remove(_),this.opts.storage.remove(P),{oauth:{provider:"x",accessToken:y.accessToken},handle:H}}};function Z(){let r=globalThis.sessionStorage;if(!r)throw new Error("sessionStorage unavailable; provide options.storage");return{get:e=>r.getItem(e),set:(e,t)=>r.setItem(e,t),remove:e=>r.removeItem(e)}}export{g as a,Q as b,E as c,b as d,R as e,$ as f,F as g,ee as h,A as i,w as j,O as k,C as l,D as m,x as n,B as o,M as p};
@@ -1 +0,0 @@
1
- import{a as i}from"./chunk-5DT3H2VX.js";function g(a){return a.trim().replace(/^@/,"").toLowerCase()}function S(a){let e=a.baseUrl.replace(/\/$/,""),r=e.includes("?")?"&":"?",n=a.claimAddress?`&claim=${encodeURIComponent(a.claimAddress)}`:"",s=`${e}${r}sender=${encodeURIComponent(a.sender)}${n}`;return a.secret?`${s}#${encodeURIComponent(a.secret)}`:s}function E(a){let e=a.indexOf("#"),r=e===-1?a:a.slice(0,e),n=e===-1?"":a.slice(e+1),s=r.indexOf("?"),d=s===-1?"":r.slice(s+1);return{sender:A(d,"sender"),secret:n?decodeURIComponent(n):null}}function B(a){return`\u{1F381} You've received a one-pop drop! Claim your tokens here: ${a}`}function M(a,e){let r=[`text=${encodeURIComponent(a)}`];return e&&r.push(`recipient_id=${encodeURIComponent(e)}`),`https://x.com/messages/compose?${r.join("&")}`}function A(a,e){if(!a)return null;for(let r of a.split("&")){if(!r)continue;let n=r.indexOf("=");if(decodeURIComponent(n===-1?r:r.slice(0,n))===e)return decodeURIComponent(n===-1?"":r.slice(n+1))}return null}var y=class{constructor(e,r,n,s){this.chain=e;this.api=r;this.crypto=n;this.claimBaseUrl=s}async execute(e){if(!e.sender)throw new i("MISSING_SENDER","sender address is required");if(!e.recipient?.handle)throw new i("MISSING_RECIPIENT","recipient social handle is required");if(!e.token)throw new i("INVALID_TOKEN","token address is required (ERC20 only)");if(e.amount<=0n)throw new i("INVALID_AMOUNT","amount must be a positive BigInt");if(e.message&&[...e.message].length>140)throw new i("INVALID_PARAM","message must be <= 140 runes");let r=g(e.recipient.handle);if(!r)throw new i("MISSING_RECIPIENT","recipient handle normalizes to empty");let n=await this.api.createClaimWallet({sender:e.sender,recipient:{...e.recipient,handle:r}}),s=n.id,d=async m=>{if(this.api.recordDropMetadata)try{await this.api.recordDropMetadata({txHash:m,message:e.message,envelopeId:e.envelopeId})}catch(c){if(c instanceof i&&c.details?.codeName==="ENVELOPE_NOT_FOUND"&&e.envelopeId)try{await this.api.recordDropMetadata({txHash:m,message:e.message})}catch{}}};if(n.isMapped){let{txHash:m,dropKey:c}=await this.chain.depositMapped({token:e.token,amount:e.amount,id:s,onSubmitted:d});return{isMapped:!0,dropKey:c,depositTxHash:m}}let o=e.secret??this.crypto.randomSecret();if(!o)throw new i("MISSING_SECRET","secret is empty");let t=this.crypto.keccak256(o),l={claimAddress:n.claimAddress,token:e.token,amount:e.amount,id:s,secretHash:t,onSubmitted:d},{txHash:h,dropKey:u}=await this.chain.depositWithPermit(l);return{isMapped:!1,dropKey:u,claimAddress:n.claimAddress,secretHash:t,withdrawLink:S({baseUrl:this.claimBaseUrl,sender:e.sender,claimAddress:n.claimAddress,secret:o}),depositTxHash:h}}};var b=BigInt(1800),N=30,f=class{constructor(e,r,n,s=()=>Date.now()){this.chain=e;this.api=r;this.crypto=n;this.now=s}async execute(e){let r=g(e.id);if(!r)throw new i("MISSING_RECIPIENT","batchClaim requires an id");if(!e.claimAddress)throw new i("MISSING_CLAIM_ADDRESS","claim address is required");if(!e.sponsor)throw new i("MISSING_SENDER","sponsor address is required");if(!e.claimKey)throw new i("MISSING_CLAIM_KEY","claim key is required");if(!e.secret)throw new i("MISSING_SECRET","secret is required");if(!this.api.requestBatchClaimSignature)throw new i("API_ERROR","requestBatchClaimSignature is not implemented");if(!this.chain.getValidatorNonce||!this.chain.getValidatorClaimDigest||!this.chain.getValidator)throw new i("CHAIN_ERROR","validator reads are not implemented");let n=await this.chain.getDropKeyByClaimAddress(e.claimAddress,e.sponsor);if(!n)throw new i("DROP_NOT_FOUND","anchor drop not found");let s=await this.chain.getDropByKey(n);if(!s||s.id!==r)throw new i("DROP_NOT_FOUND","anchor drop id does not match");let d=await this.chain.getPendingDropsById({id:r});if(!d.length)throw new i("DROP_NOT_FOUND",`No pending drops for ${r}`);let o=e.maxCount??N;if(!Number.isSafeInteger(o)||o<=0)throw new i("INVALID_PARAM","maxCount must be a positive safe integer");let t=e.deadline??BigInt(Math.floor(this.now()/1e3))+(e.deadlineTtlSeconds??b),l=[],h="",u=BigInt(0);for(;d.length;){let m=await this.chain.getValidatorNonce({id:r}),c=await this.api.requestBatchClaimSignature({id:r,oauth:e.oauth,nonce:m,deadline:t});if(e.recipient&&e.recipient.toLowerCase()!==c.recipient.toLowerCase())throw new i("SIGN_FAILED","validator signature is bound to a different recipient");if(h&&h.toLowerCase()!==c.recipient.toLowerCase())throw new i("SIGN_FAILED","validator recipient changed between batches");h=c.recipient,l.length||(u=c.nonce);let R=await this.chain.getValidatorClaimDigest({executor:h,recipient:h,id:r,nonce:c.nonce,deadline:c.deadline});await this.assertSignedByValidator(R,c.signature);let I=d.length,D=await this.chain.withdrawUnmappedBatchByKeys({claimKey:e.claimKey,recipient:h,id:r,anchorDropKey:n,secret:e.secret,nonce:c.nonce,deadline:c.deadline,executor:h,dropKeys:d.slice(0,o).map(C=>C.dropKey).filter(C=>C.toLowerCase()!==n.toLowerCase()),validatorSignature:c.signature});if(l.push(D),d=await this.chain.getPendingDropsById({id:r}),d.length>=I)throw new i("CHAIN_ERROR","batch claim made no progress",{id:r,txHash:D})}return{txHashes:l,recipient:h,id:r,nonce:u,deadline:t}}async assertSignedByValidator(e,r){if(!this.crypto.recoverAddress||!this.chain.getValidator)return;let[n,s]=await Promise.all([this.crypto.recoverAddress({digest:e,signature:r}),this.chain.getValidator()]);if(n.toLowerCase()!==s.toLowerCase())throw new i("SIGN_FAILED","batch-claim signature does not recover to validator")}};var P=class{constructor(e,r){this.chain=e;this.signer=r}async execute(e){if(!e.recipient)throw new i("MISSING_RECIPIENT","recipient address is required");if(!e.claimAddress)throw new i("MISSING_CLAIM_ADDRESS","claim address is required");if(!e.secret)throw new i("MISSING_SECRET","secret is required");if(!e.claimKey)throw new i("MISSING_CLAIM_KEY","claim key is required");if(!e.sponsor)throw new i("MISSING_SENDER","sponsor address is required");let r=await this.chain.getDropKeyByClaimAddress(e.claimAddress,e.sponsor);if(!r)throw new i("DROP_NOT_FOUND",`No drop for claim address ${e.claimAddress}`);let n=await this.chain.getDropByKey(r);if(!n)throw new i("DROP_NOT_FOUND",`No drop for key ${r}`);let s=await this.chain.getClaimDigest({recipient:e.recipient,id:n.id,dropKey:r}),d=await this.signer.signDigest({claimKey:e.claimKey,digest:s});return{txHash:await this.chain.withdrawUnmapped({claimKey:e.claimKey,recipient:e.recipient,id:n.id,dropKey:r,signature:d,secret:e.secret})}}};var w=class{constructor(e){this.chain=e}async execute(e){if(!e.claimAddress)throw new i("MISSING_CLAIM_ADDRESS","claim address is required");if(!e.sponsor)throw new i("MISSING_SENDER","sponsor address is required");let r=await this.chain.getDropKeyByClaimAddress(e.claimAddress,e.sponsor);if(!r)throw new i("DROP_NOT_FOUND",`No drop for claim address ${e.claimAddress}`);return{txHash:await this.chain.refundByKey({dropKey:r})}}};function p(a,e){if(!a)throw new i("API_ERROR",`SafeDropApiPort.${e} is not implemented by the injected api adapter`);return a}function Y(a,e){let r=new y(e.chain,e.api,e.crypto,a.claimBaseUrl),n=new P(e.chain,e.signer),s=new w(e.chain),d=new f(e.chain,e.api,e.crypto),{api:o}=e;return{config:a,deposit:t=>r.execute(t),retrieveClaimKey:t=>o.retrieveClaimKey(t),withdraw:t=>n.execute(t),refund:t=>s.execute(t),getDrop:(t,l)=>e.chain.getDrop(t,l),getDropByKey:t=>e.chain.getDropByKey(t),getDropKeyByClaimAddress:(t,l)=>e.chain.getDropKeyByClaimAddress(t,l),getClaimedRecipient:t=>e.chain.getClaimedRecipient({id:t}),getPendingDropsById:t=>e.chain.getPendingDropsById({id:t}),getPendingDropsByRecipient:t=>e.chain.getPendingDropsByRecipient({recipient:t}),getPendingDropsBySponsor:t=>e.chain.getPendingDropsBySponsor({sponsor:t}),withdrawUnmapped:t=>e.chain.withdrawUnmapped(t),withdrawMapped:t=>e.chain.withdrawMapped(t),batchWithdrawMapped:t=>e.chain.batchWithdrawMapped({count:t}),batchWithdrawMappedByKeys:t=>e.chain.batchWithdrawMappedByKeys({dropKeys:t}),refundByKey:t=>e.chain.refundByKey({dropKey:t}),getChangeNonce:t=>e.chain.getChangeNonce({id:t}),getPendingRecipientChange:t=>e.chain.getPendingRecipientChange({id:t}),requestRecipientChange:(t,l)=>e.chain.requestRecipientChange({id:t,newRecipient:l}),completeRecipientChange:t=>e.chain.completeRecipientChange(t),cancelRecipientChange:t=>e.chain.cancelRecipientChange({id:t}),resetRecipient:t=>e.chain.resetRecipient(t),listDrops:t=>p(o.listDrops,"listDrops").call(o,t),rejectDrops:t=>p(o.rejectDrops,"rejectDrops").call(o,{dropIds:t}),listEnvelopes:t=>p(o.listEnvelopes,"listEnvelopes").call(o,t),getLeaderboard:t=>p(o.getLeaderboard,"getLeaderboard").call(o,t),getMyLeaderboardEntry:t=>p(o.getMyLeaderboardEntry,"getMyLeaderboardEntry").call(o,t),listHistories:t=>p(o.listHistories,"listHistories").call(o,t),getXConnection:()=>p(o.getXConnection,"getXConnection").call(o),connectX:t=>p(o.connectX,"connectX").call(o,t),disconnectX:()=>p(o.disconnectX,"disconnectX").call(o),submitFeedback:t=>p(o.submitFeedback,"submitFeedback").call(o,t),setRevealYou:t=>p(o.setRevealYou,"setRevealYou").call(o,{revealYou:t}),requestRecipientChangeSignature:t=>p(o.requestRecipientChangeSignature,"requestRecipientChangeSignature").call(o,t),requestRecipientResetSignature:t=>p(o.requestRecipientResetSignature,"requestRecipientResetSignature").call(o,t),batchClaim:t=>d.execute(t),requestBatchClaimSignature:t=>p(o.requestBatchClaimSignature,"requestBatchClaimSignature").call(o,t)}}export{g as a,S as b,E as c,B as d,M as e,y as f,f as g,P as h,w as i,Y as j};