@nexus-cross/pop 1.4.0 → 1.4.1-beta.2

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
@@ -65,7 +65,11 @@ prefix matching the framework, Vite `VITE_` or Next.js `NEXT_PUBLIC_`:
65
65
  Base URLs must be `https` (or `http://localhost` for local dev) or construction throws.
66
66
  Dev and stage contract deployments are built in. Production contract addresses are not configured
67
67
  yet, so production must pass `contractAddress` explicitly. Claim base URL and X client id remain app options.
68
- The protocol fee is fixed at 5% (`ONE_POP_FEE_BPS = 500n`).
68
+ The protocol fee is fixed at 5% (`ONE_POP_FEE_BPS = 500n`); `listDrops`/`listHistories` also return the
69
+ server-reported `feeBps` and fall back to that constant.
70
+
71
+ Only the **dev** deployment runs the current build (`executor` argument + `anchorClaimDigest`). Stage still
72
+ runs the previous build, so `batchClaim` reverts there until stage is redeployed.
69
73
 
70
74
  ## 4. Wiring
71
75
 
@@ -171,7 +175,9 @@ Rules specific to this path:
171
175
 
172
176
  - **The recipient is the SIWE-authenticated address**, not a parameter you choose. Passing a
173
177
  different `recipient` fails with `SIGN_FAILED`. To claim to another wallet, do SIWE with it.
174
- - The anchor temporary wallet submits the transaction with the configured sponsored fee path.
178
+ - The recipient's own wallet submits the transaction. The enclave pins the signed `executor` to
179
+ `recipient`, and the contract compares `executor` against `msg.sender`; any other sender reverts
180
+ with `InvalidExecutor()`. The anchor claim key is used only to sign the anchor claim digest.
175
181
  - The anchor drop's `secret` and `claimKey` are required in addition to the validator signature.
176
182
  - A successful batch consumes the nonce and signature. Request a fresh signature for another call.
177
183
  - Each page gets a fresh nonce and validator signature; `maxCount` defaults to 30.
@@ -182,16 +188,17 @@ The on-chain contract (verified against deployed bytecode, CROSS testnet 612044)
182
188
 
183
189
  ```
184
190
  domain { name: 'ONEpop', version: '1', chainId, verifyingContract: <SafeDrop> }
185
- type ValidatorClaim(address recipient,string id,uint256 nonce,uint256 deadline)
191
+ type ValidatorClaim(address executor,address recipient,string id,uint256 nonce,uint256 deadline)
186
192
  nonce validatorNonceById(bytes32 keccak256(utf8(id))) // hashed key, NOT the raw string
193
+ anchor anchorClaimDigest(recipient, id, anchorDropKey) // NOT claimDigest — separate replay domain
187
194
  submit withdrawUnmappedBatchByKeys(recipient, id, anchorDropKey, claimSignature,
188
- secret, nonce, deadline, dropKeys, validatorSignature)
195
+ secret, nonce, deadline, executor, dropKeys, validatorSignature)
189
196
  errors ValidatorSigExpired() → deadline passed | InvalidValidatorNonce() → stale nonce
190
197
  ECDSAInvalidSignature() → signer is not validator()
191
198
  ```
192
199
 
193
- These functions are absent from the bundled `safedrop_abi.json` (a Foundry artifact that does not
194
- match the deployment); the SDK carries its own bytecode-verified ABI in `adapters/validatorAbi.ts`.
200
+ The bundled `safedrop_abi.json` now matches the deployment and carries these functions; the SDK
201
+ keeps a trimmed copy of the validator reads in `adapters/validatorAbi.ts`.
195
202
 
196
203
  ### Live notifications
197
204
 
@@ -236,7 +243,7 @@ The SDK does not wrap it — use `EventSource` directly. Delivery is best-effort
236
243
  | `getLeaderboard` | `GET /leaderboards?token=` | public |
237
244
  | `listHistories` | `GET /histories` | JWT |
238
245
  | `getXConnection` / `connectX` / `disconnectX` | `GET`/`POST`/`DELETE /x-connections` | JWT |
239
- | `batchClaim` | `POST /batch-claim-signature` + `withdrawUnmappedBatchByKeys` | JWT + X OAuth token + anchor claim key |
246
+ | `batchClaim` | `POST /batch-claim-signature` + `withdrawUnmappedBatchByKeys` | JWT + X OAuth token + anchor claim key + recipient wallet (submits the tx) |
240
247
  | `requestBatchClaimSignature` | `POST /batch-claim-signature` (low-level; prefer `batchClaim`) | JWT + X OAuth token |
241
248
 
242
249
  ## 8. Errors
