@nexus-cross/pop 1.4.0-beta.2 → 1.4.0-beta.3
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 +5 -5
- package/README.md +7 -4
- package/dist/adapters/index.d.ts +24 -6
- package/dist/adapters/index.js +1 -1
- package/dist/chunk-E3ZMMRDI.js +1 -0
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-SE2HF5WH.js +0 -1
package/AGENTS.md
CHANGED
|
@@ -39,7 +39,7 @@ pnpm add @nexus-cross/pop viem # + react if using ./react
|
|
|
39
39
|
|
|
40
40
|
| What | Where it goes | Notes |
|
|
41
41
|
|---|---|---|
|
|
42
|
-
| SafeDrop contract address |
|
|
42
|
+
| SafeDrop contract address | selected by `ONE_POP_ENVIRONMENT` | explicit `contractAddress` remains an override |
|
|
43
43
|
| viem `publicClient` / `walletClient` / `chain` | same | walletClient = connected sponsor wallet |
|
|
44
44
|
| claim page base URL | `createSafeDropClient({ claimBaseUrl })` | the route that handles the claim link |
|
|
45
45
|
| SIWE JWT provider | `createSafeDropClient({ api: { getJwt } })` | **required** for deposit and all authed reads |
|
|
@@ -51,13 +51,14 @@ prefix matching the framework, Vite `VITE_` or Next.js `NEXT_PUBLIC_`:
|
|
|
51
51
|
|
|
52
52
|
| Variable | Purpose |
|
|
53
53
|
|---|---|
|
|
54
|
-
| `VITE_ONE_POP_ENVIRONMENT` / `NEXT_PUBLIC_ONE_POP_ENVIRONMENT` / `ONE_POP_ENVIRONMENT` | `dev` \| `stage` \| `production` (default `production`) → picks the
|
|
54
|
+
| `VITE_ONE_POP_ENVIRONMENT` / `NEXT_PUBLIC_ONE_POP_ENVIRONMENT` / `ONE_POP_ENVIRONMENT` | `dev` \| `stage` \| `production` (default `production`) → picks the API and contract deployment together |
|
|
55
55
|
| `VITE_ONE_POP_API_BASE_URL` / `NEXT_PUBLIC_ONE_POP_API_BASE_URL` | override the One Pop API base URL |
|
|
56
56
|
| `VITE_CROSS_AUTH_URL` / `NEXT_PUBLIC_CROSS_AUTH_URL` | override the cross-auth (SIWE) base URL |
|
|
57
57
|
|
|
58
58
|
Base URLs must be `https` (or `http://localhost` for local dev) or construction throws.
|
|
59
|
-
|
|
60
|
-
|
|
59
|
+
Dev and stage contract deployments are built in. Production contract addresses are not configured
|
|
60
|
+
yet, so production must pass `contractAddress` explicitly. Claim base URL and X client id remain app options.
|
|
61
|
+
The protocol fee is fixed at 5% (`ONE_POP_FEE_BPS = 500n`).
|
|
61
62
|
|
|
62
63
|
## 4. Wiring
|
|
63
64
|
|
|
@@ -75,7 +76,6 @@ const signature = await walletClient.signMessage({ account: address, message });
|
|
|
75
76
|
const { token } = await auth.siweToken(address, signature);
|
|
76
77
|
|
|
77
78
|
const safeDrop = createSafeDropClient({
|
|
78
|
-
contractAddress: SAFEDROP_ADDRESS,
|
|
79
79
|
publicClient,
|
|
80
80
|
walletClient,
|
|
81
81
|
chain,
|
package/README.md
CHANGED
|
@@ -41,12 +41,11 @@ const publicClient = createPublicClient({ chain, transport: http() });
|
|
|
41
41
|
const walletClient = createWalletClient({ chain, transport: custom(window.ethereum) }); // 연결된 지갑
|
|
42
42
|
|
|
43
43
|
const safeDrop = createSafeDropClient({
|
|
44
|
-
contractAddress: '0x…SafeDrop',
|
|
45
44
|
publicClient,
|
|
46
45
|
walletClient,
|
|
47
46
|
chain,
|
|
48
47
|
claimBaseUrl: 'https://one-pop.example/claim',
|
|
49
|
-
//
|
|
48
|
+
// API와 ONEpop 주소는 VITE_/NEXT_PUBLIC_ONE_POP_ENVIRONMENT로 함께 결정
|
|
50
49
|
api: { getJwt: async () => siweJwt }, // deposit(createClaimWallet)에 SIWE JWT 필요
|
|
51
50
|
});
|
|
52
51
|
```
|
|
@@ -243,7 +242,11 @@ Provider는 client를 context로 넣기만 한다 — 연결 로직은 없다.
|
|
|
243
242
|
| `ONE_POP_ENVIRONMENT` | 위 environment의 서버 전용(SSR, 접두사 없음) 변형 |
|
|
244
243
|
| `VITE_CROSS_AUTH_URL` / `NEXT_PUBLIC_CROSS_AUTH_URL` | cross-auth base URL override |
|
|
245
244
|
|
|
246
|
-
|
|
245
|
+
environment 하나로 one-pop-api와 ONEpop/Permit ERC20/NFT/Validator/FeeRecipient 주소를 함께 고른다.
|
|
246
|
+
dev/stage 주소는 패키지에 내장되어 있으며 production contract는 아직 미설정이므로 production에서는
|
|
247
|
+
`contractAddress`를 직접 넘겨야 한다. API override 미지정 시 environment의 기본 URL을 사용한다.
|
|
248
|
+
base URL은 https(또는 `http://localhost`)만 허용한다. 프로토콜 수수료는 5% 고정이며
|
|
249
|
+
`ONE_POP_FEE_BPS`(`500n`)와 `ONE_POP_BPS_DENOMINATOR`(`10_000n`)를 제공한다.
|
|
247
250
|
|
|
248
251
|
## 에러
|
|
249
252
|
|
|
@@ -277,7 +280,7 @@ override 미지정 시 environment로 기본 URL을 고른다. base URL은 https
|
|
|
277
280
|
|
|
278
281
|
| 옵션 | 타입 | 기본 | 설명 |
|
|
279
282
|
|---|---|---|---|
|
|
280
|
-
| `contractAddress` | `Address` |
|
|
283
|
+
| `contractAddress` | `Address` | environment의 ONEpop 주소 | 테스트/별도 배포 시 override. production 주소 미설정 상태에서는 필수 |
|
|
281
284
|
| `publicClient` | viem `PublicClient` | — (필수) | 읽기·getDrop·digest |
|
|
282
285
|
| `walletClient` | viem `WalletClient` | — (필수) | deposit/refund 서명(연결 지갑) |
|
|
283
286
|
| `chain` | viem `Chain` | — (필수) | 대상 체인 |
|
package/dist/adapters/index.d.ts
CHANGED
|
@@ -192,9 +192,8 @@ declare class ViemSafeDropChainAdapter implements SafeDropChainPort {
|
|
|
192
192
|
}
|
|
193
193
|
|
|
194
194
|
/**
|
|
195
|
-
*
|
|
196
|
-
*
|
|
197
|
-
* 환경 식별 → 기본 URL, https 검증)을 따른다.
|
|
195
|
+
* ONEpop 배포 설정 — API와 컨트랙트 주소를 동일한 환경 식별자로 선택한다.
|
|
196
|
+
* Vite import.meta.env + Next literal process.env 컨벤션을 따른다.
|
|
198
197
|
*
|
|
199
198
|
* 우선순위 (override):
|
|
200
199
|
* 1) `VITE_ONE_POP_API_BASE_URL` (Vite 빌드)
|
|
@@ -205,6 +204,22 @@ declare class ViemSafeDropChainAdapter implements SafeDropChainPort {
|
|
|
205
204
|
* 스펙: packages/pop/src/infrastructure/openapi.json (basePath `/api`)
|
|
206
205
|
*/
|
|
207
206
|
type PopEnvironment = 'dev' | 'stage' | 'production';
|
|
207
|
+
interface PopContracts {
|
|
208
|
+
onePop: `0x${string}`;
|
|
209
|
+
permitErc20: `0x${string}`;
|
|
210
|
+
nft: `0x${string}`;
|
|
211
|
+
nftMinter: `0x${string}`;
|
|
212
|
+
validator: `0x${string}`;
|
|
213
|
+
feeRecipient: `0x${string}`;
|
|
214
|
+
}
|
|
215
|
+
interface PopDeployment {
|
|
216
|
+
apiBaseUrl: string;
|
|
217
|
+
contracts?: PopContracts;
|
|
218
|
+
}
|
|
219
|
+
/** ONEpop protocol fee: 5% (500 / 10,000 basis points). */
|
|
220
|
+
declare const ONE_POP_FEE_BPS: bigint;
|
|
221
|
+
declare const ONE_POP_BPS_DENOMINATOR: bigint;
|
|
222
|
+
declare const ONE_POP_DEPLOYMENTS: Readonly<Record<PopEnvironment, PopDeployment>>;
|
|
208
223
|
interface PopApiPaths {
|
|
209
224
|
/** POST — 임시 claim 지갑 생성 (Bearer JWT). */
|
|
210
225
|
createWallet: string;
|
|
@@ -233,6 +248,9 @@ interface PopApiPaths {
|
|
|
233
248
|
eventsSubscribe: string;
|
|
234
249
|
}
|
|
235
250
|
declare const DEFAULT_POP_API_PATHS: PopApiPaths;
|
|
251
|
+
declare function getPopEnvironment(): PopEnvironment;
|
|
252
|
+
declare function getOnePopDeployment(): PopDeployment;
|
|
253
|
+
declare function getOnePopContracts(): PopContracts;
|
|
236
254
|
/** 환경변수(override → 환경 식별)로 one-pop-api base URL을 결정한다. */
|
|
237
255
|
declare function getOnePopApiBaseUrl(): string;
|
|
238
256
|
/** 환경변수(override → 기본)로 cross-auth base URL을 결정한다. */
|
|
@@ -853,8 +871,8 @@ declare class CrossAuthClient {
|
|
|
853
871
|
}
|
|
854
872
|
|
|
855
873
|
interface CreateSafeDropClientOptions {
|
|
856
|
-
/** SafeDrop 컨트랙트 주소. */
|
|
857
|
-
contractAddress
|
|
874
|
+
/** SafeDrop 컨트랙트 주소. 미지정 시 ONE_POP_ENVIRONMENT 배포 설정. */
|
|
875
|
+
contractAddress?: Address;
|
|
858
876
|
publicClient: PublicClient;
|
|
859
877
|
/** deposit/refund 서명용 연결 지갑. */
|
|
860
878
|
walletClient: WalletClient;
|
|
@@ -959,4 +977,4 @@ declare class XAuthClient {
|
|
|
959
977
|
}>;
|
|
960
978
|
}
|
|
961
979
|
|
|
962
|
-
export { type CreateSafeDropClientOptions, CrossAuthClient, type CrossAuthClientOptions, DEFAULT_POP_API_PATHS, HttpSafeDropApiAdapter, type HttpSafeDropApiAdapterOptions, HttpXAuthAdapter, type HttpXAuthAdapterOptions, ONEPOP_ABI, type Pkce, type PopApiPaths, type PopEnvironment, SAFEDROP_ABI, SAFEDROP_VALIDATOR_ABI, type SafeDropTransactionFees, type SessionStore, ViemClaimSignerAdapter, ViemCryptoAdapter, ViemSafeDropChainAdapter, type ViemSafeDropChainAdapterOptions, XAuthClient, type XAuthClientOptions, createSafeDropClient, generatePkce, generateState, getCrossAuthBaseUrl, getOnePopApiBaseUrl };
|
|
980
|
+
export { type CreateSafeDropClientOptions, CrossAuthClient, type CrossAuthClientOptions, DEFAULT_POP_API_PATHS, HttpSafeDropApiAdapter, type HttpSafeDropApiAdapterOptions, HttpXAuthAdapter, type HttpXAuthAdapterOptions, ONEPOP_ABI, ONE_POP_BPS_DENOMINATOR, ONE_POP_DEPLOYMENTS, ONE_POP_FEE_BPS, type Pkce, type PopApiPaths, type PopContracts, type PopDeployment, type PopEnvironment, SAFEDROP_ABI, SAFEDROP_VALIDATOR_ABI, type SafeDropTransactionFees, type SessionStore, ViemClaimSignerAdapter, ViemCryptoAdapter, ViemSafeDropChainAdapter, type ViemSafeDropChainAdapterOptions, XAuthClient, type XAuthClientOptions, createSafeDropClient, generatePkce, generateState, getCrossAuthBaseUrl, getOnePopApiBaseUrl, getOnePopContracts, getOnePopDeployment, getPopEnvironment };
|
package/dist/adapters/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,k as j}from"../chunk-SE2HF5WH.js";import{bytesToHex as he,keccak256 as ge,recoverAddress as fe,toBytes as be}from"viem";var g=class{keccak256(e){return ge(be(e))}randomSecret(){let e=new Uint8Array(32);return we().getRandomValues(e),he(e).slice(2)}recoverAddress(e){return fe({hash:e.digest,signature:e.signature})}};function we(){let i=globalThis.crypto;if(!i||typeof i.getRandomValues!="function")throw new Error("Secure crypto RNG (globalThis.crypto.getRandomValues) is unavailable");return i}import{serializeSignature as Te,sign as Pe}from"viem/accounts";var f=class{async signDigest(e){try{let t=await Pe({hash:e.digest,privateKey:e.claimKey});return Te(t)}catch(t){throw new a("SIGN_FAILED","Failed to sign claim digest with temp key",{cause:t instanceof Error?t.message:String(t)})}}};import{BaseError as Ce,ContractFunctionRevertedError as J,createWalletClient as Y,http as Re,keccak256 as H,parseSignature as Q,toBytes as T,toHex as ee}from"viem";import{privateKeyToAccount as te,serializeSignature as ne,sign as ie}from"viem/accounts";var Z=[{name:"sponsor",type:"address"},{name:"amount",type:"uint96"},{name:"claimAddr",type:"address"},{name:"recipient",type:"address"},{name:"secretHash",type:"bytes32"},{name:"id",type:"string"}],D=[{name:"dropKeys",type:"bytes32[]"},{name:"records",type:"tuple[]",components:Z}],Ae=["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"],N=[...Ae.map(i=>({type:"error",name:i,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"}]}],d=[{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:Z},{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:D},{type:"function",name:"pendingDropsByRecipient",stateMutability:"view",inputs:[{name:"recipient",type:"address"}],outputs:D},{type:"function",name:"pendingDropsOf",stateMutability:"view",inputs:[{name:"sponsor",type:"address"}],outputs:D},{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:[]},...N];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"}]},...N],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[]"}]}],k={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]};var w=[{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 _e="0x0000000000000000000000000000000000000000",ve=`0x${"00".repeat(32)}`,Ie={gas:BigInt(1e6),batchBaseGas:BigInt(1e6),batchGasPerDrop:BigInt(75e4),maxBatchGas:BigInt(3e7),maxFeePerGas:BigInt(4e9),maxPriorityFeePerGas:BigInt(1e9)},re=BigInt(1800),P=class{constructor(e){if(this.address=e.address,this.publicClient=e.publicClient,this.walletClient=e.walletClient,this.chain=e.chain,this.transport=e.transport??Re(),this.transactionFees={...Ie,...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 a("INVALID_PARAM","invalid EIP-1559 gas configuration");this.depositWithPermit=t=>this.permitDeposit(t)}async getDropByKey(e){try{let[t,n,r,s,c,u]=await this.publicClient.readContract({address:this.address,abi:d,functionName:"drops",args:[e]});return t.toLowerCase()===_e?null:{dropKey:e,sponsor:t,amount:n,claimAddress:r,recipient:s,secretHash:c,id:u}}catch(t){throw p("drops",t)}}async getDropKeyByClaimAddress(e,t){try{let n=await this.publicClient.readContract({address:this.address,abi:d,functionName:"activeDropOf",args:[t,e]});return n===ve?null:n}catch(n){throw p("activeDropOf",n)}}async getPendingDropsById(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:d,functionName:"pendingDropsByXid",args:[e.id]});return n.map((r,s)=>M(t[s],r))}catch(t){throw p("pendingDropsByXid",t)}}async getPendingDropsByRecipient(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:d,functionName:"pendingDropsByRecipient",args:[e.recipient]});return n.map((r,s)=>M(t[s],r))}catch(t){throw p("pendingDropsByRecipient",t)}}async getPendingDropsBySponsor(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:d,functionName:"pendingDropsOf",args:[e.sponsor]});return n.map((r,s)=>M(t[s],r))}catch(t){throw p("pendingDropsOf",t)}}async getDrop(e,t){let n=await this.getDropKeyByClaimAddress(e,t);if(!n)return null;let[r,s]=await Promise.all([this.getDropByKey(n),this.escrowToken()]);return r&&s?{...r,token:s}:null}async escrowToken(){try{return await this.publicClient.readContract({address:this.address,abi:C,functionName:"token"})}catch{throw new a("CHAIN_ERROR","token() failed")}}async getClaimDigest(e){try{return await this.publicClient.readContract({address:this.address,abi:d,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,[r,s,c]=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(r.toLowerCase()!==n.toLowerCase())throw new a("INVALID_TOKEN","token does not match the escrow token",{expected:r,received:e.token});let u=BigInt(Math.floor(Date.now()/1e3))+re,h=await this.walletClient.signTypedData({account:t,domain:{...c,chainId:this.chain.id,verifyingContract:n},types:k,primaryType:"Permit",message:{owner:t.address,spender:this.address,value:e.amount,nonce:s,deadline:u}}),{r:I,s:S,v:x,yParity:E}=Q(h),l=await this.walletClient.writeContract({address:this.address,abi:C,functionName:"deposit",args:[e.claimAddress,e.amount,e.id,e.secretHash,u,Number(x??BigInt(E+27)),I,S],account:t,chain:this.chain,...this.transactionOverrides()});return await e.onSubmitted?.(l),await this.confirm("depositWithPermit",l),{txHash:l}}catch(t){throw p("depositWithPermit",t)}}async depositMapped(e){try{let t=this.requireAccount(),n=e.token,[r,s,c]=await Promise.all([this.publicClient.readContract({address:this.address,abi:d,functionName:"token"}),this.publicClient.readContract({address:n,abi:b,functionName:"nonces",args:[t.address]}),this.permitDomain(n)]);if(r.toLowerCase()!==n.toLowerCase())throw new a("INVALID_TOKEN","token does not match the escrow token",{expected:r,received:e.token});let u=BigInt(Math.floor(Date.now()/1e3))+re,h=await this.walletClient.signTypedData({account:t,domain:{...c,chainId:this.chain.id,verifyingContract:n},types:k,primaryType:"Permit",message:{owner:t.address,spender:this.address,value:e.amount,nonce:s,deadline:u}}),{r:I,s:S,v:x,yParity:E}=Q(h),l=[e.amount,e.id,u,Number(x??BigInt(E+27)),I,S];await this.publicClient.simulateContract({address:this.address,abi:d,functionName:"depositMapped",args:l,account:t});let O=await this.walletClient.writeContract({address:this.address,abi:d,functionName:"depositMapped",args:l,account:t,chain:this.chain,...this.transactionOverrides()});return await e.onSubmitted?.(O),await this.confirm("depositMapped",O),{txHash:O}}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=te(e.claimKey),n=await this.publicClient.readContract({address:this.address,abi:d,functionName:"claimDigest",args:[e.recipient,e.id,e.dropKey]}),r=e.signature??ne(await ie({hash:n,privateKey:e.claimKey})),c=await Y({account:t,chain:this.chain,transport:this.transport}).writeContract({address:this.address,abi:d,functionName:"withdrawUnmapped",args:[e.recipient,e.id,e.dropKey,r,ee(T(e.secret))],...this.transactionOverrides()});return await e.onSubmitted?.(c),await this.confirm("withdrawUnmapped",c),c}catch(t){throw t instanceof a?t:new a("CHAIN_ERROR","withdrawUnmapped failed")}}async withdrawMapped(e){let t=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:d,functionName:"withdrawMapped",args:[e.dropKey],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:d,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 a("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:d,functionName:"batchWithdrawMapped",args:[BigInt(e.count)],account:n});let r=await this.walletClient.writeContract({address:this.address,abi:d,functionName:"batchWithdrawMapped",args:[BigInt(e.count)],account:n,chain:this.chain,...t});return await this.confirm("batchWithdrawMapped",r),r}catch(r){throw p("batchWithdrawMapped",r)}}async batchWithdrawMappedByKeys(e){if(!e.dropKeys.length)throw new a("INVALID_PARAM","dropKeys must not be empty");let t=this.batchTransactionOverrides(e.dropKeys.length),n=this.requireAccount(),r=[e.dropKeys];try{await this.publicClient.simulateContract({address:this.address,abi:d,functionName:"batchWithdrawMapped",args:r,account:n});let s=await this.walletClient.writeContract({address:this.address,abi:d,functionName:"batchWithdrawMapped",args:r,account:n,chain:this.chain,...t});return await this.confirm("batchWithdrawMapped",s),s}catch(s){throw p("batchWithdrawMapped",s)}}async withdrawUnmappedBatchByKeys(e){let t=this.batchTransactionOverrides(e.dropKeys.length);try{let n=te(e.claimKey),r=await this.publicClient.readContract({address:this.address,abi:d,functionName:"claimDigest",args:[e.recipient,e.id,e.anchorDropKey]}),s=ne(await ie({hash:r,privateKey:e.claimKey})),u=await Y({account:n,chain:this.chain,transport:this.transport}).writeContract({address:this.address,abi:d,functionName:"withdrawUnmappedBatchByKeys",args:[e.recipient,e.id,e.anchorDropKey,s,ee(T(e.secret)),e.nonce,e.deadline,e.dropKeys,e.validatorSignature],...t});return await this.confirm("withdrawUnmappedBatchByKeys",u),u}catch{throw new a("CHAIN_ERROR","withdrawUnmappedBatchByKeys failed")}}async getValidatorNonce(e){try{return await this.publicClient.readContract({address:this.address,abi:w,functionName:"validatorNonceById",args:[H(T(e.id))]})}catch(t){throw p("validatorNonceById",t)}}async getValidatorClaimDigest(e){try{return await this.publicClient.readContract({address:this.address,abi:w,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:w,functionName:"validator"})}catch(e){throw p("validator",e)}}async getClaimedRecipient(e){try{return await this.publicClient.readContract({address:this.address,abi:d,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:d,functionName:"refund",args:[e.dropKey],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:d,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:d,functionName:"changeNonceById",args:[H(T(e.id))]})}catch(t){throw p("changeNonceById",t)}}async getPendingRecipientChange(e){try{return await this.publicClient.readContract({address:this.address,abi:d,functionName:"pendingRecipientChange",args:[H(T(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:d,functionName:"resetRecipient",args:[e.id,e.nonce,e.deadline,e.signature],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:d,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:d,functionName:e,args:t,account:n});let r=await this.walletClient.writeContract({address:this.address,abi:d,functionName:e,args:t,account:n,chain:this.chain,...this.transactionOverrides()});return await this.confirm(e,r),r}catch(r){throw p(e,r)}}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 a("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 a("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)}}async confirm(e,t){let n=await this.publicClient.waitForTransactionReceipt({hash:t});if(n.status!=="success"){let r=await this.recoverRevertName(t,n.blockNumber),s=r?`SafeDrop.${e} reverted: ${r}`:`transaction reverted: ${t}`;throw new a("CHAIN_ERROR",s,{revertName:r,txHash:t})}}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 ae(n)}}requireAccount(){let e=this.walletClient.account;if(!e)throw new a("CHAIN_ERROR","walletClient has no account (connect a wallet first)");return e}};function M(i,e){return{dropKey:i,sponsor:e.sponsor,amount:e.amount,claimAddress:e.claimAddr,recipient:e.recipient,secretHash:e.secretHash,id:e.id}}function p(i,e){if(e instanceof a)return e;let t=ae(e),n=e instanceof Error?e.message:String(e),r=t?`SafeDrop.${i} reverted: ${t}`:`SafeDrop.${i} failed`;return new a("CHAIN_ERROR",r,{cause:n,revertName:t})}function ae(i){if(!(i instanceof Ce))return;let e=i.walk(t=>t instanceof J);if(e instanceof J)return e.data?.errorName??e.reason??void 0}var Se={dev:"https://dev-one-pop-api.onechain.nexus/api",stage:"https://stg-one-pop-api.onechain.nexus/api",production:"https://one-pop-api.onechain.nexus/api"},U={createWallet:"/wallets",dropMetadata:"/drops/metadata",retrievePrivateKey:"/wallets/private-key",drops:"/drops",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"},xe="https://dev-cross-auth.crosstoken.io";function B(i){try{return import.meta.env?.[i]}catch{return}}function R(i){if(!(typeof process>"u"||!process.env))switch(i){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 Ee(){switch((B("VITE_ONE_POP_ENVIRONMENT")??R("NEXT_PUBLIC_ONE_POP_ENVIRONMENT")??R("ONE_POP_ENVIRONMENT"))?.toLowerCase()){case"dev":case"development":return"dev";case"stg":case"stage":case"staging":return"stage";default:return"production"}}function V(){let e=B("VITE_ONE_POP_API_BASE_URL")??R("NEXT_PUBLIC_ONE_POP_API_BASE_URL")??Se[Ee()];return se(e),e}function K(){let e=(B("VITE_CROSS_AUTH_URL")??R("NEXT_PUBLIC_CROSS_AUTH_URL")??xe).replace(/\/+$/,"");return se(e),e}function se(i){let e;try{e=new URL(i)}catch{throw new Error(`[pop] Invalid base URL: ${i}`)}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: ${i}`)}var Oe={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"},_=140,A=class{constructor(e={}){this.baseUrl=(e.baseUrl??V()).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={...U,...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 a("API_ERROR","createClaimWallet: missing address in response",{body:t});if(!t.identifier)throw new a("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>_)throw new a("INVALID_PARAM",`message must be <= ${_} 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?.is_mapped===!0)return{isMapped:!0};if(!t?.private_key||!t.address)throw new a("API_ERROR","retrieveClaimKey: missing key/address in response",{body:t});if(t.address.toLowerCase()!==e.claimAddress.toLowerCase())throw new a("API_ERROR","retrieveClaimKey: returned a different address");return{isMapped:!1,claimKey:t.private_key,claimAddress:t.address}}async listDrops(e={}){let t=await this.request(this.paths.drops,{method:"GET",auth:!0,query:{token:e.token}});return{items:(t?.items??[]).map(Ne),count:t?.count??0,totalAmount:y(t?.total_amount,"drops.total_amount"),hasClaimedBefore:t?.has_claimed_before===!0,mappedRecipient:m(t?.mapped_recipient),pendingChangeTo:m(t?.pending_change_to)}}async listEnvelopes(e={}){return((await this.request(this.paths.envelopes,{method:"GET",query:{locale:e.locale}}))?.items??[]).map(n=>({id:o(n.id),name:o(n.name),imageUrl:o(n.image_url),badge:o(n.badge),sortOrder:Number(n.sort_order??0)}))}async getLeaderboard(e){if(!e.token)throw new a("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(de),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{...de(t??{}),rank:ye(t?.rank)}}async listHistories(e){if(!e?.type)throw new a("INVALID_PARAM","listHistories requires type");let t=await this.request(this.paths.histories,{method:"GET",auth:!0,query:{type:e.type,token:e.token,page:e.page,page_size:e.pageSize}});return{items:(t?.items??[]).map(n=>({id:Number(n.id??0),type:o(n.type),status:o(n.status),token:o(n.token),amount:y(n.amount,"history.amount"),claimAddress:o(n.claim_address),depositTxHash:o(n.deposit_tx_hash),depositedAt:o(n.deposited_at),resolvedTxHash:m(n.resolved_tx_hash),resolvedAt:m(n.resolved_at),message:o(n.message),feedback:m(n.feedback),envelopeId:o(n.envelope_id),sender:pe(n.sender),receiver:pe(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?oe(e):null}async connectX(e){let t=await this.request(this.paths.xConnections,{method:"POST",auth:!0,payload:{oauth_token:e.oauth.accessToken}});return oe(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 a("INVALID_PARAM","dropId must be a positive integer");if(!e.message.trim()||[...e.message.trim()].length>_)throw new a("INVALID_PARAM",`message must be 1-${_} runes`);let t=await this.request(this.paths.feedbacks,{method:"PUT",auth:!0,query:{drop_id:e.dropId},payload:{message:e.message}});return o(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:ce(e)});return{...ue(t,e),newRecipient:o(t?.new_recipient)}}async requestRecipientResetSignature(e){let t=await this.request(this.paths.recipientResetSignature,{method:"POST",payload:ce(e)});return ue(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=o(t?.signature);if(!n)throw new a("API_ERROR","requestBatchClaimSignature: missing signature",{body:t});return{id:o(t?.id)||e.id,recipient:o(t?.recipient),nonce:v(t?.nonce)?y(t?.nonce,"batchClaim.nonce"):e.nonce,deadline:v(t?.deadline)?y(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 s=await this.getJwt?.();if(!s)throw new a("UNAUTHORIZED",`${e} requires a SIWE JWT (options.getJwt)`);n.Authorization=`Bearer ${s}`}let r;try{r=await this.fetchImpl(`${this.baseUrl}${e}${De(t.query)}`,{method:t.method,headers:n,body:t.payload?JSON.stringify(t.payload):void 0})}catch(s){throw new a("API_ERROR",`Network error calling ${e}`,{cause:s instanceof Error?s.message:String(s)})}if(r.status===404&&t.notFoundAsNull)return null;if(!r.ok){let s=await r.json().catch(()=>{}),c=s?.code_name;throw new a((c?Oe[c]:void 0)??"API_ERROR",s?.message?`${e}: ${s.message}`:`${e} responded ${r.status}`,{status:r.status,code:s?.code,codeName:c})}return r.status===204?null:await r.json().catch(()=>null)}};function De(i){if(!i)return"";let e=new URLSearchParams;for(let[n,r]of Object.entries(i))r!==void 0&&r!==""&&e.set(n,String(r));let t=e.toString();return t?`?${t}`:""}function v(i){return i!=null&&i!==""}function o(i){return typeof i=="string"?i:""}function m(i){return typeof i=="string"&&i?i:null}function y(i,e){if(typeof i=="bigint")return i;if(typeof i=="number"){if(!Number.isSafeInteger(i))throw new a("API_ERROR",`${e} exceeds safe-integer precision as a JSON number`,{value:i});return BigInt(i)}let t=typeof i=="string"?i.trim():"";if(!t)return BigInt(0);try{return BigInt(t)}catch{throw new a("API_ERROR",`${e} is not a valid decimal string`,{value:i})}}function Ne(i){let e=i??{},t=e.sender??{};return{id:Number(e.id??0),dropKey:o(e.drop_key),claimAddress:o(e.claim_address),token:o(e.token),amount:y(e.amount,"drop.amount"),message:o(e.message),envelopeId:o(e.envelope_id),depositedAt:o(e.deposited_at),sender:{address:o(t.address),handle:o(t.handle),displayName:o(t.display_name),profileImageUrl:o(t.profile_image_url)}}}function oe(i){return{xUserId:o(i.x_user_id),handle:o(i.handle),displayName:o(i.display_name),profileImageUrl:o(i.profile_image_url),walletAddress:o(i.wallet_address),revealYou:i.reveal_you===!0,onchainMapped:i.onchain_mapped===!0,mappedRecipient:m(i.mapped_recipient)}}function de(i){return{identifier:o(i.identifier),balance:y(i.balance,"leaderboard.balance"),lastDepositAmount:y(i.last_deposit_amount,"leaderboard.last_deposit_amount"),rank:Number(i.rank??0),previousRank:ye(i.previous_rank),profileImageUrl:o(i.profile_image_url)}}function ye(i){return typeof i=="number"?i:null}function pe(i){let e=i??{};return{address:o(e.address),handle:o(e.handle),displayName:o(e.display_name),profileImageUrl:o(e.profile_image_url)}}function ce(i){return{id:i.id,oauth_token:i.oauth.accessToken,nonce:i.nonce.toString(),deadline:i.deadline.toString()}}function ue(i,e){let t=o(i?.signature);if(!t)throw new a("API_ERROR","signature response is missing signature");return{id:o(i?.id)||e.id,nonce:v(i?.nonce)?y(i?.nonce,"signature.nonce"):e.nonce,deadline:v(i?.deadline)?y(i?.deadline,"signature.deadline"):e.deadline,signature:t}}var le=[{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 He=le;var L=class{constructor(e={}){this.baseUrl=(e.baseUrl??K()).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(s){throw new a("API_ERROR",`cross-auth network error calling ${e}`,{cause:s instanceof Error?s.message:String(s)})}let r=await n.json().catch(()=>({}));if(!n.ok||r.data==null)throw new a("API_ERROR",`cross-auth ${e} failed`,{code:r.code,message:r.message});return r.data}};function Me(i){let e=i.apiPort??new A(i.api),t=new P({address:i.contractAddress,publicClient:i.publicClient,walletClient:i.walletClient,chain:i.chain,transport:i.transport,withdrawFees:i.withdrawFees,transactionFees:i.transactionFees});return j({claimBaseUrl:i.claimBaseUrl},{api:e,chain:t,signer:new f,crypto:new g})}async function q(){let i=F(me(32)),e=await Ue().digest("SHA-256",Be(i)),t=F(new Uint8Array(e));return{verifier:i,challenge:t,method:"S256"}}function X(){return F(me(16))}function me(i){let e=globalThis.crypto;if(!e?.getRandomValues)throw new Error("crypto.getRandomValues unavailable");let t=new Uint8Array(i);return e.getRandomValues(t),t}function Ue(){let i=globalThis.crypto?.subtle;if(!i)throw new Error("crypto.subtle unavailable (needs https/secure context)");return i}function Be(i){return new TextEncoder().encode(i)}function F(i){let e="";for(let n of i)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 G=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 a("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(()=>({})),r=n.data?.username??n.username;if(!r)throw new a("API_ERROR","X /me: missing username",{body:n});return{handle:r}}async call(e,t){let n;try{n=await this.fetchImpl(`${this.baseUrl}${e}`,t)}catch(r){throw new a("API_ERROR",`Network error calling ${e}`,{cause:r instanceof Error?r.message:String(r)})}if(!n.ok)throw new a("API_ERROR",`${e} responded ${n.status}`,{status:n.status});return n}};var W="pop.xauth.verifier",$="pop.xauth.state",Ve="https://x.com/i/oauth2/authorize",Ke="tweet.read users.read offline.access",z=class{constructor(e){this.opts={clientId:e.clientId,redirectUri:e.redirectUri,scope:e.scope??Ke,authorizeUrl:e.authorizeUrl??Ve,port:e.port,storage:e.storage??Le()}}async start(){let e=await q(),t=X();this.opts.storage.set(W,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"),r=t.searchParams.get("state");if(!n)throw new a("API_ERROR","X callback: missing authorization code",{error:t.searchParams.get("error")});let s=this.opts.storage.get($);if(!r||!s||r!==s)throw new a("API_ERROR","X callback: state mismatch (possible CSRF)");let c=this.opts.storage.get(W);if(!c)throw new a("API_ERROR","X callback: missing PKCE verifier (expired session?)");let u=await this.opts.port.exchangeCode({clientId:this.opts.clientId,redirectUri:this.opts.redirectUri,code:n,codeVerifier:c}),{handle:h}=await this.opts.port.getHandle(u.accessToken);return this.opts.storage.remove(W),this.opts.storage.remove($),{oauth:{provider:"x",accessToken:u.accessToken},handle:h}}};function Le(){let i=globalThis.sessionStorage;if(!i)throw new Error("sessionStorage unavailable; provide options.storage");return{get:e=>i.getItem(e),set:(e,t)=>i.setItem(e,t),remove:e=>i.removeItem(e)}}export{L as CrossAuthClient,U as DEFAULT_POP_API_PATHS,A as HttpSafeDropApiAdapter,G as HttpXAuthAdapter,d as ONEPOP_ABI,He as SAFEDROP_ABI,w as SAFEDROP_VALIDATOR_ABI,f as ViemClaimSignerAdapter,g as ViemCryptoAdapter,P as ViemSafeDropChainAdapter,z as XAuthClient,Me as createSafeDropClient,q as generatePkce,X as generateState,K as getCrossAuthBaseUrl,V as getOnePopApiBaseUrl};
|
|
1
|
+
import{a,k as Q}from"../chunk-E3ZMMRDI.js";import{bytesToHex as Te,keccak256 as Ae,recoverAddress as Ce,toBytes as Re}from"viem";var g=class{keccak256(e){return Ae(Re(e))}randomSecret(){let e=new Uint8Array(32);return _e().getRandomValues(e),Te(e).slice(2)}recoverAddress(e){return Ce({hash:e.digest,signature:e.signature})}};function _e(){let i=globalThis.crypto;if(!i||typeof i.getRandomValues!="function")throw new Error("Secure crypto RNG (globalThis.crypto.getRandomValues) is unavailable");return i}import{serializeSignature as ve,sign as Ee}from"viem/accounts";var f=class{async signDigest(e){try{let t=await Ee({hash:e.digest,privateKey:e.claimKey});return ve(t)}catch(t){throw new a("SIGN_FAILED","Failed to sign claim digest with temp key",{cause:t instanceof Error?t.message:String(t)})}}};import{BaseError as ce,ContractFunctionRevertedError as te,createWalletClient as ne,http as Ie,keccak256 as M,parseSignature as ie,toBytes as P,toHex as re}from"viem";import{privateKeyToAccount as ae,serializeSignature as se,sign as oe}from"viem/accounts";var ee=[{name:"sponsor",type:"address"},{name:"amount",type:"uint96"},{name:"claimAddr",type:"address"},{name:"recipient",type:"address"},{name:"secretHash",type:"bytes32"},{name:"id",type:"string"}],D=[{name:"dropKeys",type:"bytes32[]"},{name:"records",type:"tuple[]",components:ee}],xe=["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"],N=[...xe.map(i=>({type:"error",name:i,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"}]}],d=[{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:ee},{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:D},{type:"function",name:"pendingDropsByRecipient",stateMutability:"view",inputs:[{name:"recipient",type:"address"}],outputs:D},{type:"function",name:"pendingDropsOf",stateMutability:"view",inputs:[{name:"sponsor",type:"address"}],outputs:D},{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:[]},...N];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"}]},...N],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[]"}]}],k={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]};var w=[{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 Se="0x0000000000000000000000000000000000000000",Oe=`0x${"00".repeat(32)}`,De={gas:BigInt(1e6),batchBaseGas:BigInt(1e6),batchGasPerDrop:BigInt(75e4),maxBatchGas:BigInt(3e7),maxFeePerGas:BigInt(4e9),maxPriorityFeePerGas:BigInt(1e9)},de=BigInt(1800),T=class{constructor(e){if(this.address=e.address,this.publicClient=e.publicClient,this.walletClient=e.walletClient,this.chain=e.chain,this.transport=e.transport??Ie(),this.transactionFees={...De,...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 a("INVALID_PARAM","invalid EIP-1559 gas configuration");this.depositWithPermit=t=>this.permitDeposit(t)}async getDropByKey(e){try{let[t,n,r,s,c,u]=await this.publicClient.readContract({address:this.address,abi:d,functionName:"drops",args:[e]});return t.toLowerCase()===Se?null:{dropKey:e,sponsor:t,amount:n,claimAddress:r,recipient:s,secretHash:c,id:u}}catch(t){throw p("drops",t)}}async getDropKeyByClaimAddress(e,t){try{let n=await this.publicClient.readContract({address:this.address,abi:d,functionName:"activeDropOf",args:[t,e]});return n===Oe?null:n}catch(n){throw p("activeDropOf",n)}}async getPendingDropsById(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:d,functionName:"pendingDropsByXid",args:[e.id]});return n.map((r,s)=>H(t[s],r))}catch(t){throw p("pendingDropsByXid",t)}}async getPendingDropsByRecipient(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:d,functionName:"pendingDropsByRecipient",args:[e.recipient]});return n.map((r,s)=>H(t[s],r))}catch(t){throw p("pendingDropsByRecipient",t)}}async getPendingDropsBySponsor(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:d,functionName:"pendingDropsOf",args:[e.sponsor]});return n.map((r,s)=>H(t[s],r))}catch(t){throw p("pendingDropsOf",t)}}async getDrop(e,t){let n=await this.getDropKeyByClaimAddress(e,t);if(!n)return null;let[r,s]=await Promise.all([this.getDropByKey(n),this.escrowToken()]);return r&&s?{...r,token:s}:null}async escrowToken(){try{return await this.publicClient.readContract({address:this.address,abi:C,functionName:"token"})}catch{throw new a("CHAIN_ERROR","token() failed")}}async getClaimDigest(e){try{return await this.publicClient.readContract({address:this.address,abi:d,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,[r,s,c]=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(r.toLowerCase()!==n.toLowerCase())throw new a("INVALID_TOKEN","token does not match the escrow token",{expected:r,received:e.token});let u=BigInt(Math.floor(Date.now()/1e3))+de,l=await this.walletClient.signTypedData({account:t,domain:{...c,chainId:this.chain.id,verifyingContract:n},types:k,primaryType:"Permit",message:{owner:t.address,spender:this.address,value:e.amount,nonce:s,deadline:u}}),{r:E,s:x,v:I,yParity:S}=ie(l),m=await this.walletClient.writeContract({address:this.address,abi:C,functionName:"deposit",args:[e.claimAddress,e.amount,e.id,e.secretHash,u,Number(I??BigInt(S+27)),E,x],account:t,chain:this.chain,...this.transactionOverrides()});return await e.onSubmitted?.(m),await this.confirm("depositWithPermit",m),{txHash:m}}catch(t){throw p("depositWithPermit",t)}}async depositMapped(e){try{let t=this.requireAccount(),n=e.token,[r,s,c]=await Promise.all([this.publicClient.readContract({address:this.address,abi:d,functionName:"token"}),this.publicClient.readContract({address:n,abi:b,functionName:"nonces",args:[t.address]}),this.permitDomain(n)]);if(r.toLowerCase()!==n.toLowerCase())throw new a("INVALID_TOKEN","token does not match the escrow token",{expected:r,received:e.token});let u=BigInt(Math.floor(Date.now()/1e3))+de,l=await this.walletClient.signTypedData({account:t,domain:{...c,chainId:this.chain.id,verifyingContract:n},types:k,primaryType:"Permit",message:{owner:t.address,spender:this.address,value:e.amount,nonce:s,deadline:u}}),{r:E,s:x,v:I,yParity:S}=ie(l),m=[e.amount,e.id,u,Number(I??BigInt(S+27)),E,x];await this.publicClient.simulateContract({address:this.address,abi:d,functionName:"depositMapped",args:m,account:t});let O=await this.walletClient.writeContract({address:this.address,abi:d,functionName:"depositMapped",args:m,account:t,chain:this.chain,...this.transactionOverrides()});return await e.onSubmitted?.(O),await this.confirm("depositMapped",O),{txHash:O}}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=ae(e.claimKey),n=await this.publicClient.readContract({address:this.address,abi:d,functionName:"claimDigest",args:[e.recipient,e.id,e.dropKey]}),r=e.signature??se(await oe({hash:n,privateKey:e.claimKey})),c=await ne({account:t,chain:this.chain,transport:this.transport}).writeContract({address:this.address,abi:d,functionName:"withdrawUnmapped",args:[e.recipient,e.id,e.dropKey,r,re(P(e.secret))],...this.transactionOverrides()});return await e.onSubmitted?.(c),await this.confirm("withdrawUnmapped",c),c}catch(t){throw pe("withdrawUnmapped",t)}}async withdrawMapped(e){let t=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:d,functionName:"withdrawMapped",args:[e.dropKey],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:d,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 a("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:d,functionName:"batchWithdrawMapped",args:[BigInt(e.count)],account:n});let r=await this.walletClient.writeContract({address:this.address,abi:d,functionName:"batchWithdrawMapped",args:[BigInt(e.count)],account:n,chain:this.chain,...t});return await this.confirm("batchWithdrawMapped",r),r}catch(r){throw p("batchWithdrawMapped",r)}}async batchWithdrawMappedByKeys(e){if(!e.dropKeys.length)throw new a("INVALID_PARAM","dropKeys must not be empty");let t=this.batchTransactionOverrides(e.dropKeys.length),n=this.requireAccount(),r=[e.dropKeys];try{await this.publicClient.simulateContract({address:this.address,abi:d,functionName:"batchWithdrawMapped",args:r,account:n});let s=await this.walletClient.writeContract({address:this.address,abi:d,functionName:"batchWithdrawMapped",args:r,account:n,chain:this.chain,...t});return await this.confirm("batchWithdrawMapped",s),s}catch(s){throw p("batchWithdrawMapped",s)}}async withdrawUnmappedBatchByKeys(e){let t=e.dropKeys.filter(r=>r.toLowerCase()!==e.anchorDropKey.toLowerCase()),n=this.batchTransactionOverrides(t.length+1);try{let r=ae(e.claimKey),s=await this.publicClient.readContract({address:this.address,abi:d,functionName:"claimDigest",args:[e.recipient,e.id,e.anchorDropKey]}),c=se(await oe({hash:s,privateKey:e.claimKey})),l=await ne({account:r,chain:this.chain,transport:this.transport}).writeContract({address:this.address,abi:d,functionName:"withdrawUnmappedBatchByKeys",args:[e.recipient,e.id,e.anchorDropKey,c,re(P(e.secret)),e.nonce,e.deadline,t,e.validatorSignature],...n});return await this.confirm("withdrawUnmappedBatchByKeys",l),l}catch(r){throw pe("withdrawUnmappedBatchByKeys",r)}}async getValidatorNonce(e){try{return await this.publicClient.readContract({address:this.address,abi:w,functionName:"validatorNonceById",args:[M(P(e.id))]})}catch(t){throw p("validatorNonceById",t)}}async getValidatorClaimDigest(e){try{return await this.publicClient.readContract({address:this.address,abi:w,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:w,functionName:"validator"})}catch(e){throw p("validator",e)}}async getClaimedRecipient(e){try{return await this.publicClient.readContract({address:this.address,abi:d,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:d,functionName:"refund",args:[e.dropKey],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:d,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:d,functionName:"changeNonceById",args:[M(P(e.id))]})}catch(t){throw p("changeNonceById",t)}}async getPendingRecipientChange(e){try{return await this.publicClient.readContract({address:this.address,abi:d,functionName:"pendingRecipientChange",args:[M(P(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:d,functionName:"resetRecipient",args:[e.id,e.nonce,e.deadline,e.signature],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:d,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:d,functionName:e,args:t,account:n});let r=await this.walletClient.writeContract({address:this.address,abi:d,functionName:e,args:t,account:n,chain:this.chain,...this.transactionOverrides()});return await this.confirm(e,r),r}catch(r){throw p(e,r)}}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 a("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 a("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)}}async confirm(e,t){let n=await this.publicClient.waitForTransactionReceipt({hash:t});if(n.status!=="success"){let r=await this.recoverRevertName(t,n.blockNumber),s=r?`SafeDrop.${e} reverted: ${r}`:`transaction reverted: ${t}`;throw new a("CHAIN_ERROR",s,{revertName:r,txHash:t})}}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 B(n)}}requireAccount(){let e=this.walletClient.account;if(!e)throw new a("CHAIN_ERROR","walletClient has no account (connect a wallet first)");return e}};function H(i,e){return{dropKey:i,sponsor:e.sponsor,amount:e.amount,claimAddress:e.claimAddr,recipient:e.recipient,secretHash:e.secretHash,id:e.id}}function p(i,e){if(e instanceof a)return e;let t=B(e),n=e instanceof Error?e.message:String(e),r=t?`SafeDrop.${i} reverted: ${t}`:`SafeDrop.${i} failed`;return new a("CHAIN_ERROR",r,{cause:n,revertName:t})}function pe(i,e){if(e instanceof a)return e;let t=B(e),n=e instanceof ce?e.walk(c=>{let u=c;return typeof u.code=="number"||u.data!==void 0}):void 0,r={revertName:t};typeof n?.code=="number"&&(r.rpcCode=n.code),typeof n?.details=="string"&&(r.rpcMessage=n.details),typeof n?.data=="string"&&(r.rpcData=n.data);let s=t?`SafeDrop.${i} reverted: ${t}`:`SafeDrop.${i} failed`;return new a("CHAIN_ERROR",s,r)}function B(i){if(!(i instanceof ce))return;let e=i.walk(t=>t instanceof te);if(e instanceof te)return e.data?.errorName??e.reason??void 0}var Ne=BigInt(500),ke=BigInt(1e4),U={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"}},V={createWallet:"/wallets",dropMetadata:"/drops/metadata",retrievePrivateKey:"/wallets/private-key",drops:"/drops",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"},Me="https://dev-cross-auth.crosstoken.io";function F(i){try{return import.meta.env?.[i]}catch{return}}function R(i){if(!(typeof process>"u"||!process.env))switch(i){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 K(){let i=F("VITE_ONE_POP_ENVIRONMENT")??R("NEXT_PUBLIC_ONE_POP_ENVIRONMENT")??R("ONE_POP_ENVIRONMENT");return He(i)}function He(i){switch(i?.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: ${i}`)}}function ue(){return U[K()]}function L(){return Be(K())}function Be(i){let e=U[i].contracts;if(!e)throw new Error(`[pop] Contract addresses are not configured for ${i}`);return e}function q(){let e=F("VITE_ONE_POP_API_BASE_URL")??R("NEXT_PUBLIC_ONE_POP_API_BASE_URL")??ue().apiBaseUrl;return ye(e),e}function $(){let e=(F("VITE_CROSS_AUTH_URL")??R("NEXT_PUBLIC_CROSS_AUTH_URL")??Me).replace(/\/+$/,"");return ye(e),e}function ye(i){let e;try{e=new URL(i)}catch{throw new Error(`[pop] Invalid base URL: ${i}`)}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: ${i}`)}var Ue={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"},_=140,A=class{constructor(e={}){this.baseUrl=(e.baseUrl??q()).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={...V,...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 a("API_ERROR","createClaimWallet: missing address in response",{body:t});if(!t.identifier)throw new a("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>_)throw new a("INVALID_PARAM",`message must be <= ${_} 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?.is_mapped===!0)return{isMapped:!0};if(!t?.private_key||!t.address)throw new a("API_ERROR","retrieveClaimKey: missing key/address in response",{body:t});if(t.address.toLowerCase()!==e.claimAddress.toLowerCase())throw new a("API_ERROR","retrieveClaimKey: returned a different address");return{isMapped:!1,claimKey:t.private_key,claimAddress:t.address}}async listDrops(e={}){let t=await this.request(this.paths.drops,{method:"GET",auth:!0,query:{token:e.token}});return{items:(t?.items??[]).map(Fe),count:t?.count??0,totalAmount:y(t?.total_amount,"drops.total_amount"),hasClaimedBefore:t?.has_claimed_before===!0,mappedRecipient:h(t?.mapped_recipient),pendingChangeTo:h(t?.pending_change_to)}}async listEnvelopes(e={}){return((await this.request(this.paths.envelopes,{method:"GET",query:{locale:e.locale}}))?.items??[]).map(n=>({id:o(n.id),name:o(n.name),imageUrl:o(n.image_url),badge:o(n.badge),sortOrder:Number(n.sort_order??0)}))}async getLeaderboard(e){if(!e.token)throw new a("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(me),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{...me(t??{}),rank:be(t?.rank)}}async listHistories(e){if(!e?.type)throw new a("INVALID_PARAM","listHistories requires type");let t=await this.request(this.paths.histories,{method:"GET",auth:!0,query:{type:e.type,token:e.token,page:e.page,page_size:e.pageSize}});return{items:(t?.items??[]).map(n=>({id:Number(n.id??0),type:o(n.type),status:o(n.status),token:o(n.token),amount:y(n.amount,"history.amount"),claimAddress:o(n.claim_address),depositTxHash:o(n.deposit_tx_hash),depositedAt:o(n.deposited_at),resolvedTxHash:h(n.resolved_tx_hash),resolvedAt:h(n.resolved_at),message:o(n.message),feedback:h(n.feedback),envelopeId:o(n.envelope_id),sender:he(n.sender),receiver:he(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?le(e):null}async connectX(e){let t=await this.request(this.paths.xConnections,{method:"POST",auth:!0,payload:{oauth_token:e.oauth.accessToken}});return le(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 a("INVALID_PARAM","dropId must be a positive integer");if(!e.message.trim()||[...e.message.trim()].length>_)throw new a("INVALID_PARAM",`message must be 1-${_} runes`);let t=await this.request(this.paths.feedbacks,{method:"PUT",auth:!0,query:{drop_id:e.dropId},payload:{message:e.message}});return o(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:ge(e)});return{...fe(t,e),newRecipient:o(t?.new_recipient)}}async requestRecipientResetSignature(e){let t=await this.request(this.paths.recipientResetSignature,{method:"POST",payload:ge(e)});return fe(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=o(t?.signature);if(!n)throw new a("API_ERROR","requestBatchClaimSignature: missing signature",{body:t});return{id:o(t?.id)||e.id,recipient:o(t?.recipient),nonce:v(t?.nonce)?y(t?.nonce,"batchClaim.nonce"):e.nonce,deadline:v(t?.deadline)?y(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 s=await this.getJwt?.();if(!s)throw new a("UNAUTHORIZED",`${e} requires a SIWE JWT (options.getJwt)`);n.Authorization=`Bearer ${s}`}let r;try{r=await this.fetchImpl(`${this.baseUrl}${e}${Ve(t.query)}`,{method:t.method,headers:n,body:t.payload?JSON.stringify(t.payload):void 0})}catch(s){throw new a("API_ERROR",`Network error calling ${e}`,{cause:s instanceof Error?s.message:String(s)})}if(r.status===404&&t.notFoundAsNull)return null;if(!r.ok){let s=await r.json().catch(()=>{}),c=s?.code_name;throw new a((c?Ue[c]:void 0)??"API_ERROR",s?.message?`${e}: ${s.message}`:`${e} responded ${r.status}`,{status:r.status,code:s?.code,codeName:c})}return r.status===204?null:await r.json().catch(()=>null)}};function Ve(i){if(!i)return"";let e=new URLSearchParams;for(let[n,r]of Object.entries(i))r!==void 0&&r!==""&&e.set(n,String(r));let t=e.toString();return t?`?${t}`:""}function v(i){return i!=null&&i!==""}function o(i){return typeof i=="string"?i:""}function h(i){return typeof i=="string"&&i?i:null}function y(i,e){if(typeof i=="bigint")return i;if(typeof i=="number"){if(!Number.isSafeInteger(i))throw new a("API_ERROR",`${e} exceeds safe-integer precision as a JSON number`,{value:i});return BigInt(i)}let t=typeof i=="string"?i.trim():"";if(!t)return BigInt(0);try{return BigInt(t)}catch{throw new a("API_ERROR",`${e} is not a valid decimal string`,{value:i})}}function Fe(i){let e=i??{},t=e.sender??{};return{id:Number(e.id??0),dropKey:o(e.drop_key),claimAddress:o(e.claim_address),token:o(e.token),amount:y(e.amount,"drop.amount"),message:o(e.message),envelopeId:o(e.envelope_id),depositedAt:o(e.deposited_at),sender:{address:o(t.address),handle:o(t.handle),displayName:o(t.display_name),profileImageUrl:o(t.profile_image_url)}}}function le(i){return{xUserId:o(i.x_user_id),handle:o(i.handle),displayName:o(i.display_name),profileImageUrl:o(i.profile_image_url),walletAddress:o(i.wallet_address),revealYou:i.reveal_you===!0,onchainMapped:i.onchain_mapped===!0,mappedRecipient:h(i.mapped_recipient)}}function me(i){return{identifier:o(i.identifier),balance:y(i.balance,"leaderboard.balance"),lastDepositAmount:y(i.last_deposit_amount,"leaderboard.last_deposit_amount"),rank:Number(i.rank??0),previousRank:be(i.previous_rank),profileImageUrl:o(i.profile_image_url)}}function be(i){return typeof i=="number"?i:null}function he(i){let e=i??{};return{address:o(e.address),handle:o(e.handle),displayName:o(e.display_name),profileImageUrl:o(e.profile_image_url)}}function ge(i){return{id:i.id,oauth_token:i.oauth.accessToken,nonce:i.nonce.toString(),deadline:i.deadline.toString()}}function fe(i,e){let t=o(i?.signature);if(!t)throw new a("API_ERROR","signature response is missing signature");return{id:o(i?.id)||e.id,nonce:v(i?.nonce)?y(i?.nonce,"signature.nonce"):e.nonce,deadline:v(i?.deadline)?y(i?.deadline,"signature.deadline"):e.deadline,signature:t}}var we=[{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 Le=we;var X=class{constructor(e={}){this.baseUrl=(e.baseUrl??$()).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(s){throw new a("API_ERROR",`cross-auth network error calling ${e}`,{cause:s instanceof Error?s.message:String(s)})}let r=await n.json().catch(()=>({}));if(!n.ok||r.data==null)throw new a("API_ERROR",`cross-auth ${e} failed`,{code:r.code,message:r.message});return r.data}};function qe(i){let e=i.apiPort??new A(i.api),t=new T({address:i.contractAddress??L().onePop,publicClient:i.publicClient,walletClient:i.walletClient,chain:i.chain,transport:i.transport,withdrawFees:i.withdrawFees,transactionFees:i.transactionFees});return Q({claimBaseUrl:i.claimBaseUrl},{api:e,chain:t,signer:new f,crypto:new g})}async function W(){let i=G(Pe(32)),e=await $e().digest("SHA-256",Xe(i)),t=G(new Uint8Array(e));return{verifier:i,challenge:t,method:"S256"}}function z(){return G(Pe(16))}function Pe(i){let e=globalThis.crypto;if(!e?.getRandomValues)throw new Error("crypto.getRandomValues unavailable");let t=new Uint8Array(i);return e.getRandomValues(t),t}function $e(){let i=globalThis.crypto?.subtle;if(!i)throw new Error("crypto.subtle unavailable (needs https/secure context)");return i}function Xe(i){return new TextEncoder().encode(i)}function G(i){let e="";for(let n of i)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 j=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 a("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(()=>({})),r=n.data?.username??n.username;if(!r)throw new a("API_ERROR","X /me: missing username",{body:n});return{handle:r}}async call(e,t){let n;try{n=await this.fetchImpl(`${this.baseUrl}${e}`,t)}catch(r){throw new a("API_ERROR",`Network error calling ${e}`,{cause:r instanceof Error?r.message:String(r)})}if(!n.ok)throw new a("API_ERROR",`${e} responded ${n.status}`,{status:n.status});return n}};var Z="pop.xauth.verifier",Y="pop.xauth.state",Ge="https://x.com/i/oauth2/authorize",We="tweet.read users.read offline.access",J=class{constructor(e){this.opts={clientId:e.clientId,redirectUri:e.redirectUri,scope:e.scope??We,authorizeUrl:e.authorizeUrl??Ge,port:e.port,storage:e.storage??ze()}}async start(){let e=await W(),t=z();this.opts.storage.set(Z,e.verifier),this.opts.storage.set(Y,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"),r=t.searchParams.get("state");if(!n)throw new a("API_ERROR","X callback: missing authorization code",{error:t.searchParams.get("error")});let s=this.opts.storage.get(Y);if(!r||!s||r!==s)throw new a("API_ERROR","X callback: state mismatch (possible CSRF)");let c=this.opts.storage.get(Z);if(!c)throw new a("API_ERROR","X callback: missing PKCE verifier (expired session?)");let u=await this.opts.port.exchangeCode({clientId:this.opts.clientId,redirectUri:this.opts.redirectUri,code:n,codeVerifier:c}),{handle:l}=await this.opts.port.getHandle(u.accessToken);return this.opts.storage.remove(Z),this.opts.storage.remove(Y),{oauth:{provider:"x",accessToken:u.accessToken},handle:l}}};function ze(){let i=globalThis.sessionStorage;if(!i)throw new Error("sessionStorage unavailable; provide options.storage");return{get:e=>i.getItem(e),set:(e,t)=>i.setItem(e,t),remove:e=>i.removeItem(e)}}export{X as CrossAuthClient,V as DEFAULT_POP_API_PATHS,A as HttpSafeDropApiAdapter,j as HttpXAuthAdapter,d as ONEPOP_ABI,ke as ONE_POP_BPS_DENOMINATOR,U as ONE_POP_DEPLOYMENTS,Ne as ONE_POP_FEE_BPS,Le as SAFEDROP_ABI,w as SAFEDROP_VALIDATOR_ABI,f as ViemClaimSignerAdapter,g as ViemCryptoAdapter,T as ViemSafeDropChainAdapter,J as XAuthClient,qe as createSafeDropClient,W as generatePkce,z as generateState,$ as getCrossAuthBaseUrl,q as getOnePopApiBaseUrl,L as getOnePopContracts,ue as getOnePopDeployment,K as getPopEnvironment};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var i=class extends Error{constructor(e,r,n){super(r),this.name="SafeDropError",this.code=e,this.details=n}};function g(a){return a.trim().replace(/^@/,"").toLowerCase()}function w(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 b(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 M(a){return`\u{1F381} You've received a one-pop drop! Claim your tokens here: ${a}`}function H(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(u){if(u instanceof i&&u.details?.codeName==="ENVELOPE_NOT_FOUND"&&e.envelopeId)try{await this.api.recordDropMetadata({txHash:m,message:e.message})}catch{}}};if(n.isMapped){let{txHash:m}=await this.chain.depositMapped({token:e.token,amount:e.amount,id:s,onSubmitted:d});return{isMapped:!0,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),p={claimAddress:n.claimAddress,token:e.token,amount:e.amount,id:s,secretHash:t,onSubmitted:d},{txHash:h}=await this.chain.depositWithPermit(p);return{isMapped:!1,claimAddress:n.claimAddress,secretHash:t,withdrawLink:w({baseUrl:this.claimBaseUrl,sender:e.sender,claimAddress:n.claimAddress,secret:o}),depositTxHash:h}}};var N=BigInt(1800),x=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??x;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??N),p=[],h="",m=BigInt(0);for(;d.length;){let u=await this.chain.getValidatorNonce({id:r}),l=await this.api.requestBatchClaimSignature({id:r,oauth:e.oauth,nonce:u,deadline:t});if(e.recipient&&e.recipient.toLowerCase()!==l.recipient.toLowerCase())throw new i("SIGN_FAILED","validator signature is bound to a different recipient");if(h&&h.toLowerCase()!==l.recipient.toLowerCase())throw new i("SIGN_FAILED","validator recipient changed between batches");h=l.recipient,p.length||(m=l.nonce);let I=await this.chain.getValidatorClaimDigest({recipient:h,id:r,nonce:l.nonce,deadline:l.deadline});await this.assertSignedByValidator(I,l.signature);let R=d.length,C=await this.chain.withdrawUnmappedBatchByKeys({claimKey:e.claimKey,recipient:h,id:r,anchorDropKey:n,secret:e.secret,nonce:l.nonce,deadline:l.deadline,dropKeys:d.slice(0,o).map(D=>D.dropKey).filter(D=>D.toLowerCase()!==n.toLowerCase()),validatorSignature:l.signature});if(p.push(C),d=await this.chain.getPendingDropsById({id:r}),d.length>=R)throw new i("CHAIN_ERROR","batch claim made no progress",{id:r,txHash:C})}return{txHashes:p,recipient:h,id:r,nonce:m,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 S=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 c(a,e){if(!a)throw new i("API_ERROR",`SafeDropApiPort.${e} is not implemented by the injected api adapter`);return a}function z(a,e){let r=new y(e.chain,e.api,e.crypto,a.claimBaseUrl),n=new P(e.chain,e.signer),s=new S(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,p)=>e.chain.getDrop(t,p),getDropByKey:t=>e.chain.getDropByKey(t),getDropKeyByClaimAddress:(t,p)=>e.chain.getDropKeyByClaimAddress(t,p),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,p)=>e.chain.requestRecipientChange({id:t,newRecipient:p}),completeRecipientChange:t=>e.chain.completeRecipientChange(t),cancelRecipientChange:t=>e.chain.cancelRecipientChange({id:t}),resetRecipient:t=>e.chain.resetRecipient(t),listDrops:t=>c(o.listDrops,"listDrops").call(o,t),listEnvelopes:t=>c(o.listEnvelopes,"listEnvelopes").call(o,t),getLeaderboard:t=>c(o.getLeaderboard,"getLeaderboard").call(o,t),getMyLeaderboardEntry:t=>c(o.getMyLeaderboardEntry,"getMyLeaderboardEntry").call(o,t),listHistories:t=>c(o.listHistories,"listHistories").call(o,t),getXConnection:()=>c(o.getXConnection,"getXConnection").call(o),connectX:t=>c(o.connectX,"connectX").call(o,t),disconnectX:()=>c(o.disconnectX,"disconnectX").call(o),submitFeedback:t=>c(o.submitFeedback,"submitFeedback").call(o,t),setRevealYou:t=>c(o.setRevealYou,"setRevealYou").call(o,{revealYou:t}),requestRecipientChangeSignature:t=>c(o.requestRecipientChangeSignature,"requestRecipientChangeSignature").call(o,t),requestRecipientResetSignature:t=>c(o.requestRecipientResetSignature,"requestRecipientResetSignature").call(o,t),batchClaim:t=>d.execute(t),requestBatchClaimSignature:t=>c(o.requestBatchClaimSignature,"requestBatchClaimSignature").call(o,t)}}export{i as a,g as b,w as c,b as d,M as e,H as f,y as g,f as h,P as i,S as j,z as k};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as r,b as e,c as o,d as t,e as p,f as a,g as s,h as i,i as f,j as n,k as m}from"./chunk-
|
|
1
|
+
import{a as r,b as e,c as o,d as t,e as p,f as a,g as s,h as i,i as f,j as n,k as m}from"./chunk-E3ZMMRDI.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};
|
package/package.json
CHANGED
package/dist/chunk-SE2HF5WH.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var i=class extends Error{constructor(e,r,n){super(r),this.name="SafeDropError",this.code=e,this.details=n}};function g(a){return a.trim().replace(/^@/,"").toLowerCase()}function C(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 b(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 M(a){return`\u{1F381} You've received a one-pop drop! Claim your tokens here: ${a}`}function H(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(u){if(u instanceof i&&u.details?.codeName==="ENVELOPE_NOT_FOUND"&&e.envelopeId)try{await this.api.recordDropMetadata({txHash:m,message:e.message})}catch{}}};if(n.isMapped){let{txHash:m}=await this.chain.depositMapped({token:e.token,amount:e.amount,id:s,onSubmitted:d});return{isMapped:!0,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),p={claimAddress:n.claimAddress,token:e.token,amount:e.amount,id:s,secretHash:t,onSubmitted:d},{txHash:h}=await this.chain.depositWithPermit(p);return{isMapped:!1,claimAddress:n.claimAddress,secretHash:t,withdrawLink:C({baseUrl:this.claimBaseUrl,sender:e.sender,claimAddress:n.claimAddress,secret:o}),depositTxHash:h}}};var N=BigInt(1800),x=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??x;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??N),p=[],h="",m=BigInt(0);for(;d.length;){let u=await this.chain.getValidatorNonce({id:r}),l=await this.api.requestBatchClaimSignature({id:r,oauth:e.oauth,nonce:u,deadline:t});if(e.recipient&&e.recipient.toLowerCase()!==l.recipient.toLowerCase())throw new i("SIGN_FAILED","validator signature is bound to a different recipient");if(h&&h.toLowerCase()!==l.recipient.toLowerCase())throw new i("SIGN_FAILED","validator recipient changed between batches");h=l.recipient,p.length||(m=l.nonce);let w=await this.chain.getValidatorClaimDigest({recipient:h,id:r,nonce:l.nonce,deadline:l.deadline});await this.assertSignedByValidator(w,l.signature);let I=d.length,D=await this.chain.withdrawUnmappedBatchByKeys({claimKey:e.claimKey,recipient:h,id:r,anchorDropKey:n,secret:e.secret,nonce:l.nonce,deadline:l.deadline,dropKeys:d.slice(0,o).map(R=>R.dropKey),validatorSignature:l.signature});if(p.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:p,recipient:h,id:r,nonce:m,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 S=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 c(a,e){if(!a)throw new i("API_ERROR",`SafeDropApiPort.${e} is not implemented by the injected api adapter`);return a}function z(a,e){let r=new y(e.chain,e.api,e.crypto,a.claimBaseUrl),n=new P(e.chain,e.signer),s=new S(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,p)=>e.chain.getDrop(t,p),getDropByKey:t=>e.chain.getDropByKey(t),getDropKeyByClaimAddress:(t,p)=>e.chain.getDropKeyByClaimAddress(t,p),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,p)=>e.chain.requestRecipientChange({id:t,newRecipient:p}),completeRecipientChange:t=>e.chain.completeRecipientChange(t),cancelRecipientChange:t=>e.chain.cancelRecipientChange({id:t}),resetRecipient:t=>e.chain.resetRecipient(t),listDrops:t=>c(o.listDrops,"listDrops").call(o,t),listEnvelopes:t=>c(o.listEnvelopes,"listEnvelopes").call(o,t),getLeaderboard:t=>c(o.getLeaderboard,"getLeaderboard").call(o,t),getMyLeaderboardEntry:t=>c(o.getMyLeaderboardEntry,"getMyLeaderboardEntry").call(o,t),listHistories:t=>c(o.listHistories,"listHistories").call(o,t),getXConnection:()=>c(o.getXConnection,"getXConnection").call(o),connectX:t=>c(o.connectX,"connectX").call(o,t),disconnectX:()=>c(o.disconnectX,"disconnectX").call(o),submitFeedback:t=>c(o.submitFeedback,"submitFeedback").call(o,t),setRevealYou:t=>c(o.setRevealYou,"setRevealYou").call(o,{revealYou:t}),requestRecipientChangeSignature:t=>c(o.requestRecipientChangeSignature,"requestRecipientChangeSignature").call(o,t),requestRecipientResetSignature:t=>c(o.requestRecipientResetSignature,"requestRecipientResetSignature").call(o,t),batchClaim:t=>d.execute(t),requestBatchClaimSignature:t=>c(o.requestBatchClaimSignature,"requestBatchClaimSignature").call(o,t)}}export{i as a,g as b,C as c,b as d,M as e,H as f,y as g,f as h,P as i,S as j,z as k};
|