@nexus-cross/pop 1.3.10-beta.2 → 1.4.0-beta.1

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.
@@ -1,4 +1,4 @@
1
- import { C as CryptoPort, g as Secret, t as SecretHash, H as Hex, A as Address, d as ClaimSignerPort, S as SafeDropChainPort, k as DropState, I as Id, a as SafeDropApiPort, u as SocialIdentifier, O as OAuthProof, i as DropInbox, E as Envelope, L as LeaderboardEntry, n as PopEventName, m as HistoryPage, X as XConnection, h as BatchClaimSignature, o as SafeDrop } from '../createSafeDrop-qoNG59jB.js';
1
+ import { C as CryptoPort, g as Secret, u as SecretHash, H as Hex, A as Address, d as ClaimSignerPort, S as SafeDropChainPort, n as OnePopDrop, I as Id, k as DropState, a as SafeDropApiPort, v as SocialIdentifier, O as OAuthProof, i as DropInbox, E as Envelope, L as LeaderboardEntry, o as PopEventName, m as HistoryPage, X as XConnection, h as BatchClaimSignature, p as SafeDrop } from '../createSafeDrop-BSO9RQBD.js';
2
2
  import { PublicClient, WalletClient, Chain, Transport } from 'viem';
3
3
  import { X as XAuthPort, a as XTokenResult } from '../XAuthPort-BNJePosj.js';
4
4
 