package/README.md CHANGED
@@ -203,7 +203,7 @@ const { txHashes, recipient } = await safeDrop.batchClaim({
203
203
  |---|---|
204
204
  | secret | anchor drop의 secret/claim key가 필요하다 |
205
205
  | 수령 주소 | **SIWE 인증 주소로 고정**. 다른 주소를 넘기면 `SIGN_FAILED`(그 주소로 SIWE 재로그인해야 함) |
206
- | tx 전송자 | anchor 임시 claim 지갑 |
206
+ | tx 전송자 | **수령자 본인 지갑**. 컨트랙트가 `executor == msg.sender`를 강제하므로 다른 지갑이 보내면 `InvalidExecutor()` |
207
207
  | 서명 재사용 | 불가 — nonce는 성공한 batch 호출마다 소비됨 |
208
208
 
209
209
  `SIGN_FAILED`가 나면 백엔드 서명이 컨트랙트가 기대하는 값과 다르다(EIP-712 domain/type 불일치,
@@ -214,17 +214,17 @@ const { txHashes, recipient } = await safeDrop.batchClaim({
214
214
 
215
215
  ```
216
216
  domain { name: 'ONEpop', version: '1', chainId, verifyingContract: <SafeDrop> }
217
- type ValidatorClaim(address recipient,string id,uint256 nonce,uint256 deadline)
217
+ type ValidatorClaim(address executor,address recipient,string id,uint256 nonce,uint256 deadline)
218
218
  nonce validatorNonceById(bytes32) ← keccak256(utf8(id)). **원문 string 아님**
219
+ anchor anchorClaimDigest(recipient, id, anchorDropKey) ← claimDigest 아님(리플레이 도메인 분리)
219
220
  submit withdrawUnmappedBatchByKeys(recipient, id, anchorDropKey, claimSignature,
220
- secret, nonce, deadline, dropKeys, validatorSignature)
221
+ secret, nonce, deadline, executor, dropKeys, validatorSignature)
221
222
  검증 순서 deadline(ValidatorSigExpired) → nonce(InvalidValidatorNonce) → 서명(ECDSAInvalidSignature)
222
223
  ```
223
224
 
224
- **미검증 2건**: 컨트랙트가 `msg.sender == recipient`와 `recipient == claimedRecipientOf(id)`를
225
- 강제하는지는 확인하지 못했다(소스 미공개 + 서명 검증이 먼저라 블랙박스 구분 불가). pop이
226
- 조건을 클라이언트에서 선제 차단하지만 온체인 강제의 대체물은 아니다 —
227
- `docs/pop/02-frontend-dependencies.md#검증-한계-중요` 참조.
225
+ `executor`는 백엔드가 `recipient`로 고정해 서명하고 컨트랙트가 `msg.sender`와 비교한다.
226
+ 따라서 batch tx는 반드시 수령자 지갑에서 보내야 하며, 임시 claim 지갑으로 보내면
227
+ `InvalidExecutor()`로 revert한다.
228
228
 
229
229
  전체 현재 ABI는 `safedrop_abi.json`에서 직접 export된다.
230
230
  서명만 직접 받아 쓰려면 저수준 `safeDrop.requestBatchClaimSignature({ id, oauth, nonce, deadline })`.
@@ -171,6 +171,8 @@ interface DropInbox {
171
171
  readonly hasClaimedBefore: boolean;
172
172
  readonly mappedRecipient: Address | null;
173
173
  readonly pendingChangeTo: Address | null;
174
+ /** 수령 시 차감되는 ONEpop 수수료(bps). `totalAmount`/`items[].amount`는 차감 전 총액. */
175
+ readonly feeBps: number;
174
176
  }
175
177
  /** GET /envelopes — 카드 디자인. 공개 엔드포인트. */
176
178
  interface Envelope {
@@ -238,6 +240,8 @@ interface HistoryPage {
238
240
  readonly page: number;
239
241
  readonly pageSize: number;
240
242
  readonly total: number;
243
+ /** 수령 시 차감되는 ONEpop 수수료(bps). `items[].amount`는 차감 전 총액. */
244
+ readonly feeBps: number;
241
245
  }
242
246
  /**
243
247
  * POST /batch-claim-signature 결과 — EIP-712 ValidatorClaim 서명.
@@ -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-DfiY8vHq.js';
2
- import { S as Secret, a as SecretHash, H as Hex, A as Address, I as Id, m as SafeDropApiPort } from '../SafeDropApiPort-BLewfSaK.js';
1
+ import { C as CryptoPort, b as ClaimSignerPort, a as SafeDropChainPort, O as OnePopDrop, D as DropState, S as SafeDrop } from '../createSafeDrop-B3ZAB4RK.js';
2
+ import { S as Secret, a as SecretHash, H as Hex, A as Address, I as Id, m as SafeDropApiPort } from '../SafeDropApiPort-BaeGaaEY.js';
3
3
  import { PublicClient, WalletClient, Chain, Transport, Abi } from 'viem';
4
- import { H as HttpSafeDropApiAdapterOptions } from '../index-2sfHzZeD.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-2sfHzZeD.js';
4
+ import { H as HttpSafeDropApiAdapterOptions } from '../index-BEpSILvz.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-BEpSILvz.js';
6
6
  import '../XAuthPort-BNJePosj.js';
7
7
 
8
8
  /**
@@ -140,6 +140,7 @@ declare class ViemSafeDropChainAdapter implements SafeDropChainPort {
140
140
  secret: Secret;
141
141
  nonce: bigint;
142
142
  deadline: bigint;
143
+ executor: Address;
143
144
  dropKeys: readonly Hex[];
144
145
  validatorSignature: Hex;
145
146
  }): Promise<Hex>;
@@ -149,6 +150,7 @@ declare class ViemSafeDropChainAdapter implements SafeDropChainPort {
149
150
  }): Promise<bigint>;
150
151
  /** 온체인 EIP-712 다이제스트. 로컬 재조립 대신 이 값으로 백엔드 서명을 검증한다. */
151
152
  getValidatorClaimDigest(params: {
153
+ executor: Address;
152
154
  recipient: Address;
153
155
  id: Id;
154
156
  nonce: bigint;
@@ -213,6 +215,9 @@ declare const SAFEDROP_VALIDATOR_ABI: readonly [{
213
215
  readonly name: "validatorClaimDigest";
214
216
  readonly stateMutability: "view";
215
217
  readonly inputs: readonly [{
218
+ readonly name: "executor";
219
+ readonly type: "address";
220
+ }, {
216
221
  readonly name: "recipient";
217
222
  readonly type: "address";
218
223
  }, {
@@ -360,6 +365,23 @@ declare const ONEPOP_ABI: readonly [{
360
365
  readonly outputs: readonly [{
361
366
  readonly type: "bytes32";
362
367
  }];
368
+ }, {
369
+ readonly type: "function";
370
+ readonly name: "anchorClaimDigest";
371
+ readonly stateMutability: "view";
372
+ readonly inputs: readonly [{
373
+ readonly name: "recipient";
374
+ readonly type: "address";
375
+ }, {
376
+ readonly name: "id";
377
+ readonly type: "string";
378
+ }, {
379
+ readonly name: "dropKey";
380
+ readonly type: "bytes32";
381
+ }];
382
+ readonly outputs: readonly [{
383
+ readonly type: "bytes32";
384
+ }];
363
385
  }, {
364
386
  readonly type: "function";
365
387
  readonly name: "claimedRecipientOf";
@@ -543,6 +565,9 @@ declare const ONEPOP_ABI: readonly [{
543
565
  }, {
544
566
  readonly name: "deadline";
545
567
  readonly type: "uint256";
568
+ }, {
569
+ readonly name: "executor";
570
+ readonly type: "address";
546
571
  }, {
547
572
  readonly name: "dropKeys";
548
573
  readonly type: "bytes32[]";
@@ -669,7 +694,7 @@ declare const ONEPOP_ABI: readonly [{
669
694
  readonly outputs: readonly [];
670
695
  }, ...{
671
696
  type: "error";
672
- name: "AlreadyMapped" | "AmountOverflow" | "ChangeAlreadyRequested" | "ChangeInProgress" | "CountExceedsPending" | "DropAlreadyExists" | "DropNotFound" | "ECDSAInvalidSignature" | "EmptyId" | "IdMismatch" | "IdNotMapped" | "InvalidClaimSignature" | "InvalidShortString" | "InvalidValidatorNonce" | "InvalidValidatorSignature" | "NoPendingChange" | "NotRecipient" | "NotSponsor" | "PendingLimitExceeded" | "RecipientNotEmpty" | "ReentrancyGuardReentrantCall" | "SameRecipient" | "SecretMismatch" | "ValidatorSigExpired" | "ZeroAmount" | "ZeroClaimAddress" | "ZeroCount" | "ZeroRecipient" | "ZeroSbt" | "ZeroSecretHash" | "ZeroToken" | "ZeroValidator";
697
+ name: "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";
673
698
  inputs: readonly [];
674
699
  }[], {
675
700
  readonly type: "error";
@@ -1 +1 @@
1
- import{j as N}from"../chunk-GS7GCYQD.js";import{a as $,b as X,c as j,d as Y,e as z,g as J,h as P,i as Q,j as ee,k as D,l as te,m as ne,n as ie,o as ae,p as se}from"../chunk-I7UGWJHZ.js";import{a as o}from"../chunk-5DT3H2VX.js";import{bytesToHex as re,keccak256 as pe,recoverAddress as oe,toBytes as de}from"viem";var l=class{keccak256(e){return pe(de(e))}randomSecret(){let e=new Uint8Array(32);return ye().getRandomValues(e),re(e).slice(2)}recoverAddress(e){return oe({hash:e.digest,signature:e.signature})}};function ye(){let s=globalThis.crypto;if(!s||typeof s.getRandomValues!="function")throw new Error("Secure crypto RNG (globalThis.crypto.getRandomValues) is unavailable");return s}import{serializeSignature as ce,sign as ue}from"viem/accounts";var h=class{async signDigest(e){try{let t=await ue({hash:e.digest,privateKey:e.claimKey});return ce(t)}catch(t){throw new o("SIGN_FAILED","Failed to sign claim digest with temp key",{cause:t instanceof Error?t.message:String(t)})}}};import{BaseError as U,ContractFunctionRevertedError as K,createWalletClient as B,http as le,keccak256 as I,parseEventLogs as he,parseSignature as V,toBytes as f,toHex as _}from"viem";import{privateKeyToAccount as F,serializeSignature as k,sign as L}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}],me=["AlreadyMapped","AmountOverflow","ChangeAlreadyRequested","ChangeInProgress","CountExceedsPending","DropAlreadyExists","DropNotFound","ECDSAInvalidSignature","EmptyId","IdMismatch","IdNotMapped","InvalidClaimSignature","InvalidShortString","InvalidValidatorNonce","InvalidValidatorSignature","NoPendingChange","NotRecipient","NotSponsor","PendingLimitExceeded","RecipientNotEmpty","ReentrancyGuardReentrantCall","SameRecipient","SecretMismatch","ValidatorSigExpired","ZeroAmount","ZeroClaimAddress","ZeroCount","ZeroRecipient","ZeroSbt","ZeroSecretHash","ZeroToken","ZeroValidator"],R=[...me.map(s=>({type:"error",name:s,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"}]}],a=[{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:"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:"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 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"}]},...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:"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)},G=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??le(),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 o("INVALID_PARAM","invalid EIP-1559 gas configuration");this.depositWithPermit=t=>this.permitDeposit(t)}async getDropByKey(e){try{let[t,n,i,r,d,y]=await this.publicClient.readContract({address:this.address,abi:a,functionName:"drops",args:[e]});return t.toLowerCase()===be?null:{dropKey:e,sponsor:t,amount:n,claimAddress:i,recipient:r,secretHash:d,id:y}}catch(t){throw p("drops",t)}}async getDropKeyByClaimAddress(e,t){try{let n=await this.publicClient.readContract({address:this.address,abi:a,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:a,functionName:"pendingDropsByXid",args:[e.id]});return n.map((i,r)=>M(t[r],i))}catch(t){throw p("pendingDropsByXid",t)}}async getPendingDropsByRecipient(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:a,functionName:"pendingDropsByRecipient",args:[e.recipient]});return n.map((i,r)=>M(t[r],i))}catch(t){throw p("pendingDropsByRecipient",t)}}async getPendingDropsBySponsor(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:a,functionName:"pendingDropsOf",args:[e.sponsor]});return n.map((i,r)=>M(t[r],i))}catch(t){throw p("pendingDropsOf",t)}}async getDrop(e,t){let n=await this.getDropKeyByClaimAddress(e,t);if(!n)return null;let[i,r]=await Promise.all([this.getDropByKey(n),this.escrowToken()]);return i&&r?{...i,token:r}:null}async escrowToken(){try{return await this.publicClient.readContract({address:this.address,abi:C,functionName:"token"})}catch{throw new o("CHAIN_ERROR","token() failed")}}async getClaimDigest(e){try{return await this.publicClient.readContract({address:this.address,abi:a,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,r,d]=await Promise.all([this.publicClient.readContract({address:this.address,abi:C,functionName:"token"}),this.publicClient.readContract({address:n,abi:b,functionName:"nonces",args:[t.address]}),this.permitDomain(n)]);if(i.toLowerCase()!==n.toLowerCase())throw new o("INVALID_TOKEN","token does not match the escrow token",{expected:i,received:e.token});let y=BigInt(Math.floor(Date.now()/1e3))+G,c=await this.walletClient.signTypedData({account:t,domain:{...d,chainId:this.chain.id,verifyingContract:n},types:H,primaryType:"Permit",message:{owner:t.address,spender:this.address,value:e.amount,nonce:r,deadline:y}}),{r:T,s:x,v:A,yParity:v}=V(c),u=await this.walletClient.writeContract({address:this.address,abi:C,functionName:"deposit",args:[e.claimAddress,e.amount,e.id,e.secretHash,y,Number(A??BigInt(v+27)),T,x],account:t,chain:this.chain,...this.transactionOverrides()});await e.onSubmitted?.(u);let m=await this.confirm("depositWithPermit",u);return{txHash:u,dropKey:this.depositedDropKey(m.logs,t.address,e.amount,e.id,u)}}catch(t){throw p("depositWithPermit",t)}}async depositMapped(e){try{let t=this.requireAccount(),n=e.token,[i,r,d]=await Promise.all([this.publicClient.readContract({address:this.address,abi:a,functionName:"token"}),this.publicClient.readContract({address:n,abi:b,functionName:"nonces",args:[t.address]}),this.permitDomain(n)]);if(i.toLowerCase()!==n.toLowerCase())throw new o("INVALID_TOKEN","token does not match the escrow token",{expected:i,received:e.token});let y=BigInt(Math.floor(Date.now()/1e3))+G,c=await this.walletClient.signTypedData({account:t,domain:{...d,chainId:this.chain.id,verifyingContract:n},types:H,primaryType:"Permit",message:{owner:t.address,spender:this.address,value:e.amount,nonce:r,deadline:y}}),{r:T,s:x,v:A,yParity:v}=V(c),u=[e.amount,e.id,y,Number(A??BigInt(v+27)),T,x];await this.publicClient.simulateContract({address:this.address,abi:a,functionName:"depositMapped",args:u,account:t});let m=await this.walletClient.writeContract({address:this.address,abi:a,functionName:"depositMapped",args:u,account:t,chain:this.chain,...this.transactionOverrides()});await e.onSubmitted?.(m);let Z=await this.confirm("depositMapped",m);return{txHash:m,dropKey:this.depositedDropKey(Z.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=F(e.claimKey),n=await this.publicClient.readContract({address:this.address,abi:a,functionName:"claimDigest",args:[e.recipient,e.id,e.dropKey]}),i=e.signature??k(await L({hash:n,privateKey:e.claimKey})),d=await B({account:t,chain:this.chain,transport:this.transport}).writeContract({address:this.address,abi:a,functionName:"withdrawUnmapped",args:[e.recipient,e.id,e.dropKey,i,_(f(e.secret))],...this.transactionOverrides()});return await e.onSubmitted?.(d),await this.confirm("withdrawUnmapped",d),d}catch(t){throw W("withdrawUnmapped",t)}}async withdrawMapped(e){let t=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:a,functionName:"withdrawMapped",args:[e.dropKey],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:a,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 o("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:a,functionName:"batchWithdrawMapped",args:[BigInt(e.count)],account:n});let i=await this.walletClient.writeContract({address:this.address,abi:a,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 o("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:a,functionName:"batchWithdrawMapped",args:i,account:n});let r=await this.walletClient.writeContract({address:this.address,abi:a,functionName:"batchWithdrawMapped",args:i,account:n,chain:this.chain,...t});return await this.confirm("batchWithdrawMapped",r),r}catch(r){throw p("batchWithdrawMapped",r)}}async withdrawUnmappedBatchByKeys(e){let t=e.dropKeys.filter(i=>i.toLowerCase()!==e.anchorDropKey.toLowerCase()),n=this.batchTransactionOverrides(t.length+1);try{let i=F(e.claimKey),r=await this.publicClient.readContract({address:this.address,abi:a,functionName:"claimDigest",args:[e.recipient,e.id,e.anchorDropKey]}),d=k(await L({hash:r,privateKey:e.claimKey})),c=await B({account:i,chain:this.chain,transport:this.transport}).writeContract({address:this.address,abi:a,functionName:"withdrawUnmappedBatchByKeys",args:[e.recipient,e.id,e.anchorDropKey,d,_(f(e.secret)),e.nonce,e.deadline,t,e.validatorSignature],...n});return await this.confirm("withdrawUnmappedBatchByKeys",c),c}catch(i){throw W("withdrawUnmappedBatchByKeys",i)}}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.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:a,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:a,functionName:"refund",args:[e.dropKey],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:a,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:a,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:a,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:a,functionName:"resetRecipient",args:[e.id,e.nonce,e.deadline,e.signature],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:a,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:a,functionName:e,args:t,account:n});let i=await this.walletClient.writeContract({address:this.address,abi:a,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 o("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 o("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,r){let d=he({abi:a,eventName:"Deposited",logs:[...e]}).find(({address:y,args:c})=>y.toLowerCase()===this.address.toLowerCase()&&c.sponsor.toLowerCase()===t.toLowerCase()&&c.amount===n&&c.id===i);if(!d)throw new o("CHAIN_ERROR","deposit receipt omitted the Deposited event",{txHash:r});return d.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),r=i?`SafeDrop.${e} reverted: ${i}`:`transaction reverted: ${t}`;throw new o("CHAIN_ERROR",r,{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 o("CHAIN_ERROR","walletClient has no account (connect a wallet first)");return e}};function M(s,e){return{dropKey:s,sponsor:e.sponsor,amount:e.amount,claimAddress:e.claimAddr,recipient:e.recipient,secretHash:e.secretHash,id:e.id}}function p(s,e){if(e instanceof o)return e;let t=O(e),n=e instanceof Error?e.message:String(e),i=t?`SafeDrop.${s} reverted: ${t}`:`SafeDrop.${s} failed`;return new o("CHAIN_ERROR",i,{cause:n,revertName:t})}function W(s,e){if(e instanceof o)return e;let t=O(e),n=e instanceof U?e.walk(d=>{let y=d;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 r=t?`SafeDrop.${s} reverted: ${t}`:`SafeDrop.${s} failed`;return new o("CHAIN_ERROR",r,i)}function O(s){if(!(s instanceof U))return;let e=s.walk(t=>t instanceof K);if(e instanceof K)return e.data?.errorName??e.reason??void 0}var q=[{type:"constructor",inputs:[{name:"token_",type:"address",internalType:"contract IERC20"},{name:"validator_",type:"address",internalType:"address"},{name:"sbt_",type:"address",internalType:"contract ISoulboundToken"}],stateMutability:"nonpayable"},{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:"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:"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:"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:"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:"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:"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:"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:"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:"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:"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:"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:"ValidatorSigExpired",inputs:[]},{type:"error",name:"ZeroAmount",inputs:[]},{type:"error",name:"ZeroClaimAddress",inputs:[]},{type:"error",name:"ZeroCount",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 Ce=q;function Te(s){let e=s.apiPort??new D(s.api),t=new w({address:s.contractAddress??P().onePop,publicClient:s.publicClient,walletClient:s.walletClient,chain:s.chain,transport:s.transport,withdrawFees:s.withdrawFees,transactionFees:s.transactionFees});return N({claimBaseUrl:s.claimBaseUrl},{api:e,chain:t,signer:new h,crypto:new l})}export{te as CrossAuthClient,Y as DEFAULT_POP_API_PATHS,D as HttpSafeDropApiAdapter,ae as HttpXAuthAdapter,a as ONEPOP_ABI,X as ONE_POP_BPS_DENOMINATOR,j as ONE_POP_DEPLOYMENTS,$ as ONE_POP_FEE_BPS,Ce as SAFEDROP_ABI,g as SAFEDROP_VALIDATOR_ABI,h as ViemClaimSignerAdapter,l as ViemCryptoAdapter,w as ViemSafeDropChainAdapter,se as XAuthClient,Te as createSafeDropClient,ne as generatePkce,ie as generateState,ee as getCrossAuthBaseUrl,Q as getOnePopApiBaseUrl,P as getOnePopContracts,J as getOnePopDeployment,z as getPopEnvironment};
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-IFWZ2Z32.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,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-2sfHzZeD.js';
2
- import '../SafeDropApiPort-BLewfSaK.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-BEpSILvz.js';
2
+ import '../SafeDropApiPort-BaeGaaEY.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-I7UGWJHZ.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-IFWZ2Z32.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};
@@ -0,0 +1 @@
1
+ import{a as o}from"./chunk-5DT3H2VX.js";var h=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:"0x4c4599fFa1D83bB9689d9a0C557fF2EB35443949",permitErc20:"0xFaDAB54449262178aE0562F5D8416bBeF4659714",nft:"0x0535fce7113cf48f21C32472bBA929F8F31ab05c",nftMinter:"0x4c4599fFa1D83bB9689d9a0C557fF2EB35443949",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"},H="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 X(r)}function X(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 $(){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")??$().apiBaseUrl;return I(e),e}function w(){let e=(f("VITE_CROSS_AUTH_URL")??u("NEXT_PUBLIC_CROSS_AUTH_URL")??H).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(h)}}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)}))}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(h)}}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:N(e)});return{...v(t,e),newRecipient:s(t?.new_recipient)}}async requestRecipientResetSignature(e){let t=await this.request(this.paths.recipientResetSignature,{method:"POST",payload:N(e)});return v(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:g(t?.nonce)?d(t?.nonce,"batchClaim.nonce"):e.nonce,deadline:g(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 g(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),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),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),displayName:s(e.display_name),profileImageUrl:s(e.profile_image_url)}}function K(r){return{...U(r),address:c(r?.address)}}function N(r){return{id:r.id,oauth_token:r.oauth.accessToken,nonce:r.nonce.toString(),deadline:r.deadline.toString()}}function v(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:g(r?.nonce)?d(r?.nonce,"signature.nonce"):e.nonce,deadline:g(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:F}=await this.opts.port.getHandle(y.accessToken);return this.opts.storage.remove(_),this.opts.storage.remove(P),{oauth:{provider:"x",accessToken:y.accessToken},handle:F}}};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{h as a,Q as b,E as c,b as d,R as e,X as 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};
@@ -0,0 +1 @@
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};
@@ -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-BLewfSaK.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-BaeGaaEY.js';
2
2
 
3
3
  /**
4
4
  * 순수 계산이 아니라 외부 구현(해시 라이브러리/CSPRNG)이 필요한 암호 연산.
@@ -115,6 +115,8 @@ interface SafeDropChainPort {
115
115
  secret: Secret;
116
116
  nonce: bigint;
117
117
  deadline: bigint;
118
+ /** 컨트랙트가 msg.sender와 대조하는 주소. 백엔드가 recipient로 고정해 서명한다. */
119
+ executor: Address;
118
120
  dropKeys: readonly Hex[];
119
121
  validatorSignature: Hex;
120
122
  }): Promise<Hex>;
@@ -151,10 +153,11 @@ interface SafeDropChainPort {
151
153
  id: Id;
152
154
  }): Promise<bigint>;
153
155
  /**
154
- * validatorClaimDigest(recipient, id, nonce, deadline) — 온체인 EIP-712 다이제스트.
156
+ * validatorClaimDigest(executor, recipient, id, nonce, deadline) — 온체인 EIP-712 다이제스트.
155
157
  * 로컬 재조립 대신 이 값을 읽어 백엔드 서명을 검증한다.
156
158
  */
157
159
  getValidatorClaimDigest?(params: {
160
+ executor: Address;
158
161
  recipient: Address;
159
162
  id: Id;
160
163
  nonce: bigint;
@@ -1,4 +1,4 @@
1
- import { m as SafeDropApiPort, A as Address, v 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-BLewfSaK.js';
1
+ import { m as SafeDropApiPort, A as Address, v 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-BaeGaaEY.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-BLewfSaK.js';
2
- export { l as BatchClaimSignature, e as DropInbox, n as DropSender, E as Envelope, H as Hex, o as HistoryEntry, h as HistoryPage, p as HistoryParty, q as HistoryReceiverParty, g as HistoryStatus, f as HistoryType, I as Id, r as LeaderboardEntry, L as LeaderboardPage, s as MappedDepositResult, M as MyLeaderboardEntry, O as OAuthProof, P as PendingDrop, i as RecipientChangeSignature, j as RecipientSignature, t as SafeDropError, u as SafeDropErrorCode, a as SecretHash, v as SocialIdentifier, w as SocialProvider, U as UnmappedDepositResult, X as XConnection } from './SafeDropApiPort-BLewfSaK.js';
3
- import { a as SafeDropChainPort, C as CryptoPort, b as ClaimSignerPort } from './createSafeDrop-DfiY8vHq.js';
4
- export { D as DropState, O as OnePopDrop, S as SafeDrop, c as SafeDropConfig, d as SafeDropDeps, e as createSafeDrop } from './createSafeDrop-DfiY8vHq.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-BaeGaaEY.js';
2
+ export { l as BatchClaimSignature, e as DropInbox, n as DropSender, E as Envelope, H as Hex, o as HistoryEntry, h as HistoryPage, p as HistoryParty, q as HistoryReceiverParty, g as HistoryStatus, f as HistoryType, I as Id, r as LeaderboardEntry, L as LeaderboardPage, s as MappedDepositResult, M as MyLeaderboardEntry, O as OAuthProof, P as PendingDrop, i as RecipientChangeSignature, j as RecipientSignature, t as SafeDropError, u as SafeDropErrorCode, a as SecretHash, v as SocialIdentifier, w as SocialProvider, U as UnmappedDepositResult, X as XConnection } from './SafeDropApiPort-BaeGaaEY.js';
3
+ import { a as SafeDropChainPort, C as CryptoPort, b as ClaimSignerPort } from './createSafeDrop-B3ZAB4RK.js';
4
+ export { D as DropState, O as OnePopDrop, S as SafeDrop, c as SafeDropConfig, d as SafeDropDeps, e as createSafeDrop } from './createSafeDrop-B3ZAB4RK.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-GS7GCYQD.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 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,7 +1,7 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { S as SafeDrop } from '../createSafeDrop-DfiY8vHq.js';
4
- import '../SafeDropApiPort-BLewfSaK.js';
3
+ import { S as SafeDrop } from '../createSafeDrop-B3ZAB4RK.js';
4
+ import '../SafeDropApiPort-BaeGaaEY.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.0",
3
+ "version": "1.4.1-beta.2",
4
4
  "description": "pop — framework-agnostic core + React adapter.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -17,7 +17,7 @@
17
17
  "BearerAuth": []
18
18
  }
19
19
  ],
20
- "description": "Returns an EIP-712 ValidatorClaim signature bound to the SIWE-authenticated address as recipient, for withdrawUnmappedBatch / withdrawUnmappedBatchByKeys. The caller must prove ownership of id via an X OAuth token in the body; recipient always comes from the bearer token, never the body. id must be canonical (lowercase, no \"@\") — non-canonical ids are rejected with 400 (spec §5.4). nonce/deadline are supplied by the caller (read from validatorNonceById on-chain). NOTE (ONEpop): the nonce is consumed per successful call — one signature authorizes exactly one on-chain call; request a new signature (with the advanced nonce) for each subsequent batch.",
20
+ "description": "Returns an EIP-712 ValidatorClaim signature bound to the SIWE-authenticated address as recipient, for withdrawUnmappedBatch / withdrawUnmappedBatchByKeys. The caller must prove ownership of id via an X OAuth token in the body; recipient always comes from the bearer token, never the body. id must be canonical (lowercase, no \"@\") — non-canonical ids are rejected with 400 (spec §5.4). nonce/deadline are supplied by the caller (read from validatorNonceById on-chain). NOTE (ONEpop): the nonce is consumed per successful call — one signature authorizes exactly one on-chain call; request a new signature (with the advanced nonce) for each subsequent batch. NOTE (executor): the enclave signs this ValidatorClaim with the on-chain `executor` argument pinned to `recipient` — the withdrawUnmappedBatch / withdrawUnmappedBatchByKeys transaction MUST be submitted from the recipient's own wallet, or the contract reverts with InvalidExecutor.",
21
21
  "consumes": [
22
22
  "application/json"
23
23
  ],
@@ -508,7 +508,7 @@
508
508
  },
509
509
  "/leaderboards": {
510
510
  "get": {
511
- "description": "Returns identifiers ordered by pending (claimable) amount of the given ERC20 token, descending (identifier ascending as tiebreak), maintained from Deposited/Withdrawn/Refunded events. Paged via page/page_size; (page-1)*page_size must stay below 10000. identifier switches to exact-match search mode: one item (or none) with page/page_size fixed to 1, page and page_size ignored. Identifiers with zero pending balance are excluded from the board and from search results (negative balances — a data-corruption signal — stay visible). rank is the current 1-based position; previous_rank is the position in the latest periodic snapshot (null = new entrant or no snapshot yet). balance and last_deposit_amount are wei as decimal strings. profile_image_url is the identifier's active X profile image (empty string when the identifier has no active X connection). Public endpoint.",
511
+ "description": "Returns identifiers ordered by pending (claimable) amount of the given ERC20 token, descending (identifier ascending as tiebreak), maintained from Deposited/Withdrawn/Refunded events. Paged via page/page_size; (page-1)*page_size must stay below 10000. identifier switches to exact-match search mode: one item (or none) with page/page_size fixed to 1, page and page_size ignored. Identifiers with zero pending balance are excluded from the board and from search results (negative balances — a data-corruption signal — stay visible). rank is the current 1-based position; previous_rank is the position in the latest periodic snapshot (null = new entrant or no snapshot yet). balance and last_deposit_amount are wei as decimal strings. profile_image_url is the identifier's active X profile image (empty string when the identifier has no active X connection). Balances are reject-adjusted: pending amounts rejected by the handle's current owner are subtracted. Public endpoint.",
512
512
  "produces": [
513
513
  "application/json"
514
514
  ],
@@ -1330,6 +1330,11 @@
1330
1330
  "type": "integer",
1331
1331
  "example": 3
1332
1332
  },
1333
+ "fee_bps": {
1334
+ "description": "FeeBps is ONEpop's withdrawal fee in basis points (500 = 5%).\nTotalAmount above is the pending (not yet claimed) sum and is\nunaffected by this — the fee only applies once a drop is\nclaimed, at which point the recipient receives amount *\n(10000-fee_bps)/10000.",
1335
+ "type": "integer",
1336
+ "example": 500
1337
+ },
1333
1338
  "has_claimed_before": {
1334
1339
  "description": "HasClaimedBefore gates the batch-claim CTA. Derived from the\nidentifier_recipients mapping row (row exists == a first batch\nclaim recorded the mapping on-chain).",
1335
1340
  "type": "boolean",
@@ -1507,6 +1512,11 @@
1507
1512
  "types.HistoryResp": {
1508
1513
  "type": "object",
1509
1514
  "properties": {
1515
+ "fee_bps": {
1516
+ "description": "FeeBps is ONEpop's withdrawal fee in basis points (500 = 5%).\namount above stays gross; multiply by (10000-fee_bps)/10000 for\nthe net amount a claimed drop's recipient actually received.",
1517
+ "type": "integer",
1518
+ "example": 500
1519
+ },
1510
1520
  "items": {
1511
1521
  "type": "array",
1512
1522
  "items": {
@@ -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({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,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};
@@ -1 +0,0 @@
1
- import{a as o}from"./chunk-5DT3H2VX.js";var Z=BigInt(500),Q=BigInt(1e4),y={dev:{apiBaseUrl:"https://dev-one-pop-api.onechain.nexus/api",contracts:{onePop:"0xfBadB337e634757ca8F8EEB7682acF06bA297d85",permitErc20:"0xFaDAB54449262178aE0562F5D8416bBeF4659714",nft:"0x11ce973082c7B90aB2Fc789949CC04e1F85397ff",nftMinter:"0xfBadB337e634757ca8F8EEB7682acF06bA297d85",validator:"0xF30d8e0544f0b92A6987522f4F696D3915B579b4",feeRecipient:"0xF30d8e0544f0b92A6987522f4F696D3915B579b4"}},stage:{apiBaseUrl:"https://stg-one-pop-api.onechain.nexus/api",contracts:{onePop:"0x4c4599fFa1D83bB9689d9a0C557fF2EB35443949",permitErc20:"0xFaDAB54449262178aE0562F5D8416bBeF4659714",nft:"0x0535fce7113cf48f21C32472bBA929F8F31ab05c",nftMinter:"0x4c4599fFa1D83bB9689d9a0C557fF2EB35443949",validator:"0xa953af3742345dFC2BdcA30cBa79D8313b0a3B61",feeRecipient:"0xa953af3742345dFC2BdcA30cBa79D8313b0a3B61"}},production:{apiBaseUrl:"https://one-pop-api.onechain.nexus/api"}},E={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"},F="https://dev-cross-auth.crosstoken.io";function h(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 b(){let r=h("VITE_ONE_POP_ENVIRONMENT")??u("NEXT_PUBLIC_ONE_POP_ENVIRONMENT")??u("ONE_POP_ENVIRONMENT");return H(r)}function H(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 X(){return y[b()]}function ee(){return $(b())}function $(r){let e=y[r].contracts;if(!e)throw new Error(`[pop] Contract addresses are not configured for ${r}`);return e}function R(){let e=h("VITE_ONE_POP_API_BASE_URL")??u("NEXT_PUBLIC_ONE_POP_API_BASE_URL")??X().apiBaseUrl;return w(e),e}function A(){let e=(h("VITE_CROSS_AUTH_URL")??u("NEXT_PUBLIC_CROSS_AUTH_URL")??F).replace(/\/+$/,"");return w(e),e}function w(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 q={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,I=class{constructor(e={}){this.baseUrl=(e.baseUrl??R()).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={...E,...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(j),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)}}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)}))}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(S),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{...S(t??{}),rank:N(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:k(n.sender),receiver:z(n.receiver)})),page:t?.page??1,pageSize:t?.page_size??0,total:t?.total??0}}async getXConnection(){let e=await this.request(this.paths.xConnections,{method:"GET",auth:!0,notFoundAsNull:!0});return e?O(e):null}async connectX(e){let t=await this.request(this.paths.xConnections,{method:"POST",auth:!0,payload:{oauth_token:e.oauth.accessToken}});return O(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:T(e)});return{...v(t,e),newRecipient:s(t?.new_recipient)}}async requestRecipientResetSignature(e){let t=await this.request(this.paths.recipientResetSignature,{method:"POST",payload:T(e)});return v(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:g(t?.nonce)?d(t?.nonce,"batchClaim.nonce"):e.nonce,deadline:g(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}${V(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?q[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 V(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 g(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 j(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 O(r){return{xUserId:s(r.x_user_id),handle:s(r.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 S(r){return{identifier:s(r.identifier),balance:d(r.balance,"leaderboard.balance"),lastDepositAmount:d(r.last_deposit_amount,"leaderboard.last_deposit_amount"),rank:Number(r.rank??0),previousRank:N(r.previous_rank),profileImageUrl:s(r.profile_image_url)}}function N(r){return typeof r=="number"?r:null}function k(r){let e=r??{};return{address:s(e.address),handle:s(e.handle),displayName:s(e.display_name),profileImageUrl:s(e.profile_image_url)}}function z(r){return{...k(r),address:c(r?.address)}}function T(r){return{id:r.id,oauth_token:r.oauth.accessToken,nonce:r.nonce.toString(),deadline:r.deadline.toString()}}function v(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:g(r?.nonce)?d(r?.nonce,"signature.nonce"):e.nonce,deadline:g(r?.deadline)?d(r?.deadline,"signature.deadline"):e.deadline,signature:t}}var U=class{constructor(e={}){this.baseUrl=(e.baseUrl??A()).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 C(){let r=f(x(32)),e=await K().digest("SHA-256",W(r)),t=f(new Uint8Array(e));return{verifier:r,challenge:t,method:"S256"}}function D(){return f(x(16))}function x(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 K(){let r=globalThis.crypto?.subtle;if(!r)throw new Error("crypto.subtle unavailable (needs https/secure context)");return r}function W(r){return new TextEncoder().encode(r)}function f(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 L=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 m="pop.xauth.verifier",_="pop.xauth.state",G="https://x.com/i/oauth2/authorize",J="tweet.read users.read offline.access",B=class{constructor(e){this.opts={clientId:e.clientId,redirectUri:e.redirectUri,scope:e.scope??J,authorizeUrl:e.authorizeUrl??G,port:e.port,storage:e.storage??Y()}}async start(){let e=await C(),t=D();this.opts.storage.set(m,e.verifier),this.opts.storage.set(_,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(_);if(!i||!a||i!==a)throw new o("API_ERROR","X callback: state mismatch (possible CSRF)");let p=this.opts.storage.get(m);if(!p)throw new o("API_ERROR","X callback: missing PKCE verifier (expired session?)");let P=await this.opts.port.exchangeCode({clientId:this.opts.clientId,redirectUri:this.opts.redirectUri,code:n,codeVerifier:p}),{handle:M}=await this.opts.port.getHandle(P.accessToken);return this.opts.storage.remove(m),this.opts.storage.remove(_),{oauth:{provider:"x",accessToken:P.accessToken},handle:M}}};function Y(){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{Z as a,Q as b,y as c,E as d,b as e,H as f,X as g,ee as h,R as i,A as j,I as k,U as l,C as m,D as n,L as o,B as p};