@@ -72,6 +72,17 @@ declare class ViemSafeDropChainAdapter implements SafeDropChainPort {
72
72
  */
73
73
  readonly depositWithPermit?: SafeDropChainPort['depositWithPermit'];
74
74
  constructor(options: ViemSafeDropChainAdapterOptions);
75
+ getDropByKey(dropKey: Hex): Promise<OnePopDrop | null>;
76
+ getDropKeyByClaimAddress(claimAddress: Address, sponsor?: Address): Promise<Hex | null>;
77
+ getPendingDropsById(params: {
78
+ id: Id;
79
+ }): Promise<readonly OnePopDrop[]>;
80
+ getPendingDropsByRecipient(params: {
81
+ recipient: Address;
82
+ }): Promise<readonly OnePopDrop[]>;
83
+ getPendingDropsBySponsor(params: {
84
+ sponsor: Address;
85
+ }): Promise<readonly OnePopDrop[]>;
75
86
  /**
76
87
  * drops(claimAddr). 배포본에 따라 반환 필드가 8개(Foundry ABI) 또는 5개(permit
77
88
  * 배포본)다 — 셀렉터가 같으므로 raw call 1회 후 디코딩만 나눈다. 8필드를 먼저
@@ -104,6 +115,14 @@ declare class ViemSafeDropChainAdapter implements SafeDropChainPort {
104
115
  * 이 배포본의 deposit에는 token 인자가 없다 — 컨트랙트가 token()으로 고정한다.
105
116
  */
106
117
  private permitDeposit;
118
+ depositMapped(params: {
119
+ token: Address;
120
+ amount: bigint;
121
+ id: Id;
122
+ onSubmitted?: (txHash: Hex) => void | Promise<void>;
123
+ }): Promise<{
124
+ txHash: Hex;
125
+ }>;
107
126
  /**
108
127
  * permit 서명 도메인. EIP-5267 eip712Domain()이 있으면 그 값을 쓰고, 없으면
109
128
  * name() + version '1'로 폴백한다. version을 상수로 박으면 다른 버전을 쓰는
@@ -118,6 +137,21 @@ declare class ViemSafeDropChainAdapter implements SafeDropChainPort {
118
137
  signature: Hex;
119
138
  secret: Secret;
120
139
  }): Promise<Hex>;
140
+ withdrawUnmapped(params: {
141
+ claimKey: Hex;
142
+ recipient: Address;
143
+ id: Id;
144
+ dropKey: Hex;
145
+ secret: Secret;
146
+ onSubmitted?: (txHash: Hex) => void | Promise<void>;
147
+ }): Promise<Hex>;
148
+ withdrawMapped(params: {
149
+ dropKey: Hex;
150
+ onSubmitted?: (txHash: Hex) => void | Promise<void>;
151
+ }): Promise<Hex>;
152
+ batchWithdrawMapped(params: {
153
+ count: number;
154
+ }): Promise<Hex>;
121
155
  /** validatorNonceById는 **bytes32(id 해시)** 로 키잉된다 — 원문 string이 아니다. */
122
156
  getValidatorNonce(params: {
123
157
  id: Id;
@@ -153,6 +187,18 @@ declare class ViemSafeDropChainAdapter implements SafeDropChainPort {
153
187
  refund(params: {
154
188
  claimAddress: Address;
155
189
  }): Promise<Hex>;
190
+ refundByKey(params: {
191
+ dropKey: Hex;
192
+ }): Promise<Hex>;
193
+ getChangeNonce(params: {
194
+ id: Id;
195
+ }): Promise<bigint>;
196
+ resetRecipient(params: {
197
+ id: Id;
198
+ nonce: bigint;
199
+ deadline: bigint;
200
+ signature: Hex;
201
+ }): Promise<Hex>;
156
202
  private sponsorWrite;
157
203
  private confirm;
158
204
  private recoverRevertName;
@@ -176,6 +222,8 @@ type PopEnvironment = 'dev' | 'stage' | 'production';
176
222
  interface PopApiPaths {
177
223
  /** POST — 임시 claim 지갑 생성 (Bearer JWT). */
178
224
  createWallet: string;
225
+ /** POST — tx hash에 메시지/봉투 메타데이터 연결 (Bearer JWT). */
226
+ dropMetadata: string;
179
227
  /** POST — pending 지갑 개인키 수령 (X OAuth 토큰). */
180
228
  retrievePrivateKey: string;
181
229
  /** GET — 수령 대기 인박스 (Bearer JWT + 활성 X 연결). */
@@ -236,11 +284,22 @@ declare class HttpSafeDropApiAdapter implements SafeDropApiPort {
236
284
  envelopeId?: string;
237
285
  }): Promise<{
238
286
  claimAddress: Address;
287
+ id: Id;
288
+ isMapped: boolean;
239
289
  }>;
290
+ recordDropMetadata(params: {
291
+ txHash: Hex;
292
+ message?: string;
293
+ envelopeId?: string;
294
+ }): Promise<void>;
240
295
  retrieveClaimKey(params: {
296
+ claimAddress: Address;
241
297
  senderAddress: Address;
242
298
  oauth: OAuthProof;
243
299
  }): Promise<{
300
+ isMapped: true;
301
+ } | {
302
+ isMapped: false;
244
303
  claimKey: Hex;
245
304
  claimAddress: Address;
246
305
  }>;
@@ -1028,6 +1087,286 @@ declare const SAFEDROP_VALIDATOR_ABI: readonly [{
1028
1087
  readonly inputs: readonly [];
1029
1088
  }];
1030
1089
 
1090
+ /** Current ONEpop mapped/unmapped deployment ABI used by the SDK. */
1091
+ declare const ONEPOP_ABI: readonly [{
1092
+ readonly type: "function";
1093
+ readonly name: "activeDropOf";
1094
+ readonly stateMutability: "view";
1095
+ readonly inputs: readonly [{
1096
+ readonly name: "claimAddr";
1097
+ readonly type: "address";
1098
+ }];
1099
+ readonly outputs: readonly [{
1100
+ readonly type: "bytes32";
1101
+ }];
1102
+ }, {
1103
+ readonly type: "function";
1104
+ readonly name: "drops";
1105
+ readonly stateMutability: "view";
1106
+ readonly inputs: readonly [{
1107
+ readonly name: "dropKey";
1108
+ readonly type: "bytes32";
1109
+ }];
1110
+ readonly outputs: readonly [{
1111
+ readonly name: "sponsor";
1112
+ readonly type: "address";
1113
+ }, {
1114
+ readonly name: "amount";
1115
+ readonly type: "uint96";
1116
+ }, {
1117
+ readonly name: "claimAddr";
1118
+ readonly type: "address";
1119
+ }, {
1120
+ readonly name: "recipient";
1121
+ readonly type: "address";
1122
+ }, {
1123
+ readonly name: "secretHash";
1124
+ readonly type: "bytes32";
1125
+ }, {
1126
+ readonly name: "id";
1127
+ readonly type: "string";
1128
+ }];
1129
+ }, {
1130
+ readonly type: "function";
1131
+ readonly name: "token";
1132
+ readonly stateMutability: "view";
1133
+ readonly inputs: readonly [];
1134
+ readonly outputs: readonly [{
1135
+ readonly type: "address";
1136
+ }];
1137
+ }, {
1138
+ readonly type: "function";
1139
+ readonly name: "claimDigest";
1140
+ readonly stateMutability: "view";
1141
+ readonly inputs: readonly [{
1142
+ readonly name: "recipient";
1143
+ readonly type: "address";
1144
+ }, {
1145
+ readonly name: "id";
1146
+ readonly type: "string";
1147
+ }, {
1148
+ readonly name: "dropKey";
1149
+ readonly type: "bytes32";
1150
+ }];
1151
+ readonly outputs: readonly [{
1152
+ readonly type: "bytes32";
1153
+ }];
1154
+ }, {
1155
+ readonly type: "function";
1156
+ readonly name: "claimedRecipientOf";
1157
+ readonly stateMutability: "view";
1158
+ readonly inputs: readonly [{
1159
+ readonly name: "id";
1160
+ readonly type: "string";
1161
+ }];
1162
+ readonly outputs: readonly [{
1163
+ readonly type: "address";
1164
+ }];
1165
+ }, {
1166
+ readonly type: "function";
1167
+ readonly name: "pendingDropsByXid";
1168
+ readonly stateMutability: "view";
1169
+ readonly inputs: readonly [{
1170
+ readonly name: "id";
1171
+ readonly type: "string";
1172
+ }];
1173
+ readonly outputs: readonly [{
1174
+ readonly name: "dropKeys";
1175
+ readonly type: "bytes32[]";
1176
+ }, {
1177
+ readonly name: "records";
1178
+ readonly type: "tuple[]";
1179
+ readonly components: readonly [{
1180
+ readonly name: "sponsor";
1181
+ readonly type: "address";
1182
+ }, {
1183
+ readonly name: "amount";
1184
+ readonly type: "uint96";
1185
+ }, {
1186
+ readonly name: "claimAddr";
1187
+ readonly type: "address";
1188
+ }, {
1189
+ readonly name: "recipient";
1190
+ readonly type: "address";
1191
+ }, {
1192
+ readonly name: "secretHash";
1193
+ readonly type: "bytes32";
1194
+ }, {
1195
+ readonly name: "id";
1196
+ readonly type: "string";
1197
+ }];
1198
+ }];
1199
+ }, {
1200
+ readonly type: "function";
1201
+ readonly name: "pendingDropsByRecipient";
1202
+ readonly stateMutability: "view";
1203
+ readonly inputs: readonly [{
1204
+ readonly name: "recipient";
1205
+ readonly type: "address";
1206
+ }];
1207
+ readonly outputs: readonly [{
1208
+ readonly name: "dropKeys";
1209
+ readonly type: "bytes32[]";
1210
+ }, {
1211
+ readonly name: "records";
1212
+ readonly type: "tuple[]";
1213
+ readonly components: readonly [{
1214
+ readonly name: "sponsor";
1215
+ readonly type: "address";
1216
+ }, {
1217
+ readonly name: "amount";
1218
+ readonly type: "uint96";
1219
+ }, {
1220
+ readonly name: "claimAddr";
1221
+ readonly type: "address";
1222
+ }, {
1223
+ readonly name: "recipient";
1224
+ readonly type: "address";
1225
+ }, {
1226
+ readonly name: "secretHash";
1227
+ readonly type: "bytes32";
1228
+ }, {
1229
+ readonly name: "id";
1230
+ readonly type: "string";
1231
+ }];
1232
+ }];
1233
+ }, {
1234
+ readonly type: "function";
1235
+ readonly name: "pendingDropsOf";
1236
+ readonly stateMutability: "view";
1237
+ readonly inputs: readonly [{
1238
+ readonly name: "sponsor";
1239
+ readonly type: "address";
1240
+ }];
1241
+ readonly outputs: readonly [{
1242
+ readonly name: "dropKeys";
1243
+ readonly type: "bytes32[]";
1244
+ }, {
1245
+ readonly name: "records";
1246
+ readonly type: "tuple[]";
1247
+ readonly components: readonly [{
1248
+ readonly name: "sponsor";
1249
+ readonly type: "address";
1250
+ }, {
1251
+ readonly name: "amount";
1252
+ readonly type: "uint96";
1253
+ }, {
1254
+ readonly name: "claimAddr";
1255
+ readonly type: "address";
1256
+ }, {
1257
+ readonly name: "recipient";
1258
+ readonly type: "address";
1259
+ }, {
1260
+ readonly name: "secretHash";
1261
+ readonly type: "bytes32";
1262
+ }, {
1263
+ readonly name: "id";
1264
+ readonly type: "string";
1265
+ }];
1266
+ }];
1267
+ }, {
1268
+ readonly type: "function";
1269
+ readonly name: "depositMapped";
1270
+ readonly stateMutability: "nonpayable";
1271
+ readonly inputs: readonly [{
1272
+ readonly name: "amount";
1273
+ readonly type: "uint256";
1274
+ }, {
1275
+ readonly name: "id";
1276
+ readonly type: "string";
1277
+ }, {
1278
+ readonly name: "permitDeadline";
1279
+ readonly type: "uint256";
1280
+ }, {
1281
+ readonly name: "v";
1282
+ readonly type: "uint8";
1283
+ }, {
1284
+ readonly name: "r";
1285
+ readonly type: "bytes32";
1286
+ }, {
1287
+ readonly name: "s";
1288
+ readonly type: "bytes32";
1289
+ }];
1290
+ readonly outputs: readonly [];
1291
+ }, {
1292
+ readonly type: "function";
1293
+ readonly name: "withdrawUnmapped";
1294
+ readonly stateMutability: "nonpayable";
1295
+ readonly inputs: readonly [{
1296
+ readonly name: "recipient";
1297
+ readonly type: "address";
1298
+ }, {
1299
+ readonly name: "id";
1300
+ readonly type: "string";
1301
+ }, {
1302
+ readonly name: "dropKey";
1303
+ readonly type: "bytes32";
1304
+ }, {
1305
+ readonly name: "signature";
1306
+ readonly type: "bytes";
1307
+ }, {
1308
+ readonly name: "secret";
1309
+ readonly type: "bytes";
1310
+ }];
1311
+ readonly outputs: readonly [];
1312
+ }, {
1313
+ readonly type: "function";
1314
+ readonly name: "withdrawMapped";
1315
+ readonly stateMutability: "nonpayable";
1316
+ readonly inputs: readonly [{
1317
+ readonly name: "dropKey";
1318
+ readonly type: "bytes32";
1319
+ }];
1320
+ readonly outputs: readonly [];
1321
+ }, {
1322
+ readonly type: "function";
1323
+ readonly name: "batchWithdrawMapped";
1324
+ readonly stateMutability: "nonpayable";
1325
+ readonly inputs: readonly [{
1326
+ readonly name: "count";
1327
+ readonly type: "uint256";
1328
+ }];
1329
+ readonly outputs: readonly [];
1330
+ }, {
1331
+ readonly type: "function";
1332
+ readonly name: "refund";
1333
+ readonly stateMutability: "nonpayable";
1334
+ readonly inputs: readonly [{
1335
+ readonly name: "dropKey";
1336
+ readonly type: "bytes32";
1337
+ }];
1338
+ readonly outputs: readonly [];
1339
+ }, {
1340
+ readonly type: "function";
1341
+ readonly name: "changeNonceById";
1342
+ readonly stateMutability: "view";
1343
+ readonly inputs: readonly [{
1344
+ readonly name: "idKey";
1345
+ readonly type: "bytes32";
1346
+ }];
1347
+ readonly outputs: readonly [{
1348
+ readonly type: "uint256";
1349
+ }];
1350
+ }, {
1351
+ readonly type: "function";
1352
+ readonly name: "resetRecipient";
1353
+ readonly stateMutability: "nonpayable";
1354
+ readonly inputs: readonly [{
1355
+ readonly name: "id";
1356
+ readonly type: "string";
1357
+ }, {
1358
+ readonly name: "nonce";
1359
+ readonly type: "uint256";
1360
+ }, {
1361
+ readonly name: "deadline";
1362
+ readonly type: "uint256";
1363
+ }, {
1364
+ readonly name: "validatorSignature";
1365
+ readonly type: "bytes";
1366
+ }];
1367
+ readonly outputs: readonly [];
1368
+ }];
1369
+
1031
1370
  /**
1032
1371
  * cross-auth SIWE 로그인 클라이언트. createClaimWallet에 필요한 플랫폼 JWT를 얻는다.
1033
1372
  * 1) unsignedHash(chainId, address) → { hash, message }
@@ -1172,4 +1511,4 @@ declare class XAuthClient {
1172
1511
  }>;
1173
1512
  }
1174
1513
 
1175
- export { type CreateSafeDropClientOptions, CrossAuthClient, type CrossAuthClientOptions, DEFAULT_POP_API_PATHS, HttpSafeDropApiAdapter, type HttpSafeDropApiAdapterOptions, HttpXAuthAdapter, type HttpXAuthAdapterOptions, type Pkce, type PopApiPaths, type PopEnvironment, SAFEDROP_ABI, SAFEDROP_VALIDATOR_ABI, type SessionStore, ViemClaimSignerAdapter, ViemCryptoAdapter, ViemSafeDropChainAdapter, type ViemSafeDropChainAdapterOptions, XAuthClient, type XAuthClientOptions, createSafeDropClient, generatePkce, generateState, getCrossAuthBaseUrl, getOnePopApiBaseUrl };
1514
+ 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 SessionStore, ViemClaimSignerAdapter, ViemCryptoAdapter, ViemSafeDropChainAdapter, type ViemSafeDropChainAdapterOptions, XAuthClient, type XAuthClientOptions, createSafeDropClient, generatePkce, generateState, getCrossAuthBaseUrl, getOnePopApiBaseUrl };
@@ -1 +1 @@
1
- import{a as s,k as B}from"../chunk-KEW4FB4S.js";import{bytesToHex as Y,keccak256 as Q,recoverAddress as ee,toBytes as te}from"viem";var h=class{keccak256(e){return Q(te(e))}randomSecret(){let e=new Uint8Array(32);return ne().getRandomValues(e),Y(e).slice(2)}recoverAddress(e){return ee({hash:e.digest,signature:e.signature})}};function ne(){let r=globalThis.crypto;if(!r||typeof r.getRandomValues!="function")throw new Error("Secure crypto RNG (globalThis.crypto.getRandomValues) is unavailable");return r}import{serializeSignature as re,sign as ie}from"viem/accounts";var g=class{async signDigest(e){try{let t=await ie({hash:e.digest,privateKey:e.claimKey});return re(t)}catch(t){throw new s("SIGN_FAILED","Failed to sign claim digest with temp key",{cause:t instanceof Error?t.message:String(t)})}}};import{BaseError as se,ContractFunctionRevertedError as F,createWalletClient as ae,decodeFunctionResult as X,encodeFunctionData as oe,http as de,keccak256 as pe,parseSignature as ce,toBytes as $,toHex as ue}from"viem";import{privateKeyToAccount as le}from"viem/accounts";var b=[{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"}]}],L=[{type:"function",name:"drops",stateMutability:"view",inputs:[{name:"claimAddr",type:"address"}],outputs:[{name:"sponsor",type:"address"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"},{name:"salt",type:"bytes32"},{name:"id",type:"string"}]}],A=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"nonces",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"eip712Domain",stateMutability:"view",inputs:[],outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}]}],M={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]};var u=[{type:"constructor",inputs:[{name:"claimPeriod_",type:"uint64",internalType:"uint64"}],stateMutability:"nonpayable"},{type:"function",name:"claimDigest",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"salt",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"claimPeriod",inputs:[],outputs:[{name:"",type:"uint64",internalType:"uint64"}],stateMutability:"view"},{type:"function",name:"claimedRecipientOf",inputs:[{name:"id",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"deposit",inputs:[{name:"claimAddr",type:"address",internalType:"address"},{name:"token",type:"address",internalType:"contract IERC20"},{name:"amount",type:"uint256",internalType:"uint256"},{name:"id",type:"string",internalType:"string"},{name:"secretHash",type:"bytes32",internalType:"bytes32"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"depositCountOf",inputs:[{name:"sponsor",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"depositsBySponsor",inputs:[{name:"sponsor",type:"address",internalType:"address"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"claimAddr",type:"address",internalType:"address"},{name:"token",type:"address",internalType:"contract IERC20"},{name:"amount",type:"uint128",internalType:"uint128"},{name:"expiry",type:"uint64",internalType:"uint64"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"depositsOf",inputs:[{name:"sponsor",type:"address",internalType:"address"}],outputs:[{name:"",type:"tuple[]",internalType:"struct SafeDrop.DepositRecord[]",components:[{name:"claimAddr",type:"address",internalType:"address"},{name:"token",type:"address",internalType:"contract IERC20"},{name:"amount",type:"uint128",internalType:"uint128"},{name:"expiry",type:"uint64",internalType:"uint64"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]}],stateMutability:"view"},{type:"function",name:"drops",inputs:[{name:"claimAddr",type:"address",internalType:"address"}],outputs:[{name:"sponsor",type:"address",internalType:"address"},{name:"recordIndex",type:"uint96",internalType:"uint96"},{name:"token",type:"address",internalType:"contract IERC20"},{name:"amount",type:"uint128",internalType:"uint128"},{name:"expiry",type:"uint64",internalType:"uint64"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"salt",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:"liveClaimAddrsById",inputs:[{name:"id",type:"string",internalType:"string"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"liveDropCountById",inputs:[{name:"id",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"liveDropsById",inputs:[{name:"id",type:"string",internalType:"string"}],outputs:[{name:"claimAddrs",type:"address[]",internalType:"address[]"},{name:"records",type:"tuple[]",internalType:"struct SafeDrop.Drop[]",components:[{name:"sponsor",type:"address",internalType:"address"},{name:"recordIndex",type:"uint96",internalType:"uint96"},{name:"token",type:"address",internalType:"contract IERC20"},{name:"amount",type:"uint128",internalType:"uint128"},{name:"expiry",type:"uint64",internalType:"uint64"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"salt",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]}],stateMutability:"view"},{type:"function",name:"refund",inputs:[{name:"claimAddr",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"unclaimedCountOf",inputs:[{name:"sponsor",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"unclaimedDepositsOf",inputs:[{name:"sponsor",type:"address",internalType:"address"}],outputs:[{name:"records",type:"tuple[]",internalType:"struct SafeDrop.DepositRecord[]",components:[{name:"claimAddr",type:"address",internalType:"address"},{name:"token",type:"address",internalType:"contract IERC20"},{name:"amount",type:"uint128",internalType:"uint128"},{name:"expiry",type:"uint64",internalType:"uint64"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]}],stateMutability:"view"},{type:"function",name:"unclaimedIndexesOf",inputs:[{name:"sponsor",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256[]",internalType:"uint256[]"}],stateMutability:"view"},{type:"function",name:"withdraw",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"salt",type:"bytes32",internalType:"bytes32"},{name:"signature",type:"bytes",internalType:"bytes"},{name:"secret",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"Deposited",inputs:[{name:"claimAddr",type:"address",indexed:!0,internalType:"address"},{name:"sponsor",type:"address",indexed:!0,internalType:"address"},{name:"token",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"id",type:"string",indexed:!1,internalType:"string"},{name:"expiry",type:"uint64",indexed:!1,internalType:"uint64"},{name:"secretHash",type:"bytes32",indexed:!1,internalType:"bytes32"}],anonymous:!1},{type:"event",name:"EIP712DomainChanged",inputs:[],anonymous:!1},{type:"event",name:"Refunded",inputs:[{name:"claimAddr",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"}],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"}],anonymous:!1},{type:"error",name:"AmountOverflow",inputs:[]},{type:"error",name:"DropAlreadyExists",inputs:[]},{type:"error",name:"DropExpired",inputs:[]},{type:"error",name:"DropNotExpired",inputs:[]},{type:"error",name:"DropNotFound",inputs:[]},{type:"error",name:"DuplicateDropForId",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:"InvalidShortString",inputs:[]},{type:"error",name:"NotSponsor",inputs:[]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]},{type:"error",name:"SaltMismatch",inputs:[]},{type:"error",name:"SecretMismatch",inputs:[]},{type:"error",name:"StringTooLong",inputs:[{name:"str",type:"string",internalType:"string"}]},{type:"error",name:"ZeroAmount",inputs:[]},{type:"error",name:"ZeroClaimAddress",inputs:[]},{type:"error",name:"ZeroRecipient",inputs:[]},{type:"error",name:"ZeroToken",inputs:[]}];var l=[{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:"withdrawByValidator",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"id",type:"string"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"maxCount",type:"uint256"},{name:"signature",type:"bytes"}],outputs:[]},{type:"function",name:"liveDropCountById",stateMutability:"view",inputs:[{name:"id",type:"string"}],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 me=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],ye="0x0000000000000000000000000000000000000000",he={gas:BigInt(3e5),maxFeePerGas:BigInt(4e9),maxPriorityFeePerGas:BigInt(1e9)},ge=BigInt(3600),f=class{constructor(e){this.address=e.address,this.publicClient=e.publicClient,this.walletClient=e.walletClient,this.chain=e.chain,this.transport=e.transport??de(),this.withdrawFees={...he,...e.withdrawFees},e.permit&&(this.depositWithPermit=t=>this.permitDeposit(t))}async getDrop(e){try{let{data:t}=await this.publicClient.call({to:this.address,data:oe({abi:u,functionName:"drops",args:[e]})});if(!t||t==="0x")return null;let n;try{let[i,,o,d,c,m,T,_]=X({abi:u,functionName:"drops",data:t});n={claimAddress:e,sponsor:i,token:o,amount:d,expiry:Number(c),secretHash:m,salt:T,id:_}}catch{let[i,o,d,c,m]=X({abi:L,functionName:"drops",data:t});n={claimAddress:e,sponsor:i,amount:o,secretHash:d,salt:c,id:m}}return!n.sponsor||n.sponsor.toLowerCase()===ye?null:(n.token||(n.token=await this.escrowToken()),n)}catch(t){throw p("getDrop",t)}}async escrowToken(){try{return await this.publicClient.readContract({address:this.address,abi:b,functionName:"token"})}catch{return}}async getClaimDigest(e){try{return await this.publicClient.readContract({address:this.address,abi:u,functionName:"claimDigest",args:[e.recipient,e.id,e.salt]})}catch(t){throw p("claimDigest",t)}}async approve(e){return this.sponsorWrite("approve",()=>this.walletClient.writeContract({address:e.token,abi:me,functionName:"approve",args:[this.address,e.amount],account:this.requireAccount(),chain:this.chain}))}async deposit(e){let t=[e.claimAddress,e.token,e.amount,e.id,e.secretHash];try{await this.publicClient.simulateContract({address:this.address,abi:u,functionName:"deposit",args:t,account:this.requireAccount()})}catch(i){throw p("deposit",i)}return{txHash:await this.sponsorWrite("deposit",()=>this.walletClient.writeContract({address:this.address,abi:u,functionName:"deposit",args:t,account:this.requireAccount(),chain:this.chain}))}}async permitDeposit(e){try{let t=this.requireAccount(),n=e.token,[i,o,d]=await Promise.all([this.publicClient.readContract({address:this.address,abi:b,functionName:"token"}),this.publicClient.readContract({address:n,abi:A,functionName:"nonces",args:[t.address]}),this.permitDomain(n)]);if(i.toLowerCase()!==n.toLowerCase())throw new s("INVALID_TOKEN","token does not match the escrow token",{expected:i,received:e.token});let c=BigInt(Math.floor(Date.now()/1e3))+ge,m=await this.walletClient.signTypedData({account:t,domain:{...d,chainId:this.chain.id,verifyingContract:n},types:M,primaryType:"Permit",message:{owner:t.address,spender:this.address,value:e.amount,nonce:o,deadline:c}}),{r:T,s:_,v:J,yParity:Z}=ce(m),V=await this.walletClient.writeContract({address:this.address,abi:b,functionName:"deposit",args:[e.claimAddress,e.amount,e.id,e.secretHash,c,Number(J??BigInt(Z+27)),T,_],account:t,chain:this.chain});return await this.confirm("depositWithPermit",V),{txHash:V}}catch(t){throw p("depositWithPermit",t)}}async permitDomain(e){try{let t=await this.publicClient.readContract({address:e,abi:A,functionName:"eip712Domain"});return{name:t[1],version:t[2]}}catch{return{name:await this.publicClient.readContract({address:e,abi:A,functionName:"name"}),version:"1"}}}async withdraw(e){try{let t=le(e.claimKey),i=await ae({account:t,chain:this.chain,transport:this.transport}).writeContract({address:this.address,abi:u,functionName:"withdraw",args:[e.recipient,e.id,e.salt,e.signature,ue($(e.secret))],gas:this.withdrawFees.gas,maxFeePerGas:this.withdrawFees.maxFeePerGas,maxPriorityFeePerGas:this.withdrawFees.maxPriorityFeePerGas});return await this.confirm("withdraw",i),i}catch(t){throw p("withdraw",t)}}async getValidatorNonce(e){try{return await this.publicClient.readContract({address:this.address,abi:l,functionName:"validatorNonceById",args:[pe($(e.id))]})}catch(t){throw p("validatorNonceById",t)}}async getValidatorClaimDigest(e){try{return await this.publicClient.readContract({address:this.address,abi:l,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:l,functionName:"validator"})}catch(e){throw p("validator",e)}}async getClaimedRecipient(e){try{return await this.publicClient.readContract({address:this.address,abi:l,functionName:"claimedRecipientOf",args:[e.id]})}catch(t){throw p("claimedRecipientOf",t)}}async getLiveDropCount(e){try{return await this.publicClient.readContract({address:this.address,abi:l,functionName:"liveDropCountById",args:[e.id]})}catch(t){throw p("liveDropCountById",t)}}async withdrawByValidator(e){let t=[e.recipient,e.id,e.nonce,e.deadline,BigInt(e.maxCount),e.signature],n=this.requireAccount();if(n.address.toLowerCase()!==e.recipient.toLowerCase())throw new s("CHAIN_ERROR","withdrawByValidator must be sent by the recipient wallet",{connected:n.address,recipient:e.recipient});try{await this.publicClient.simulateContract({address:this.address,abi:l,functionName:"withdrawByValidator",args:t,account:n})}catch(i){throw p("withdrawByValidator",i)}return this.sponsorWrite("withdrawByValidator",()=>this.walletClient.writeContract({address:this.address,abi:l,functionName:"withdrawByValidator",args:t,account:n,chain:this.chain}))}async refund(e){return this.sponsorWrite("refund",()=>this.walletClient.writeContract({address:this.address,abi:u,functionName:"refund",args:[e.claimAddress],account:this.requireAccount(),chain:this.chain}))}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 i=await this.recoverRevertName(t,n.blockNumber),o=i?`SafeDrop.${e} reverted: ${i}`:`transaction reverted: ${t}`;throw new s("CHAIN_ERROR",o,{revertName:i,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 q(n)}}requireAccount(){let e=this.walletClient.account;if(!e)throw new s("CHAIN_ERROR","walletClient has no account (connect a wallet first)");return e}};function p(r,e){if(e instanceof s)return e;let t=q(e),n=e instanceof Error?e.message:String(e),i=t?`SafeDrop.${r} reverted: ${t}`:`SafeDrop.${r} failed`;return new s("CHAIN_ERROR",i,{cause:n,revertName:t})}function q(r){if(!(r instanceof se))return;let e=r.walk(t=>t instanceof F);if(e instanceof F)return e.data?.errorName??e.reason??void 0}var fe={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"},C={createWallet:"/wallets",retrievePrivateKey:"/wallets/private-key",drops:"/drops",envelopes:"/envelopes",leaderboards:"/leaderboards",histories:"/histories",xConnections:"/x-connections",batchClaimSignature:"/batch-claim-signature",eventsSubscribe:"/events/subscribe"},we="https://dev-cross-auth.crosstoken.io";function E(r){try{return import.meta.env?.[r]}catch{return}}function P(r){if(!(typeof process>"u"||!process.env))switch(r){case"NEXT_PUBLIC_ONE_POP_ENVIRONMENT":return process.env.NEXT_PUBLIC_ONE_POP_ENVIRONMENT;case"ONE_POP_ENVIRONMENT":return process.env.ONE_POP_ENVIRONMENT;case"NEXT_PUBLIC_ONE_POP_API_BASE_URL":return process.env.NEXT_PUBLIC_ONE_POP_API_BASE_URL;case"NEXT_PUBLIC_CROSS_AUTH_URL":return process.env.NEXT_PUBLIC_CROSS_AUTH_URL;default:return}}function be(){switch((E("VITE_ONE_POP_ENVIRONMENT")??P("NEXT_PUBLIC_ONE_POP_ENVIRONMENT")??P("ONE_POP_ENVIRONMENT"))?.toLowerCase()){case"dev":case"development":return"dev";case"stg":case"stage":case"staging":return"stage";default:return"production"}}function I(){let e=E("VITE_ONE_POP_API_BASE_URL")??P("NEXT_PUBLIC_ONE_POP_API_BASE_URL")??fe[be()];return W(e),e}function S(){let e=(E("VITE_CROSS_AUTH_URL")??P("NEXT_PUBLIC_CROSS_AUTH_URL")??we).replace(/\/+$/,"");return W(e),e}function W(r){let e;try{e=new URL(r)}catch{throw new Error(`[pop] Invalid base URL: ${r}`)}if(e.protocol==="https:")return;let t=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname.endsWith(".local");if(!(e.protocol==="http:"&&t))throw new Error(`[pop] base URL must be https (or http://localhost for dev). Got: ${r}`)}var Ae={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",X_CONNECTION_NOT_FOUND:"X_CONNECTION_NOT_FOUND"},G=140,w=class{constructor(e={}){this.baseUrl=(e.baseUrl??I()).replace(/\/+$/,"");let t=e.fetchImpl??globalThis.fetch;if(!t)throw new Error("fetch is unavailable; provide options.fetchImpl");this.fetchImpl=t,this.getJwt=e.getJwt,this.paths={...C,...e.paths}}async createClaimWallet(e){if(e.message&&[...e.message].length>G)throw new s("INVALID_PARAM",`message must be <= ${G} runes`,{length:[...e.message].length});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,...e.message?{message:e.message}:{},...e.envelopeId?{envelope_id:e.envelopeId}:{}}});if(!t?.address)throw new s("API_ERROR","createClaimWallet: missing address in response",{body:t});return{claimAddress:t.address}}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}});if(!t?.private_key||!t.address)throw new s("API_ERROR","retrieveClaimKey: missing key/address in response",{body:t});return{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(Te),count:t?.count??0,totalAmount:y(t?.total_amount,"drops.total_amount"),hasClaimedBefore:t?.has_claimed_before===!0}}async listEnvelopes(e={}){return((await this.request(this.paths.envelopes,{method:"GET",query:{locale:e.locale}}))?.items??[]).map(n=>({id:a(n.id),name:a(n.name),imageUrl:a(n.image_url),badge:a(n.badge),sortOrder:Number(n.sort_order??0)}))}async getLeaderboard(e){if(!e.token)throw new s("INVALID_PARAM","getLeaderboard requires a token address");return((await this.request(this.paths.leaderboards,{method:"GET",query:{token:e.token}}))?.items??[]).map(n=>({identifier:a(n.identifier),balance:y(n.balance,"leaderboard.balance"),lastDepositAmount:y(n.last_deposit_amount,"leaderboard.last_deposit_amount")}))}async listHistories(e={}){let t=await this.request(this.paths.histories,{method:"GET",auth:!0,query:{event:e.event,page:e.page,page_size:e.pageSize}});return{items:(t?.items??[]).map(n=>({eventName:a(n.event_name),txHash:a(n.tx_hash),blockNumber:Number(n.block_number??0),logIndex:Number(n.log_index??0),contractAddress:a(n.contract_address),fromAddress:v(n.from_address),toAddress:v(n.to_address),tempTo:v(n.temp_to),identifier:a(n.identifier),amount:y(n.amount,"history.amount"),createdAt:a(n.created_at),payload:n.payload??void 0})),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?K(e):null}async connectX(e){let t=await this.request(this.paths.xConnections,{method:"POST",auth:!0,payload:{oauth_token:e.oauth.accessToken}});return K(t??{})}async disconnectX(){await this.request(this.paths.xConnections,{method:"DELETE",auth:!0,notFoundAsNull:!0})}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=a(t?.signature);if(!n)throw new s("API_ERROR","requestBatchClaimSignature: missing signature",{body:t});return{id:a(t?.id)||e.id,recipient:a(t?.recipient),nonce:j(t?.nonce)?y(t?.nonce,"batchClaim.nonce"):e.nonce,deadline:j(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 o=await this.getJwt?.();if(!o)throw new s("UNAUTHORIZED",`${e} requires a SIWE JWT (options.getJwt)`);n.Authorization=`Bearer ${o}`}let i;try{i=await this.fetchImpl(`${this.baseUrl}${e}${Pe(t.query)}`,{method:t.method,headers:n,body:t.payload?JSON.stringify(t.payload):void 0})}catch(o){throw new s("API_ERROR",`Network error calling ${e}`,{cause:o instanceof Error?o.message:String(o)})}if(i.status===404&&t.notFoundAsNull)return null;if(!i.ok){let o=await i.json().catch(()=>{}),d=o?.code_name;throw new s((d?Ae[d]:void 0)??"API_ERROR",o?.message?`${e}: ${o.message}`:`${e} responded ${i.status}`,{status:i.status,code:o?.code,codeName:d})}return i.status===204?null:await i.json().catch(()=>null)}};function Pe(r){if(!r)return"";let e=new URLSearchParams;for(let[n,i]of Object.entries(r))i!==void 0&&i!==""&&e.set(n,String(i));let t=e.toString();return t?`?${t}`:""}function j(r){return r!=null&&r!==""}function a(r){return typeof r=="string"?r:""}function v(r){return typeof r=="string"&&r?r:null}function y(r,e){if(typeof r=="bigint")return r;if(typeof r=="number"){if(!Number.isSafeInteger(r))throw new s("API_ERROR",`${e} exceeds safe-integer precision as a JSON number`,{value:r});return BigInt(r)}let t=typeof r=="string"?r.trim():"";if(!t)return BigInt(0);try{return BigInt(t)}catch{throw new s("API_ERROR",`${e} is not a valid decimal string`,{value:r})}}function Te(r){let e=r??{},t=e.sender??{};return{claimAddress:a(e.claim_address),token:a(e.token),amount:y(e.amount,"drop.amount"),message:a(e.message),envelopeId:a(e.envelope_id),depositedAt:a(e.deposited_at),sender:{address:a(t.address),handle:a(t.handle),displayName:a(t.display_name),profileImageUrl:a(t.profile_image_url)}}}function K(r){return{xUserId:a(r.x_user_id),handle:a(r.handle),displayName:a(r.display_name),profileImageUrl:a(r.profile_image_url),walletAddress:a(r.wallet_address)}}var R=class{constructor(e={}){this.baseUrl=(e.baseUrl??S()).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(o){throw new s("API_ERROR",`cross-auth network error calling ${e}`,{cause:o instanceof Error?o.message:String(o)})}let i=await n.json().catch(()=>({}));if(!n.ok||i.data==null)throw new s("API_ERROR",`cross-auth ${e} failed`,{code:i.code,message:i.message});return i.data}};function _e(r){let e=r.apiPort??new w(r.api),t=new f({address:r.contractAddress,publicClient:r.publicClient,walletClient:r.walletClient,chain:r.chain,transport:r.transport,withdrawFees:r.withdrawFees,permit:r.permit});return B({claimBaseUrl:r.claimBaseUrl},{api:e,chain:t,signer:new g,crypto:new h})}async function O(){let r=x(z(32)),e=await Ce().digest("SHA-256",Ee(r)),t=x(new Uint8Array(e));return{verifier:r,challenge:t,method:"S256"}}function D(){return x(z(16))}function z(r){let e=globalThis.crypto;if(!e?.getRandomValues)throw new Error("crypto.getRandomValues unavailable");let t=new Uint8Array(r);return e.getRandomValues(t),t}function Ce(){let r=globalThis.crypto?.subtle;if(!r)throw new Error("crypto.subtle unavailable (needs https/secure context)");return r}function Ee(r){return new TextEncoder().encode(r)}function x(r){let e="";for(let n of r)e+=String.fromCharCode(n);let t=globalThis.btoa?.(e);if(t===void 0)throw new Error("btoa unavailable");return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var N=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 s("API_ERROR","X token exchange: missing access_token",{body:n});return{accessToken:n.access_token,scope:n.scope,expiresIn:n.expires_in,refreshToken:n.refresh_token}}async getHandle(e){let n=await(await this.call(this.mePath,{method:"GET",headers:{Authorization:`Bearer ${e}`}})).json().catch(()=>({})),i=n.data?.username??n.username;if(!i)throw new s("API_ERROR","X /me: missing username",{body:n});return{handle:i}}async call(e,t){let n;try{n=await this.fetchImpl(`${this.baseUrl}${e}`,t)}catch(i){throw new s("API_ERROR",`Network error calling ${e}`,{cause:i instanceof Error?i.message:String(i)})}if(!n.ok)throw new s("API_ERROR",`${e} responded ${n.status}`,{status:n.status});return n}};var k="pop.xauth.verifier",U="pop.xauth.state",Ie="https://x.com/i/oauth2/authorize",Se="tweet.read users.read offline.access",H=class{constructor(e){this.opts={clientId:e.clientId,redirectUri:e.redirectUri,scope:e.scope??Se,authorizeUrl:e.authorizeUrl??Ie,port:e.port,storage:e.storage??ve()}}async start(){let e=await O(),t=D();this.opts.storage.set(k,e.verifier),this.opts.storage.set(U,t);let n=new URLSearchParams({response_type:"code",client_id:this.opts.clientId,redirect_uri:this.opts.redirectUri,scope:this.opts.scope,state:t,code_challenge:e.challenge,code_challenge_method:"S256"});return{authorizeUrl:`${this.opts.authorizeUrl}?${n.toString()}`,state:t}}async complete(e){let t=new URL(e),n=t.searchParams.get("code"),i=t.searchParams.get("state");if(!n)throw new s("API_ERROR","X callback: missing authorization code",{error:t.searchParams.get("error")});let o=this.opts.storage.get(U);if(!i||!o||i!==o)throw new s("API_ERROR","X callback: state mismatch (possible CSRF)");let d=this.opts.storage.get(k);if(!d)throw new s("API_ERROR","X callback: missing PKCE verifier (expired session?)");let c=await this.opts.port.exchangeCode({clientId:this.opts.clientId,redirectUri:this.opts.redirectUri,code:n,codeVerifier:d}),{handle:m}=await this.opts.port.getHandle(c.accessToken);return this.opts.storage.remove(k),this.opts.storage.remove(U),{oauth:{provider:"x",accessToken:c.accessToken},handle:m}}};function ve(){let r=globalThis.sessionStorage;if(!r)throw new Error("sessionStorage unavailable; provide options.storage");return{get:e=>r.getItem(e),set:(e,t)=>r.setItem(e,t),remove:e=>r.removeItem(e)}}export{R as CrossAuthClient,C as DEFAULT_POP_API_PATHS,w as HttpSafeDropApiAdapter,N as HttpXAuthAdapter,u as SAFEDROP_ABI,l as SAFEDROP_VALIDATOR_ABI,g as ViemClaimSignerAdapter,h as ViemCryptoAdapter,f as ViemSafeDropChainAdapter,H as XAuthClient,_e as createSafeDropClient,O as generatePkce,D as generateState,S as getCrossAuthBaseUrl,I as getOnePopApiBaseUrl};
1
+ import{a,k as q}from"../chunk-RS7SBR7A.js";import{bytesToHex as pe,keccak256 as ce,recoverAddress as ue,toBytes as le}from"viem";var b=class{keccak256(e){return ce(le(e))}randomSecret(){let e=new Uint8Array(32);return me().getRandomValues(e),pe(e).slice(2)}recoverAddress(e){return ue({hash:e.digest,signature:e.signature})}};function me(){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 ye,sign as he}from"viem/accounts";var A=class{async signDigest(e){try{let t=await he({hash:e.digest,privateKey:e.claimKey});return ye(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 ge,ContractFunctionRevertedError as j,createWalletClient as z,decodeFunctionResult as J,encodeFunctionData as fe,http as we,keccak256 as Z,parseSignature as Y,toBytes as E,toHex as Q}from"viem";import{privateKeyToAccount as ee,serializeSignature as be,sign as Ae}from"viem/accounts";var v=[{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"}]}],W=[{type:"function",name:"drops",stateMutability:"view",inputs:[{name:"claimAddr",type:"address"}],outputs:[{name:"sponsor",type:"address"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"},{name:"salt",type:"bytes32"},{name:"id",type:"string"}]}],P=[{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[]"}]}],S={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]};var G=[{name:"sponsor",type:"address"},{name:"amount",type:"uint96"},{name:"claimAddr",type:"address"},{name:"recipient",type:"address"},{name:"secretHash",type:"bytes32"},{name:"id",type:"string"}],x=[{name:"dropKeys",type:"bytes32[]"},{name:"records",type:"tuple[]",components:G}],c=[{type:"function",name:"activeDropOf",stateMutability:"view",inputs:[{name:"claimAddr",type:"address"}],outputs:[{type:"bytes32"}]},{type:"function",name:"drops",stateMutability:"view",inputs:[{name:"dropKey",type:"bytes32"}],outputs:G},{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:x},{type:"function",name:"pendingDropsByRecipient",stateMutability:"view",inputs:[{name:"recipient",type:"address"}],outputs:x},{type:"function",name:"pendingDropsOf",stateMutability:"view",inputs:[{name:"sponsor",type:"address"}],outputs:x},{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:"withdrawMapped",stateMutability:"nonpayable",inputs:[{name:"dropKey",type:"bytes32"}],outputs:[]},{type:"function",name:"batchWithdrawMapped",stateMutability:"nonpayable",inputs:[{name:"count",type:"uint256"}],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:"resetRecipient",stateMutability:"nonpayable",inputs:[{name:"id",type:"string"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"validatorSignature",type:"bytes"}],outputs:[]}];var m=[{type:"constructor",inputs:[{name:"claimPeriod_",type:"uint64",internalType:"uint64"}],stateMutability:"nonpayable"},{type:"function",name:"claimDigest",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"salt",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"claimPeriod",inputs:[],outputs:[{name:"",type:"uint64",internalType:"uint64"}],stateMutability:"view"},{type:"function",name:"claimedRecipientOf",inputs:[{name:"id",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"deposit",inputs:[{name:"claimAddr",type:"address",internalType:"address"},{name:"token",type:"address",internalType:"contract IERC20"},{name:"amount",type:"uint256",internalType:"uint256"},{name:"id",type:"string",internalType:"string"},{name:"secretHash",type:"bytes32",internalType:"bytes32"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"depositCountOf",inputs:[{name:"sponsor",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"depositsBySponsor",inputs:[{name:"sponsor",type:"address",internalType:"address"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"claimAddr",type:"address",internalType:"address"},{name:"token",type:"address",internalType:"contract IERC20"},{name:"amount",type:"uint128",internalType:"uint128"},{name:"expiry",type:"uint64",internalType:"uint64"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"depositsOf",inputs:[{name:"sponsor",type:"address",internalType:"address"}],outputs:[{name:"",type:"tuple[]",internalType:"struct SafeDrop.DepositRecord[]",components:[{name:"claimAddr",type:"address",internalType:"address"},{name:"token",type:"address",internalType:"contract IERC20"},{name:"amount",type:"uint128",internalType:"uint128"},{name:"expiry",type:"uint64",internalType:"uint64"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]}],stateMutability:"view"},{type:"function",name:"drops",inputs:[{name:"claimAddr",type:"address",internalType:"address"}],outputs:[{name:"sponsor",type:"address",internalType:"address"},{name:"recordIndex",type:"uint96",internalType:"uint96"},{name:"token",type:"address",internalType:"contract IERC20"},{name:"amount",type:"uint128",internalType:"uint128"},{name:"expiry",type:"uint64",internalType:"uint64"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"salt",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:"liveClaimAddrsById",inputs:[{name:"id",type:"string",internalType:"string"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"liveDropCountById",inputs:[{name:"id",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"liveDropsById",inputs:[{name:"id",type:"string",internalType:"string"}],outputs:[{name:"claimAddrs",type:"address[]",internalType:"address[]"},{name:"records",type:"tuple[]",internalType:"struct SafeDrop.Drop[]",components:[{name:"sponsor",type:"address",internalType:"address"},{name:"recordIndex",type:"uint96",internalType:"uint96"},{name:"token",type:"address",internalType:"contract IERC20"},{name:"amount",type:"uint128",internalType:"uint128"},{name:"expiry",type:"uint64",internalType:"uint64"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"salt",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]}],stateMutability:"view"},{type:"function",name:"refund",inputs:[{name:"claimAddr",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"unclaimedCountOf",inputs:[{name:"sponsor",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"unclaimedDepositsOf",inputs:[{name:"sponsor",type:"address",internalType:"address"}],outputs:[{name:"records",type:"tuple[]",internalType:"struct SafeDrop.DepositRecord[]",components:[{name:"claimAddr",type:"address",internalType:"address"},{name:"token",type:"address",internalType:"contract IERC20"},{name:"amount",type:"uint128",internalType:"uint128"},{name:"expiry",type:"uint64",internalType:"uint64"},{name:"secretHash",type:"bytes32",internalType:"bytes32"},{name:"id",type:"string",internalType:"string"}]}],stateMutability:"view"},{type:"function",name:"unclaimedIndexesOf",inputs:[{name:"sponsor",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256[]",internalType:"uint256[]"}],stateMutability:"view"},{type:"function",name:"withdraw",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"id",type:"string",internalType:"string"},{name:"salt",type:"bytes32",internalType:"bytes32"},{name:"signature",type:"bytes",internalType:"bytes"},{name:"secret",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"Deposited",inputs:[{name:"claimAddr",type:"address",indexed:!0,internalType:"address"},{name:"sponsor",type:"address",indexed:!0,internalType:"address"},{name:"token",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"id",type:"string",indexed:!1,internalType:"string"},{name:"expiry",type:"uint64",indexed:!1,internalType:"uint64"},{name:"secretHash",type:"bytes32",indexed:!1,internalType:"bytes32"}],anonymous:!1},{type:"event",name:"EIP712DomainChanged",inputs:[],anonymous:!1},{type:"event",name:"Refunded",inputs:[{name:"claimAddr",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"}],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"}],anonymous:!1},{type:"error",name:"AmountOverflow",inputs:[]},{type:"error",name:"DropAlreadyExists",inputs:[]},{type:"error",name:"DropExpired",inputs:[]},{type:"error",name:"DropNotExpired",inputs:[]},{type:"error",name:"DropNotFound",inputs:[]},{type:"error",name:"DuplicateDropForId",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:"InvalidShortString",inputs:[]},{type:"error",name:"NotSponsor",inputs:[]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]},{type:"error",name:"SaltMismatch",inputs:[]},{type:"error",name:"SecretMismatch",inputs:[]},{type:"error",name:"StringTooLong",inputs:[{name:"str",type:"string",internalType:"string"}]},{type:"error",name:"ZeroAmount",inputs:[]},{type:"error",name:"ZeroClaimAddress",inputs:[]},{type:"error",name:"ZeroRecipient",inputs:[]},{type:"error",name:"ZeroToken",inputs:[]}];var y=[{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:"withdrawByValidator",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"id",type:"string"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"maxCount",type:"uint256"},{name:"signature",type:"bytes"}],outputs:[]},{type:"function",name:"liveDropCountById",stateMutability:"view",inputs:[{name:"id",type:"string"}],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 Pe=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],te="0x0000000000000000000000000000000000000000",Ce=`0x${"00".repeat(32)}`,_e={gas:BigInt(3e5),maxFeePerGas:BigInt(4e9),maxPriorityFeePerGas:BigInt(1e9)},ne=BigInt(1800),C=class{constructor(e){this.address=e.address,this.publicClient=e.publicClient,this.walletClient=e.walletClient,this.chain=e.chain,this.transport=e.transport??we(),this.withdrawFees={..._e,...e.withdrawFees},e.permit&&(this.depositWithPermit=t=>this.permitDeposit(t))}async getDropByKey(e){try{let[t,n,r,s,p,u]=await this.publicClient.readContract({address:this.address,abi:c,functionName:"drops",args:[e]});return t.toLowerCase()===te?null:{dropKey:e,sponsor:t,amount:n,claimAddress:r,recipient:s,secretHash:p,id:u}}catch(t){throw d("drops",t)}}async getDropKeyByClaimAddress(e,t){if(t)return(await this.getPendingDropsBySponsor({sponsor:t})).find(r=>r.claimAddress.toLowerCase()===e.toLowerCase())?.dropKey??null;try{let n=await this.publicClient.readContract({address:this.address,abi:c,functionName:"activeDropOf",args:[e]});return n===Ce?null:n}catch(n){throw d("activeDropOf",n)}}async getPendingDropsById(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:c,functionName:"pendingDropsByXid",args:[e.id]});return n.map((r,s)=>O(t[s],r))}catch(t){throw d("pendingDropsByXid",t)}}async getPendingDropsByRecipient(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:c,functionName:"pendingDropsByRecipient",args:[e.recipient]});return n.map((r,s)=>O(t[s],r))}catch(t){throw d("pendingDropsByRecipient",t)}}async getPendingDropsBySponsor(e){try{let[t,n]=await this.publicClient.readContract({address:this.address,abi:c,functionName:"pendingDropsOf",args:[e.sponsor]});return n.map((r,s)=>O(t[s],r))}catch(t){throw d("pendingDropsOf",t)}}async getDrop(e){try{let{data:t}=await this.publicClient.call({to:this.address,data:fe({abi:m,functionName:"drops",args:[e]})});if(!t||t==="0x")return null;let n;try{let[r,,s,p,u,l,f,w]=J({abi:m,functionName:"drops",data:t});n={claimAddress:e,sponsor:r,token:s,amount:p,expiry:Number(u),secretHash:l,salt:f,id:w}}catch{let[r,s,p,u,l]=J({abi:W,functionName:"drops",data:t});n={claimAddress:e,sponsor:r,amount:s,secretHash:p,salt:u,id:l}}return!n.sponsor||n.sponsor.toLowerCase()===te?null:(n.token||(n.token=await this.escrowToken()),n)}catch(t){throw d("getDrop",t)}}async escrowToken(){try{return await this.publicClient.readContract({address:this.address,abi:v,functionName:"token"})}catch{return}}async getClaimDigest(e){try{return await this.publicClient.readContract({address:this.address,abi:m,functionName:"claimDigest",args:[e.recipient,e.id,e.salt]})}catch(t){throw d("claimDigest",t)}}async approve(e){return this.sponsorWrite("approve",()=>this.walletClient.writeContract({address:e.token,abi:Pe,functionName:"approve",args:[this.address,e.amount],account:this.requireAccount(),chain:this.chain}))}async deposit(e){let t=[e.claimAddress,e.token,e.amount,e.id,e.secretHash];try{await this.publicClient.simulateContract({address:this.address,abi:m,functionName:"deposit",args:t,account:this.requireAccount()})}catch(r){throw d("deposit",r)}return{txHash:await this.sponsorWrite("deposit",()=>this.walletClient.writeContract({address:this.address,abi:m,functionName:"deposit",args:t,account:this.requireAccount(),chain:this.chain}))}}async permitDeposit(e){try{let t=this.requireAccount(),n=e.token,[r,s,p]=await Promise.all([this.publicClient.readContract({address:this.address,abi:v,functionName:"token"}),this.publicClient.readContract({address:n,abi:P,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))+ne,l=await this.walletClient.signTypedData({account:t,domain:{...p,chainId:this.chain.id,verifyingContract:n},types:S,primaryType:"Permit",message:{owner:t.address,spender:this.address,value:e.amount,nonce:s,deadline:u}}),{r:f,s:w,v:R,yParity:T}=Y(l),h=await this.walletClient.writeContract({address:this.address,abi:v,functionName:"deposit",args:[e.claimAddress,e.amount,e.id,e.secretHash,u,Number(R??BigInt(T+27)),f,w],account:t,chain:this.chain});return await e.onSubmitted?.(h),await this.confirm("depositWithPermit",h),{txHash:h}}catch(t){throw d("depositWithPermit",t)}}async depositMapped(e){try{let t=this.requireAccount(),n=e.token,[r,s]=await Promise.all([this.publicClient.readContract({address:n,abi:P,functionName:"nonces",args:[t.address]}),this.permitDomain(n)]),p=BigInt(Math.floor(Date.now()/1e3))+ne,u=await this.walletClient.signTypedData({account:t,domain:{...s,chainId:this.chain.id,verifyingContract:n},types:S,primaryType:"Permit",message:{owner:t.address,spender:this.address,value:e.amount,nonce:r,deadline:p}}),{r:l,s:f,v:w,yParity:R}=Y(u),T=[e.amount,e.id,p,Number(w??BigInt(R+27)),l,f];await this.publicClient.simulateContract({address:this.address,abi:c,functionName:"depositMapped",args:T,account:t});let h=await this.walletClient.writeContract({address:this.address,abi:c,functionName:"depositMapped",args:T,account:t,chain:this.chain,...this.withdrawFees});return await e.onSubmitted?.(h),await this.confirm("depositMapped",h),{txHash:h}}catch(t){throw d("depositMapped",t)}}async permitDomain(e){try{let t=await this.publicClient.readContract({address:e,abi:P,functionName:"eip712Domain"});return{name:t[1],version:t[2]}}catch{return{name:await this.publicClient.readContract({address:e,abi:P,functionName:"name"}),version:"1"}}}async withdraw(e){try{let t=ee(e.claimKey),r=await z({account:t,chain:this.chain,transport:this.transport}).writeContract({address:this.address,abi:m,functionName:"withdraw",args:[e.recipient,e.id,e.salt,e.signature,Q(E(e.secret))],gas:this.withdrawFees.gas,maxFeePerGas:this.withdrawFees.maxFeePerGas,maxPriorityFeePerGas:this.withdrawFees.maxPriorityFeePerGas});return await this.confirm("withdraw",r),r}catch(t){throw d("withdraw",t)}}async withdrawUnmapped(e){try{let t=ee(e.claimKey),n=await this.publicClient.readContract({address:this.address,abi:c,functionName:"claimDigest",args:[e.recipient,e.id,e.dropKey]}),r=be(await Ae({hash:n,privateKey:e.claimKey})),p=await z({account:t,chain:this.chain,transport:this.transport}).writeContract({address:this.address,abi:c,functionName:"withdrawUnmapped",args:[e.recipient,e.id,e.dropKey,r,Q(E(e.secret))],...this.withdrawFees});return await e.onSubmitted?.(p),await this.confirm("withdrawUnmapped",p),p}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:c,functionName:"withdrawMapped",args:[e.dropKey],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:c,functionName:"withdrawMapped",args:[e.dropKey],account:t,chain:this.chain,...this.withdrawFees});return await e.onSubmitted?.(n),await this.confirm("withdrawMapped",n),n}catch(n){throw d("withdrawMapped",n)}}async batchWithdrawMapped(e){let t=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:c,functionName:"batchWithdrawMapped",args:[BigInt(e.count)],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:c,functionName:"batchWithdrawMapped",args:[BigInt(e.count)],account:t,chain:this.chain,...this.withdrawFees,gas:this.withdrawFees.gas*BigInt(e.count)});return await this.confirm("batchWithdrawMapped",n),n}catch(n){throw d("batchWithdrawMapped",n)}}async getValidatorNonce(e){try{return await this.publicClient.readContract({address:this.address,abi:y,functionName:"validatorNonceById",args:[Z(E(e.id))]})}catch(t){throw d("validatorNonceById",t)}}async getValidatorClaimDigest(e){try{return await this.publicClient.readContract({address:this.address,abi:y,functionName:"validatorClaimDigest",args:[e.recipient,e.id,e.nonce,e.deadline]})}catch(t){throw d("validatorClaimDigest",t)}}async getValidator(){try{return await this.publicClient.readContract({address:this.address,abi:y,functionName:"validator"})}catch(e){throw d("validator",e)}}async getClaimedRecipient(e){try{return await this.publicClient.readContract({address:this.address,abi:c,functionName:"claimedRecipientOf",args:[e.id]})}catch(t){throw d("claimedRecipientOf",t)}}async getLiveDropCount(e){try{return await this.publicClient.readContract({address:this.address,abi:y,functionName:"liveDropCountById",args:[e.id]})}catch(t){throw d("liveDropCountById",t)}}async withdrawByValidator(e){let t=[e.recipient,e.id,e.nonce,e.deadline,BigInt(e.maxCount),e.signature],n=this.requireAccount();if(n.address.toLowerCase()!==e.recipient.toLowerCase())throw new a("CHAIN_ERROR","withdrawByValidator must be sent by the recipient wallet",{connected:n.address,recipient:e.recipient});try{await this.publicClient.simulateContract({address:this.address,abi:y,functionName:"withdrawByValidator",args:t,account:n})}catch(r){throw d("withdrawByValidator",r)}return this.sponsorWrite("withdrawByValidator",()=>this.walletClient.writeContract({address:this.address,abi:y,functionName:"withdrawByValidator",args:t,account:n,chain:this.chain}))}async refund(e){return this.sponsorWrite("refund",()=>this.walletClient.writeContract({address:this.address,abi:m,functionName:"refund",args:[e.claimAddress],account:this.requireAccount(),chain:this.chain}))}async refundByKey(e){let t=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:c,functionName:"refund",args:[e.dropKey],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:c,functionName:"refund",args:[e.dropKey],account:t,chain:this.chain,...this.withdrawFees});return await this.confirm("refund",n),n}catch(n){throw d("refund",n)}}async getChangeNonce(e){try{return await this.publicClient.readContract({address:this.address,abi:c,functionName:"changeNonceById",args:[Z(E(e.id))]})}catch(t){throw d("changeNonceById",t)}}async resetRecipient(e){let t=this.requireAccount();try{await this.publicClient.simulateContract({address:this.address,abi:c,functionName:"resetRecipient",args:[e.id,e.nonce,e.deadline,e.signature],account:t});let n=await this.walletClient.writeContract({address:this.address,abi:c,functionName:"resetRecipient",args:[e.id,e.nonce,e.deadline,e.signature],account:t,chain:this.chain,...this.withdrawFees});return await this.confirm("resetRecipient",n),n}catch(n){throw d("resetRecipient",n)}}async sponsorWrite(e,t){try{let n=await t();return await this.confirm(e,n),n}catch(n){throw d(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 ie(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 O(i,e){return{dropKey:i,sponsor:e.sponsor,amount:e.amount,claimAddress:e.claimAddr,recipient:e.recipient,secretHash:e.secretHash,id:e.id}}function d(i,e){if(e instanceof a)return e;let t=ie(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 ie(i){if(!(i instanceof ge))return;let e=i.walk(t=>t instanceof j);if(e instanceof j)return e.data?.errorName??e.reason??void 0}var Te={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"},D={createWallet:"/wallets",dropMetadata:"/drops/metadata",retrievePrivateKey:"/wallets/private-key",drops:"/drops",envelopes:"/envelopes",leaderboards:"/leaderboards",histories:"/histories",xConnections:"/x-connections",batchClaimSignature:"/batch-claim-signature",eventsSubscribe:"/events/subscribe"},ve="https://dev-cross-auth.crosstoken.io";function N(i){try{return import.meta.env?.[i]}catch{return}}function I(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((N("VITE_ONE_POP_ENVIRONMENT")??I("NEXT_PUBLIC_ONE_POP_ENVIRONMENT")??I("ONE_POP_ENVIRONMENT"))?.toLowerCase()){case"dev":case"development":return"dev";case"stg":case"stage":case"staging":return"stage";default:return"production"}}function H(){let e=N("VITE_ONE_POP_API_BASE_URL")??I("NEXT_PUBLIC_ONE_POP_API_BASE_URL")??Te[Ee()];return re(e),e}function k(){let e=(N("VITE_CROSS_AUTH_URL")??I("NEXT_PUBLIC_CROSS_AUTH_URL")??ve).replace(/\/+$/,"");return re(e),e}function re(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 Ie={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",X_CONNECTION_NOT_FOUND:"X_CONNECTION_NOT_FOUND"},se=140,_=class{constructor(e={}){this.baseUrl=(e.baseUrl??H()).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={...D,...e.paths}}async createClaimWallet(e){if(e.message&&[...e.message].length>se)throw new a("INVALID_PARAM",`message must be <= ${se} runes`,{length:[...e.message].length});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){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(Se),count:t?.count??0,totalAmount:g(t?.total_amount,"drops.total_amount"),hasClaimedBefore:t?.has_claimed_before===!0}}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");return((await this.request(this.paths.leaderboards,{method:"GET",query:{token:e.token}}))?.items??[]).map(n=>({identifier:o(n.identifier),balance:g(n.balance,"leaderboard.balance"),lastDepositAmount:g(n.last_deposit_amount,"leaderboard.last_deposit_amount")}))}async listHistories(e={}){let t=await this.request(this.paths.histories,{method:"GET",auth:!0,query:{event:e.event,page:e.page,page_size:e.pageSize}});return{items:(t?.items??[]).map(n=>({eventName:o(n.event_name),txHash:o(n.tx_hash),blockNumber:Number(n.block_number??0),logIndex:Number(n.log_index??0),contractAddress:o(n.contract_address),fromAddress:U(n.from_address),toAddress:U(n.to_address),tempTo:U(n.temp_to),identifier:o(n.identifier),amount:g(n.amount,"history.amount"),createdAt:o(n.created_at),payload:n.payload??void 0})),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 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:ae(t?.nonce)?g(t?.nonce,"batchClaim.nonce"):e.nonce,deadline:ae(t?.deadline)?g(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}${Re(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(()=>{}),p=s?.code_name;throw new a((p?Ie[p]:void 0)??"API_ERROR",s?.message?`${e}: ${s.message}`:`${e} responded ${r.status}`,{status:r.status,code:s?.code,codeName:p})}return r.status===204?null:await r.json().catch(()=>null)}};function Re(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 ae(i){return i!=null&&i!==""}function o(i){return typeof i=="string"?i:""}function U(i){return typeof i=="string"&&i?i:null}function g(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 Se(i){let e=i??{},t=e.sender??{};return{claimAddress:o(e.claim_address),token:o(e.token),amount:g(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)}}var M=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 xe(i){let e=i.apiPort??new _(i.api),t=new C({address:i.contractAddress,publicClient:i.publicClient,walletClient:i.walletClient,chain:i.chain,transport:i.transport,withdrawFees:i.withdrawFees,permit:i.permit});return q({claimBaseUrl:i.claimBaseUrl},{api:e,chain:t,signer:new A,crypto:new b})}async function B(){let i=V(de(32)),e=await Oe().digest("SHA-256",De(i)),t=V(new Uint8Array(e));return{verifier:i,challenge:t,method:"S256"}}function L(){return V(de(16))}function de(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 Oe(){let i=globalThis.crypto?.subtle;if(!i)throw new Error("crypto.subtle unavailable (needs https/secure context)");return i}function De(i){return new TextEncoder().encode(i)}function V(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 F=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 X="pop.xauth.verifier",K="pop.xauth.state",Ne="https://x.com/i/oauth2/authorize",He="tweet.read users.read offline.access",$=class{constructor(e){this.opts={clientId:e.clientId,redirectUri:e.redirectUri,scope:e.scope??He,authorizeUrl:e.authorizeUrl??Ne,port:e.port,storage:e.storage??ke()}}async start(){let e=await B(),t=L();this.opts.storage.set(X,e.verifier),this.opts.storage.set(K,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(K);if(!r||!s||r!==s)throw new a("API_ERROR","X callback: state mismatch (possible CSRF)");let p=this.opts.storage.get(X);if(!p)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:p}),{handle:l}=await this.opts.port.getHandle(u.accessToken);return this.opts.storage.remove(X),this.opts.storage.remove(K),{oauth:{provider:"x",accessToken:u.accessToken},handle:l}}};function ke(){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{M as CrossAuthClient,D as DEFAULT_POP_API_PATHS,_ as HttpSafeDropApiAdapter,F as HttpXAuthAdapter,c as ONEPOP_ABI,m as SAFEDROP_ABI,y as SAFEDROP_VALIDATOR_ABI,A as ViemClaimSignerAdapter,b as ViemCryptoAdapter,C as ViemSafeDropChainAdapter,$ as XAuthClient,xe as createSafeDropClient,B as generatePkce,L as generateState,k as getCrossAuthBaseUrl,H as getOnePopApiBaseUrl};
@@ -0,0 +1 @@
1
+ var n=class extends Error{constructor(e,r,o){super(r),this.name="SafeDropError",this.code=e,this.details=o}};function u(i){return i.trim().replace(/^@/,"").toLowerCase()}function D(i){let e=i.baseUrl.replace(/\/$/,""),r=e.includes("?")?"&":"?",o=i.claimAddress?`&claim=${encodeURIComponent(i.claimAddress)}`:"",a=`${e}${r}sender=${encodeURIComponent(i.sender)}${o}`;return i.secret?`${a}#${encodeURIComponent(i.secret)}`:a}function b(i){let e=i.indexOf("#"),r=e===-1?i:i.slice(0,e),o=e===-1?"":i.slice(e+1),a=r.indexOf("?"),c=a===-1?"":r.slice(a+1);return{sender:E(c,"sender"),secret:o?decodeURIComponent(o):null}}function O(i){return`\u{1F381} You've received a one-pop drop! Claim your tokens here: ${i}`}function B(i,e){let r=[`text=${encodeURIComponent(i)}`];return e&&r.push(`recipient_id=${encodeURIComponent(e)}`),`https://x.com/messages/compose?${r.join("&")}`}function E(i,e){if(!i)return null;for(let r of i.split("&")){if(!r)continue;let o=r.indexOf("=");if(decodeURIComponent(o===-1?r:r.slice(0,o))===e)return decodeURIComponent(o===-1?"":r.slice(o+1))}return null}var f=class{constructor(e,r,o,a){this.chain=e;this.api=r;this.crypto=o;this.claimBaseUrl=a}async execute(e){if(!e.sender)throw new n("MISSING_SENDER","sender address is required");if(!e.recipient?.handle)throw new n("MISSING_RECIPIENT","recipient social handle is required");if(!e.token)throw new n("INVALID_TOKEN","token address is required (ERC20 only)");if(e.amount<=0n)throw new n("INVALID_AMOUNT","amount must be a positive BigInt");let r=u(e.recipient.handle);if(!r)throw new n("MISSING_RECIPIENT","recipient handle normalizes to empty");let o=await this.api.createClaimWallet({sender:e.sender,recipient:{...e.recipient,handle:r}}),a=o.id,c=async d=>{if(this.api.recordDropMetadata)try{await this.api.recordDropMetadata({txHash:d,message:e.message?[...e.message].slice(0,140).join(""):void 0,envelopeId:e.envelopeId})}catch(p){if(p instanceof n&&p.details?.codeName==="ENVELOPE_NOT_FOUND"&&e.envelopeId)try{await this.api.recordDropMetadata({txHash:d,message:e.message?[...e.message].slice(0,140).join(""):void 0})}catch{}}};if(o.isMapped){let{txHash:d}=await this.chain.depositMapped({token:e.token,amount:e.amount,id:a,onSubmitted:c});return{claimAddress:"",secretHash:"",withdrawLink:D({baseUrl:this.claimBaseUrl,sender:e.sender}),depositTxHash:d}}let s=e.secret??this.crypto.randomSecret();if(!s)throw new n("MISSING_SECRET","secret is empty");let t=this.crypto.keccak256(s),h={claimAddress:o.claimAddress,token:e.token,amount:e.amount,id:a,secretHash:t,onSubmitted:c},{txHash:C}=this.chain.depositWithPermit?await this.chain.depositWithPermit(h):await this.approveThenDeposit(h);return{claimAddress:o.claimAddress,secretHash:t,withdrawLink:D({baseUrl:this.claimBaseUrl,sender:e.sender,claimAddress:o.claimAddress,secret:s}),depositTxHash:C}}approveThenDeposit(e){return this.chain.approve({token:e.token,amount:e.amount}).then(()=>this.chain.deposit(e)).then(async r=>(await e.onSubmitted?.(r.txHash),r))}};var N=BigInt(1800),_=30,y=class{constructor(e,r,o,a=()=>Date.now()){this.chain=e;this.api=r;this.crypto=o;this.now=a}async execute(e){let r=u(e.id);if(!r)throw new n("MISSING_RECIPIENT","batchClaim requires an id (social handle)");let o=this.api.requestBatchClaimSignature;if(!o)throw new n("API_ERROR","SafeDropApiPort.requestBatchClaimSignature is not implemented by the injected api adapter");let{getValidatorNonce:a,getValidatorClaimDigest:c,getValidator:s,withdrawByValidator:t}=this.chain;if(!a||!c||!s||!t)throw new n("CHAIN_ERROR","this chain adapter does not support batch claim (validator functions missing)");let h=await a.call(this.chain,{id:r}),C=e.deadline??BigInt(Math.floor(this.now()/1e3))+(e.deadlineTtlSeconds??N),d=await o.call(this.api,{id:r,oauth:e.oauth,nonce:h,deadline:C}),p=d.recipient;if(!p)throw new n("API_ERROR","batch-claim signature response has no recipient",{signed:d});if(e.recipient&&e.recipient.toLowerCase()!==p.toLowerCase())throw new n("SIGN_FAILED","validator signature is bound to a different recipient",{requested:e.recipient,signed:p});await this.assertRecipientPinnedOnChain(r,p);let R=await c.call(this.chain,{recipient:p,id:r,nonce:d.nonce,deadline:d.deadline});await this.assertSignedByValidator(R,d.signature,s.bind(this.chain));let x=e.maxCount??_,S=[],m=await this.liveCount(r);for(let w=0;m>BigInt(0);w+=1){let I=await t.call(this.chain,{recipient:p,id:r,nonce:d.nonce,deadline:d.deadline,maxCount:x,signature:d.signature});S.push(I);let A=await this.liveCount(r);if(A>=m)throw new n("CHAIN_ERROR","batch claim made no progress",{id:r,remaining:m.toString(),page:w,txHash:I});m=A}return{txHashes:S,recipient:p,id:r,nonce:d.nonce,deadline:d.deadline}}async assertRecipientPinnedOnChain(e,r){let o=this.chain.getClaimedRecipient;if(!o)return;let a=await o.call(this.chain,{id:e});if(!a||/^0x0+$/i.test(a))throw new n("DROP_NOT_FOUND","this id has not claimed individually yet \u2014 the first claim must be an individual withdraw",{id:e});if(a.toLowerCase()!==r.toLowerCase())throw new n("SIGN_FAILED","batch-claim recipient does not match the on-chain claimedRecipientOf(id)",{id:e,signed:r,onChain:a})}async assertSignedByValidator(e,r,o){if(!this.crypto.recoverAddress)return;let[a,c]=await Promise.all([this.crypto.recoverAddress({digest:e,signature:r}),o()]);if(a.toLowerCase()!==c.toLowerCase())throw new n("SIGN_FAILED","batch-claim signature does not recover to the on-chain validator (backend signed a different EIP-712 domain/type, or applied a personal_sign prefix)",{signer:a,validator:c,digest:e})}async liveCount(e){let r=this.chain.getLiveDropCount;if(!r)throw new n("CHAIN_ERROR","this chain adapter cannot read liveDropCountById (required to paginate batch claim)");return r.call(this.chain,{id:e})}};var g=class{constructor(e,r){this.chain=e;this.signer=r}async execute(e){if(!e.recipient)throw new n("MISSING_RECIPIENT","recipient address is required");if(!e.claimAddress)throw new n("MISSING_CLAIM_ADDRESS","claim address is required");if(!e.secret)throw new n("MISSING_SECRET","secret is required");if(!e.claimKey)throw new n("MISSING_CLAIM_KEY","claim key is required");let r=await this.chain.getDrop(e.claimAddress);if(!r)throw new n("DROP_NOT_FOUND",`No drop for claim address ${e.claimAddress}`);let o=await this.chain.getClaimDigest({recipient:e.recipient,id:r.id,salt:r.salt}),a=await this.signer.signDigest({claimKey:e.claimKey,digest:o});return{txHash:await this.chain.withdraw({claimKey:e.claimKey,recipient:e.recipient,id:r.id,salt:r.salt,signature:a,secret:e.secret})}}};var P=class{constructor(e){this.chain=e}async execute(e){if(!e.claimAddress)throw new n("MISSING_CLAIM_ADDRESS","claim address is required");return{txHash:await this.chain.refund({claimAddress:e.claimAddress})}}};function l(i,e){if(!i)throw new n("API_ERROR",`SafeDropApiPort.${e} is not implemented by the injected api adapter`);return i}function J(i,e){let r=new f(e.chain,e.api,e.crypto,i.claimBaseUrl),o=new g(e.chain,e.signer),a=new P(e.chain),c=new y(e.chain,e.api,e.crypto),{api:s}=e;return{config:i,deposit:t=>r.execute(t),retrieveClaimKey:t=>s.retrieveClaimKey(t),withdraw:t=>o.execute(t),refund:t=>a.execute(t),getDrop:t=>e.chain.getDrop(t),getDropByKey:t=>e.chain.getDropByKey(t),getDropKeyByClaimAddress:(t,h)=>e.chain.getDropKeyByClaimAddress(t,h),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}),refundByKey:t=>e.chain.refundByKey({dropKey:t}),getChangeNonce:t=>e.chain.getChangeNonce({id:t}),resetRecipient:t=>e.chain.resetRecipient(t),listDrops:t=>l(s.listDrops,"listDrops").call(s,t),listEnvelopes:t=>l(s.listEnvelopes,"listEnvelopes").call(s,t),getLeaderboard:t=>l(s.getLeaderboard,"getLeaderboard").call(s,t),listHistories:t=>l(s.listHistories,"listHistories").call(s,t),getXConnection:()=>l(s.getXConnection,"getXConnection").call(s),connectX:t=>l(s.connectX,"connectX").call(s,t),disconnectX:()=>l(s.disconnectX,"disconnectX").call(s),batchClaim:t=>c.execute(t),requestBatchClaimSignature:t=>l(s.requestBatchClaimSignature,"requestBatchClaimSignature").call(s,t)}}export{n as a,u as b,D as c,b as d,O as e,B as f,f as g,y as h,g as i,P as j,J as k};
@@ -235,7 +235,15 @@ interface SafeDropApiPort {
235
235
  envelopeId?: string;
236
236
  }): Promise<{
237
237
  claimAddress: Address;
238
+ id: Id;
239
+ isMapped: boolean;
238
240
  }>;
241
+ /** Associate off-chain card metadata after the deposit transaction is broadcast. */
242
+ recordDropMetadata?(params: {
243
+ txHash: Hex;
244
+ message?: string;
245
+ envelopeId?: string;
246
+ }): Promise<void>;
239
247
  /**
240
248
  * Withdraw: X OAuth 검증 후 복호화된 임시 claim 개인키 반환 (point of return).
241
249
  * dropId가 아니라 (sender_address + OAuth 토큰 소유자의 identifier) 조합으로
@@ -247,9 +255,13 @@ interface SafeDropApiPort {
247
255
  * 링크마다 순차로 수령해야 한다. 전체 목록은 `listDrops()`로 본다.
248
256
  */
249
257
  retrieveClaimKey(params: {
258
+ claimAddress: Address;
250
259
  senderAddress: Address;
251
260
  oauth: OAuthProof;
252
261
  }): Promise<{
262
+ isMapped: true;
263
+ } | {
264
+ isMapped: false;
253
265
  claimKey: Hex;
254
266
  claimAddress: Address;
255
267
  }>;
@@ -315,6 +327,16 @@ interface DropState {
315
327
  salt: Hex;
316
328
  id: Id;
317
329
  }
330
+ /** Current ONEpop drop record, keyed by bytes32 rather than claim wallet. */
331
+ interface OnePopDrop {
332
+ dropKey: Hex;
333
+ sponsor: Address;
334
+ amount: bigint;
335
+ claimAddress: Address;
336
+ recipient: Address;
337
+ secretHash: SecretHash;
338
+ id: Id;
339
+ }
318
340
  /**
319
341
  * SafeDrop 컨트랙트 상호작용. 어댑터는 자신의 컨트랙트 주소를 알고 있으므로
320
342
  * approve의 spender 등은 받지 않는다. 쓰기는 receipt 확인 후 tx hash 반환.
@@ -322,6 +344,20 @@ interface DropState {
322
344
  * ABI: src/infrastructure/safedrop_abi.json.
323
345
  */
324
346
  interface SafeDropChainPort {
347
+ getDropByKey(dropKey: Hex): Promise<OnePopDrop | null>;
348
+ getDropKeyByClaimAddress(claimAddress: Address, sponsor?: Address): Promise<Hex | null>;
349
+ getClaimedRecipient(params: {
350
+ id: Id;
351
+ }): Promise<Address>;
352
+ getPendingDropsById(params: {
353
+ id: Id;
354
+ }): Promise<readonly OnePopDrop[]>;
355
+ getPendingDropsByRecipient(params: {
356
+ recipient: Address;
357
+ }): Promise<readonly OnePopDrop[]>;
358
+ getPendingDropsBySponsor(params: {
359
+ sponsor: Address;
360
+ }): Promise<readonly OnePopDrop[]>;
325
361
  /** drops(claimAddr). 없으면 null. */
326
362
  getDrop(claimAddress: Address): Promise<DropState | null>;
327
363
  /** claimDigest(recipient, id, salt) — 서명 대상 bytes32. */
@@ -357,6 +393,15 @@ interface SafeDropChainPort {
357
393
  amount: bigint;
358
394
  id: Id;
359
395
  secretHash: SecretHash;
396
+ onSubmitted?: (txHash: Hex) => void | Promise<void>;
397
+ }): Promise<{
398
+ txHash: Hex;
399
+ }>;
400
+ depositMapped(params: {
401
+ token: Address;
402
+ amount: bigint;
403
+ id: Id;
404
+ onSubmitted?: (txHash: Hex) => void | Promise<void>;
360
405
  }): Promise<{
361
406
  txHash: Hex;
362
407
  }>;
@@ -373,10 +418,37 @@ interface SafeDropChainPort {
373
418
  signature: Hex;
374
419
  secret: Secret;
375
420
  }): Promise<Hex>;
421
+ withdrawUnmapped(params: {
422
+ claimKey: Hex;
423
+ recipient: Address;
424
+ id: Id;
425
+ dropKey: Hex;
426
+ secret: Secret;
427
+ onSubmitted?: (txHash: Hex) => void | Promise<void>;
428
+ }): Promise<Hex>;
429
+ withdrawMapped(params: {
430
+ dropKey: Hex;
431
+ onSubmitted?: (txHash: Hex) => void | Promise<void>;
432
+ }): Promise<Hex>;
433
+ batchWithdrawMapped(params: {
434
+ count: number;
435
+ }): Promise<Hex>;
376
436
  /** refund(claimAddr). 만료 후 sponsor(msg.sender)만. */
377
437
  refund(params: {
378
438
  claimAddress: Address;
379
439
  }): Promise<Hex>;
440
+ refundByKey(params: {
441
+ dropKey: Hex;
442
+ }): Promise<Hex>;
443
+ getChangeNonce(params: {
444
+ id: Id;
445
+ }): Promise<bigint>;
446
+ resetRecipient(params: {
447
+ id: Id;
448
+ nonce: bigint;
449
+ deadline: bigint;
450
+ signature: Hex;
451
+ }): Promise<Hex>;
380
452
  /** validatorNonceById(keccak256(utf8(id))). id 해싱은 어댑터 책임. */
381
453
  getValidatorNonce?(params: {
382
454
  id: Id;
@@ -397,13 +469,6 @@ interface SafeDropChainPort {
397
469
  getLiveDropCount?(params: {
398
470
  id: Id;
399
471
  }): Promise<bigint>;
400
- /**
401
- * claimedRecipientOf(id) — 이 id가 **개별 수령(secret+OAuth)으로 확정한** 수령 주소.
402
- * 미수령 id는 zero. 일괄 수령의 목적지를 온체인 값으로 교차 검증하는 데 쓴다.
403
- */
404
- getClaimedRecipient?(params: {
405
- id: Id;
406
- }): Promise<Address>;
407
472
  /**
408
473
  * withdrawByValidator(recipient, id, nonce, deadline, maxCount, signature).
409
474
  * tx는 **수령인 본인 지갑**이 보낸다(컨트랙트가 msg.sender와 서명의 recipient를
@@ -459,9 +524,13 @@ interface SafeDrop {
459
524
  deposit(params: DepositParams): Promise<DepositResult>;
460
525
  /** X OAuth 검증 후 (sender_address + 토큰 소유자)로 임시 claim 키/주소를 받는다 (point of return). */
461
526
  retrieveClaimKey(params: {
527
+ claimAddress: Address;
462
528
  senderAddress: Address;
463
529
  oauth: OAuthProof;
464
530
  }): Promise<{
531
+ isMapped: true;
532
+ } | {
533
+ isMapped: false;
465
534
  claimKey: Hex;
466
535
  claimAddress: Address;
467
536
  }>;
@@ -469,6 +538,18 @@ interface SafeDrop {
469
538
  refund(params: RefundParams): Promise<RefundResult>;
470
539
  /** 온체인 드롭 상태 (drops(claimAddr)). 없으면 null. */
471
540
  getDrop(claimAddress: Address): Promise<DropState | null>;
541
+ getDropByKey(dropKey: Hex): Promise<OnePopDrop | null>;
542
+ getDropKeyByClaimAddress(claimAddress: Address, sponsor?: Address): Promise<Hex | null>;
543
+ getClaimedRecipient(id: Id): Promise<Address>;
544
+ getPendingDropsById(id: Id): Promise<readonly OnePopDrop[]>;
545
+ getPendingDropsByRecipient(recipient: Address): Promise<readonly OnePopDrop[]>;
546
+ getPendingDropsBySponsor(sponsor: Address): Promise<readonly OnePopDrop[]>;
547
+ withdrawUnmapped(params: Parameters<SafeDropChainPort['withdrawUnmapped']>[0]): Promise<Hex>;
548
+ withdrawMapped(params: Parameters<SafeDropChainPort['withdrawMapped']>[0]): Promise<Hex>;
549
+ batchWithdrawMapped(count: number): Promise<Hex>;
550
+ refundByKey(dropKey: Hex): Promise<Hex>;
551
+ getChangeNonce(id: Id): Promise<bigint>;
552
+ resetRecipient(params: Parameters<SafeDropChainPort['resetRecipient']>[0]): Promise<Hex>;
472
553
  /** 내게 온 수령 대기 목록. Bearer JWT + 활성 X 연결 필요. */
473
554
  listDrops(params?: {
474
555
  token?: Address;
@@ -513,4 +594,4 @@ interface SafeDrop {
513
594
  }
514
595
  declare function createSafeDrop(config: SafeDropConfig, deps: SafeDropDeps): SafeDrop;
515
596
 
516
- export { type Address as A, type BatchClaimParams as B, type CryptoPort as C, type DepositParams as D, type Envelope as E, type Hex as H, type Id as I, type LeaderboardEntry as L, type OAuthProof as O, type PendingDrop as P, type RefundParams as R, type SafeDropChainPort as S, type WithdrawParams as W, type XConnection as X, type SafeDropApiPort as a, type DepositResult as b, type BatchClaimResult as c, type ClaimSignerPort as d, type WithdrawResult as e, type RefundResult as f, type Secret as g, type BatchClaimSignature as h, type DropInbox as i, type DropSender as j, type DropState as k, type HistoryEntry as l, type HistoryPage as m, type PopEventName as n, type SafeDrop as o, type SafeDropConfig as p, type SafeDropDeps as q, SafeDropError as r, type SafeDropErrorCode as s, type SecretHash as t, type SocialIdentifier as u, type SocialProvider as v, createSafeDrop as w };
597
+ export { type Address as A, type BatchClaimParams as B, type CryptoPort as C, type DepositParams as D, type Envelope as E, type Hex as H, type Id as I, type LeaderboardEntry as L, type OAuthProof as O, type PendingDrop as P, type RefundParams as R, type SafeDropChainPort as S, type WithdrawParams as W, type XConnection as X, type SafeDropApiPort as a, type DepositResult as b, type BatchClaimResult as c, type ClaimSignerPort as d, type WithdrawResult as e, type RefundResult as f, type Secret as g, type BatchClaimSignature as h, type DropInbox as i, type DropSender as j, type DropState as k, type HistoryEntry as l, type HistoryPage as m, type OnePopDrop as n, type PopEventName as o, type SafeDrop as p, type SafeDropConfig as q, type SafeDropDeps as r, SafeDropError as s, type SafeDropErrorCode as t, type SecretHash as u, type SocialIdentifier as v, type SocialProvider as w, createSafeDrop as x };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SafeDropChainPort, a as SafeDropApiPort, C as CryptoPort, D as DepositParams, b as DepositResult, B as BatchClaimParams, c as BatchClaimResult, d as ClaimSignerPort, W as WithdrawParams, e as WithdrawResult, R as RefundParams, f as RefundResult, A as Address, g as Secret } from './createSafeDrop-qoNG59jB.js';
2
- export { h as BatchClaimSignature, i as DropInbox, j as DropSender, k as DropState, E as Envelope, H as Hex, l as HistoryEntry, m as HistoryPage, I as Id, L as LeaderboardEntry, O as OAuthProof, P as PendingDrop, n as PopEventName, o as SafeDrop, p as SafeDropConfig, q as SafeDropDeps, r as SafeDropError, s as SafeDropErrorCode, t as SecretHash, u as SocialIdentifier, v as SocialProvider, X as XConnection, w as createSafeDrop } from './createSafeDrop-qoNG59jB.js';
1
+ import { S as SafeDropChainPort, a as SafeDropApiPort, C as CryptoPort, D as DepositParams, b as DepositResult, B as BatchClaimParams, c as BatchClaimResult, d as ClaimSignerPort, W as WithdrawParams, e as WithdrawResult, R as RefundParams, f as RefundResult, A as Address, g as Secret } from './createSafeDrop-BSO9RQBD.js';
2
+ export { h as BatchClaimSignature, i as DropInbox, j as DropSender, k as DropState, E as Envelope, H as Hex, l as HistoryEntry, m as HistoryPage, I as Id, L as LeaderboardEntry, O as OAuthProof, n as OnePopDrop, P as PendingDrop, o as PopEventName, p as SafeDrop, q as SafeDropConfig, r as SafeDropDeps, s as SafeDropError, t as SafeDropErrorCode, u as SecretHash, v as SocialIdentifier, w as SocialProvider, X as XConnection, x as createSafeDrop } from './createSafeDrop-BSO9RQBD.js';
3
3
  export { X as XAuthPort, a as XTokenResult } from './XAuthPort-BNJePosj.js';
4
4
 
5
5
  /**
@@ -86,7 +86,8 @@ declare function buildWithdrawLink(params: {
86
86
  /** claim 페이지 base URL. 예: https://one-pop.example/claim */
87
87
  baseUrl: string;
88
88
  sender: Address;
89
- secret: Secret;
89
+ claimAddress?: Address;
90
+ secret?: Secret;
90
91
  }): string;
91
92
  declare function parseWithdrawLink(href: string): {
92
93
  sender: Address | null;
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 m,k as n}from"./chunk-KEW4FB4S.js";export{i as BatchClaimUseCase,s as DepositUseCase,m as RefundUseCase,r as SafeDropError,f as WithdrawUseCase,a as buildComposeUrl,p as buildDmText,o as buildWithdrawLink,n as createSafeDrop,e as normalizeHandle,t as parseWithdrawLink};
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 m,k as n}from"./chunk-RS7SBR7A.js";export{i as BatchClaimUseCase,s as DepositUseCase,m as RefundUseCase,r as SafeDropError,f as WithdrawUseCase,a as buildComposeUrl,p as buildDmText,o as buildWithdrawLink,n as createSafeDrop,e as normalizeHandle,t as parseWithdrawLink};
@@ -1,6 +1,6 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { o as SafeDrop } from '../createSafeDrop-qoNG59jB.js';
3
+ import { p as SafeDrop } from '../createSafeDrop-BSO9RQBD.js';
4
4
 
5
5
  interface SafeDropProviderProps {
6
6
  client: SafeDrop;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nexus-cross/pop",
3
- "version": "1.3.10-beta.2",
3
+ "version": "1.4.0-beta.1",
4
4
  "description": "pop — framework-agnostic core + React adapter.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1 +0,0 @@
1
- var r=class extends Error{constructor(e,t,n){super(t),this.name="SafeDropError",this.code=e,this.details=n}};function m(i){return i.trim().replace(/^@/,"").toLowerCase()}function w(i){let e=i.baseUrl.replace(/\/$/,""),t=e.includes("?")?"&":"?";return`${e}${t}sender=${encodeURIComponent(i.sender)}#${encodeURIComponent(i.secret)}`}function b(i){let e=i.indexOf("#"),t=e===-1?i:i.slice(0,e),n=e===-1?"":i.slice(e+1),a=t.indexOf("?"),c=a===-1?"":t.slice(a+1);return{sender:E(c,"sender"),secret:n?decodeURIComponent(n):null}}function O(i){return`\u{1F381} You've received a one-pop drop! Claim your tokens here: ${i}`}function T(i,e){let t=[`text=${encodeURIComponent(i)}`];return e&&t.push(`recipient_id=${encodeURIComponent(e)}`),`https://x.com/messages/compose?${t.join("&")}`}function E(i,e){if(!i)return null;for(let t of i.split("&")){if(!t)continue;let n=t.indexOf("=");if(decodeURIComponent(n===-1?t:t.slice(0,n))===e)return decodeURIComponent(n===-1?"":t.slice(n+1))}return null}var u=class{constructor(e,t,n,a){this.chain=e;this.api=t;this.crypto=n;this.claimBaseUrl=a}async execute(e){if(!e.sender)throw new r("MISSING_SENDER","sender address is required");if(!e.recipient?.handle)throw new r("MISSING_RECIPIENT","recipient social handle is required");if(!e.token)throw new r("INVALID_TOKEN","token address is required (ERC20 only)");if(e.amount<=0n)throw new r("INVALID_AMOUNT","amount must be a positive BigInt");let t=e.secret??this.crypto.randomSecret();if(!t)throw new r("MISSING_SECRET","secret is empty");let n=this.crypto.keccak256(t),a=m(e.recipient.handle);if(!a)throw new r("MISSING_RECIPIENT","recipient handle normalizes to empty");let{claimAddress:c}=await this.api.createClaimWallet({sender:e.sender,recipient:e.recipient,message:e.message,envelopeId:e.envelopeId}),s={claimAddress:c,token:e.token,amount:e.amount,id:a,secretHash:n},{txHash:o}=this.chain.depositWithPermit?await this.chain.depositWithPermit(s):await this.approveThenDeposit(s);return{claimAddress:c,secretHash:n,withdrawLink:w({baseUrl:this.claimBaseUrl,sender:e.sender,secret:t}),depositTxHash:o}}approveThenDeposit(e){return this.chain.approve({token:e.token,amount:e.amount}).then(()=>this.chain.deposit(e))}};var N=BigInt(1800),_=30,f=class{constructor(e,t,n,a=()=>Date.now()){this.chain=e;this.api=t;this.crypto=n;this.now=a}async execute(e){let t=m(e.id);if(!t)throw new r("MISSING_RECIPIENT","batchClaim requires an id (social handle)");let n=this.api.requestBatchClaimSignature;if(!n)throw new r("API_ERROR","SafeDropApiPort.requestBatchClaimSignature is not implemented by the injected api adapter");let{getValidatorNonce:a,getValidatorClaimDigest:c,getValidator:s,withdrawByValidator:o}=this.chain;if(!a||!c||!s||!o)throw new r("CHAIN_ERROR","this chain adapter does not support batch claim (validator functions missing)");let I=await a.call(this.chain,{id:t}),A=e.deadline??BigInt(Math.floor(this.now()/1e3))+(e.deadlineTtlSeconds??N),d=await n.call(this.api,{id:t,oauth:e.oauth,nonce:I,deadline:A}),l=d.recipient;if(!l)throw new r("API_ERROR","batch-claim signature response has no recipient",{signed:d});if(e.recipient&&e.recipient.toLowerCase()!==l.toLowerCase())throw new r("SIGN_FAILED","validator signature is bound to a different recipient",{requested:e.recipient,signed:l});await this.assertRecipientPinnedOnChain(t,l);let R=await c.call(this.chain,{recipient:l,id:t,nonce:d.nonce,deadline:d.deadline});await this.assertSignedByValidator(R,d.signature,s.bind(this.chain));let x=e.maxCount??_,y=[],h=await this.liveCount(t);for(let g=0;h>BigInt(0);g+=1){let P=await o.call(this.chain,{recipient:l,id:t,nonce:d.nonce,deadline:d.deadline,maxCount:x,signature:d.signature});y.push(P);let D=await this.liveCount(t);if(D>=h)throw new r("CHAIN_ERROR","batch claim made no progress",{id:t,remaining:h.toString(),page:g,txHash:P});h=D}return{txHashes:y,recipient:l,id:t,nonce:d.nonce,deadline:d.deadline}}async assertRecipientPinnedOnChain(e,t){let n=this.chain.getClaimedRecipient;if(!n)return;let a=await n.call(this.chain,{id:e});if(!a||/^0x0+$/i.test(a))throw new r("DROP_NOT_FOUND","this id has not claimed individually yet \u2014 the first claim must be an individual withdraw",{id:e});if(a.toLowerCase()!==t.toLowerCase())throw new r("SIGN_FAILED","batch-claim recipient does not match the on-chain claimedRecipientOf(id)",{id:e,signed:t,onChain:a})}async assertSignedByValidator(e,t,n){if(!this.crypto.recoverAddress)return;let[a,c]=await Promise.all([this.crypto.recoverAddress({digest:e,signature:t}),n()]);if(a.toLowerCase()!==c.toLowerCase())throw new r("SIGN_FAILED","batch-claim signature does not recover to the on-chain validator (backend signed a different EIP-712 domain/type, or applied a personal_sign prefix)",{signer:a,validator:c,digest:e})}async liveCount(e){let t=this.chain.getLiveDropCount;if(!t)throw new r("CHAIN_ERROR","this chain adapter cannot read liveDropCountById (required to paginate batch claim)");return t.call(this.chain,{id:e})}};var C=class{constructor(e,t){this.chain=e;this.signer=t}async execute(e){if(!e.recipient)throw new r("MISSING_RECIPIENT","recipient address is required");if(!e.claimAddress)throw new r("MISSING_CLAIM_ADDRESS","claim address is required");if(!e.secret)throw new r("MISSING_SECRET","secret is required");if(!e.claimKey)throw new r("MISSING_CLAIM_KEY","claim key is required");let t=await this.chain.getDrop(e.claimAddress);if(!t)throw new r("DROP_NOT_FOUND",`No drop for claim address ${e.claimAddress}`);let n=await this.chain.getClaimDigest({recipient:e.recipient,id:t.id,salt:t.salt}),a=await this.signer.signDigest({claimKey:e.claimKey,digest:n});return{txHash:await this.chain.withdraw({claimKey:e.claimKey,recipient:e.recipient,id:t.id,salt:t.salt,signature:a,secret:e.secret})}}};var S=class{constructor(e){this.chain=e}async execute(e){if(!e.claimAddress)throw new r("MISSING_CLAIM_ADDRESS","claim address is required");return{txHash:await this.chain.refund({claimAddress:e.claimAddress})}}};function p(i,e){if(!i)throw new r("API_ERROR",`SafeDropApiPort.${e} is not implemented by the injected api adapter`);return i}function J(i,e){let t=new u(e.chain,e.api,e.crypto,i.claimBaseUrl),n=new C(e.chain,e.signer),a=new S(e.chain),c=new f(e.chain,e.api,e.crypto),{api:s}=e;return{config:i,deposit:o=>t.execute(o),retrieveClaimKey:o=>s.retrieveClaimKey(o),withdraw:o=>n.execute(o),refund:o=>a.execute(o),getDrop:o=>e.chain.getDrop(o),listDrops:o=>p(s.listDrops,"listDrops").call(s,o),listEnvelopes:o=>p(s.listEnvelopes,"listEnvelopes").call(s,o),getLeaderboard:o=>p(s.getLeaderboard,"getLeaderboard").call(s,o),listHistories:o=>p(s.listHistories,"listHistories").call(s,o),getXConnection:()=>p(s.getXConnection,"getXConnection").call(s),connectX:o=>p(s.connectX,"connectX").call(s,o),disconnectX:()=>p(s.disconnectX,"disconnectX").call(s),batchClaim:o=>c.execute(o),requestBatchClaimSignature:o=>p(s.requestBatchClaimSignature,"requestBatchClaimSignature").call(s,o)}}export{r as a,m as b,w as c,b as d,O as e,T as f,u as g,f as h,C as i,S as j,J as k};