@polymarket/client 0.0.0-canary-20260421120448

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.
@@ -0,0 +1,6 @@
1
+ import {PolymarketError}from'@polymarket/types';var w=/^[$A-Z_a-z][$\w]*$/;function a(s){let r=p(s.issues);return r.length===0?"It was not possible to determine a more specific reason.":["Fix the following issues:",u(r)].join(`
2
+ `)}function i(s,r){let e=p(s.issues);return e.length===0?["Received an incompatible API response.",`Endpoint: ${r.endpoint}`,"This usually means the API response shape changed in a breaking way or the SDK is outdated.","It was not possible to determine a more specific reason."].join(`
3
+ `):["Received an incompatible API response.",`Endpoint: ${r.endpoint}`,"This usually means the API response shape changed in a breaking way or the SDK is outdated.","Fix the following issues:",u(e)].join(`
4
+ `)}function u(s){return s.map(e=>e.path===null?`- ${e.message}`:`- ${e.path}: ${e.message}`).join(`
5
+ `)}function p(s){return c(s).slice(0,99)}function c(s,r=[]){let e=s.flatMap(n=>{let o=[...r,...n.path];return n.code==="invalid_union"?n.errors.flatMap($=>c($,o)):[{code:n.code,message:n.message,path:o.length===0?null:v(o)}]});return R(e)}function R(s){let r=new Set,e=[];for(let n of s){let o=`${n.code}:${n.path??""}:${n.message}`;r.has(o)||(r.add(o),e.push(n));}return e.sort(Z)}function Z(s,r){return s.path===null&&r.path!==null?-1:s.path!==null&&r.path===null?1:(s.path??"").localeCompare(r.path??"")}function v(s){return s.reduce((r,e)=>typeof e=="number"?`${r}[${e.toString()}]`:typeof e!="string"?r:e.includes('"')?`${r}["${e.replaceAll('"','\\"')}"]`:w.test(e)?r.length===0?e:`${r}.${e}`:`${r}["${e}"]`,"")}var d=class s extends PolymarketError{name="UserInputError";constructor(r,e={}){super(r,e);}static fromZodError(r){return new s(a(r),{cause:r})}},l=class s extends PolymarketError{name="UnexpectedResponseError";constructor(r,e={}){super(r,e);}static fromZodError(r,e){return new s(i(r,e),{cause:r})}},f=class s extends PolymarketError{name="TransportError";constructor(r,e={}){super(r,e);}static fromError(r){return new s(r instanceof Error?r.message:"Request failed",{cause:r})}},m=class extends PolymarketError{name="RequestRejectedError";status;constructor(r,e){super(r,e),this.status=e.status;}},g=class extends PolymarketError{name="RateLimitError"},I=class extends PolymarketError{name="TimeoutError";constructor(r,e={}){super(r,e);}},E=class extends PolymarketError{name="TransactionFailedError";constructor(r,e={}){super(r,e);}},x=class s extends PolymarketError{name="CancelledSigningError";constructor(r,e={}){super(r,e);}static fromError(r){return new s(r.message,{cause:r})}},h=class extends PolymarketError{name="InsufficientLiquidityError";constructor(r,e={}){super(r,e);}},y=class s extends PolymarketError{name="SigningError";constructor(r,e={}){super(r,e);}static fromError(r,e){let n=e??(r instanceof Error?r.message:"Signing failed");return new s(n,{cause:r})}};export{d as a,l as b,f as c,m as d,g as e,I as f,E as g,x as h,h as i,y as j};//# sourceMappingURL=chunk-X2E5YUTB.js.map
6
+ //# sourceMappingURL=chunk-X2E5YUTB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/validation.ts","../src/errors.ts"],"names":["identifierRegex","formatInputZodError","error","issues","flattenIssues","formatIssues","formatResponseZodError","context","issue","flattenIssueBranches","pathPrefix","flattened","path","branch","formatPath","dedupeIssues","seen","deduped","key","compareIssues","left","right","result","segment","UserInputError","_UserInputError","PolymarketError","message","options","UnexpectedResponseError","_UnexpectedResponseError","TransportError","_TransportError","RequestRejectedError","RateLimitError","TimeoutError","TransactionFailedError","CancelledSigningError","_CancelledSigningError","InsufficientLiquidityError","SigningError","_SigningError","msg"],"mappings":"gDAGA,IAAMA,CAAAA,CAAkB,oBAAA,CAejB,SAASC,CAAAA,CAAoBC,CAAAA,CAAyB,CAC3D,IAAMC,CAAAA,CAASC,CAAAA,CAAcF,CAAAA,CAAM,MAAM,CAAA,CAEzC,OAAIC,CAAAA,CAAO,MAAA,GAAW,CAAA,CACb,0DAAA,CAGF,CAAC,2BAAA,CAA6BE,CAAAA,CAAaF,CAAM,CAAC,CAAA,CAAE,IAAA,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AAO,UAAU1B,CAAAA,CAAqC,CACpD,OAAO,IAAIoC,CAAAA,CAAsBpC,CAAAA,CAAM,OAAA,CAAS,CAC9C,KAAA,CAAOA,CACT,CAAC,CACH,CACF,CAAA,CAMaqC,EAAN,cAAyCb,eAAgB,CACrD,IAAA,CAAO,4BAAA,CAEhB,WAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAwB,EAAC,CAAG,CACvD,KAAA,CAAMD,CAAAA,CAASC,CAAO,EACxB,CACF,CAAA,CAMaY,CAAAA,CAAN,MAAMC,CAAAA,SAAqBf,eAAgB,CACvC,IAAA,CAAO,cAAA,CAEhB,WAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAwB,EAAC,CAAG,CACvD,KAAA,CAAMD,CAAAA,CAASC,CAAO,EACxB,CAEA,OAAO,SAAA,CAAU1B,CAAAA,CAAgByB,CAAAA,CAAgC,CAC/D,IAAMe,CAAAA,CACJf,CAAAA,GAAYzB,CAAAA,YAAiB,MAAQA,CAAAA,CAAM,OAAA,CAAU,gBAAA,CAAA,CACvD,OAAO,IAAIuC,CAAAA,CAAaC,CAAAA,CAAK,CAAE,KAAA,CAAOxC,CAAM,CAAC,CAC/C,CACF","file":"chunk-X2E5YUTB.js","sourcesContent":["import type { core, ZodError } from 'zod';\n\nconst maxIssuesInMessage = 99;\nconst identifierRegex = /^[$A-Z_a-z][$\\w]*$/;\n\ntype UserInputIssue = {\n code: string;\n message: string;\n path: string | null;\n};\n\nexport type ResponseValidationContext = {\n endpoint: string;\n};\n\n/**\n * Formats a `ZodError` into an SDK-oriented input validation message.\n */\nexport function formatInputZodError(error: ZodError): string {\n const issues = flattenIssues(error.issues);\n\n if (issues.length === 0) {\n return 'It was not possible to determine a more specific reason.';\n }\n\n return ['Fix the following issues:', formatIssues(issues)].join('\\n');\n}\n\n/**\n * Formats a `ZodError` into an SDK-oriented response validation message.\n */\nexport function formatResponseZodError(\n error: ZodError,\n context: ResponseValidationContext,\n): string {\n const issues = flattenIssues(error.issues);\n\n if (issues.length === 0) {\n return [\n 'Received an incompatible API response.',\n `Endpoint: ${context.endpoint}`,\n 'This usually means the API response shape changed in a breaking way or the SDK is outdated.',\n 'It was not possible to determine a more specific reason.',\n ].join('\\n');\n }\n\n return [\n 'Received an incompatible API response.',\n `Endpoint: ${context.endpoint}`,\n 'This usually means the API response shape changed in a breaking way or the SDK is outdated.',\n 'Fix the following issues:',\n formatIssues(issues),\n ].join('\\n');\n}\n\nfunction formatIssues(issues: readonly UserInputIssue[]): string {\n const lines = issues.map((issue) => {\n if (issue.path === null) {\n return `- ${issue.message}`;\n }\n\n return `- ${issue.path}: ${issue.message}`;\n });\n\n return lines.join('\\n');\n}\n\nfunction flattenIssues(issues: readonly core.$ZodIssue[]): UserInputIssue[] {\n return flattenIssueBranches(issues).slice(0, maxIssuesInMessage);\n}\n\nfunction flattenIssueBranches(\n issues: readonly core.$ZodIssue[],\n pathPrefix: readonly PropertyKey[] = [],\n): UserInputIssue[] {\n const flattened = issues.flatMap((issue) => {\n const path = [...pathPrefix, ...issue.path];\n\n if (issue.code === 'invalid_union') {\n return issue.errors.flatMap((branch) =>\n flattenIssueBranches(branch, path),\n );\n }\n\n return [\n {\n code: issue.code,\n message: issue.message,\n path: path.length === 0 ? null : formatPath(path),\n } satisfies UserInputIssue,\n ];\n });\n\n return dedupeIssues(flattened);\n}\n\nfunction dedupeIssues(issues: readonly UserInputIssue[]): UserInputIssue[] {\n const seen = new Set<string>();\n const deduped: UserInputIssue[] = [];\n\n for (const issue of issues) {\n const key = `${issue.code}:${issue.path ?? ''}:${issue.message}`;\n\n if (seen.has(key)) {\n continue;\n }\n\n seen.add(key);\n deduped.push(issue);\n }\n\n return deduped.sort(compareIssues);\n}\n\nfunction compareIssues(left: UserInputIssue, right: UserInputIssue): number {\n if (left.path === null && right.path !== null) {\n return -1;\n }\n\n if (left.path !== null && right.path === null) {\n return 1;\n }\n\n return (left.path ?? '').localeCompare(right.path ?? '');\n}\n\nfunction formatPath(path: readonly PropertyKey[]): string {\n return path.reduce<string>((result, segment) => {\n if (typeof segment === 'number') {\n return `${result}[${segment.toString()}]`;\n }\n\n if (typeof segment !== 'string') {\n return result;\n }\n\n if (segment.includes('\"')) {\n return `${result}[\"${segment.replaceAll('\"', '\\\\\"')}\"]`;\n }\n\n if (!identifierRegex.test(segment)) {\n return `${result}[\"${segment}\"]`;\n }\n\n if (result.length === 0) {\n return segment;\n }\n\n return `${result}.${segment}`;\n }, '');\n}\n","import { PolymarketError } from '@polymarket/types';\nimport type { ZodError } from 'zod';\nimport {\n formatInputZodError,\n formatResponseZodError,\n type ResponseValidationContext,\n} from './validation';\n\n/**\n * Error thrown when an action input fails SDK validation before a request is\n * sent.\n */\nexport class UserInputError extends PolymarketError {\n override name = 'UserInputError' as const;\n\n constructor(message: string, options: ErrorOptions = {}) {\n super(message, options);\n }\n\n static fromZodError(error: ZodError): UserInputError {\n return new UserInputError(formatInputZodError(error), {\n cause: error,\n });\n }\n}\n\n/**\n * Error thrown when a service response does not match the action's expected\n * response shape.\n */\nexport class UnexpectedResponseError extends PolymarketError {\n override name = 'UnexpectedResponseError' as const;\n\n constructor(message: string, options: ErrorOptions = {}) {\n super(message, options);\n }\n\n static fromZodError(\n error: ZodError,\n context: ResponseValidationContext,\n ): UnexpectedResponseError {\n return new UnexpectedResponseError(formatResponseZodError(error, context), {\n cause: error,\n });\n }\n}\n\n/**\n * Error thrown when the SDK cannot complete a request because of a network or\n * runtime transport failure.\n */\nexport class TransportError extends PolymarketError {\n override name = 'TransportError' as const;\n\n constructor(message: string, options: ErrorOptions = {}) {\n super(message, options);\n }\n\n static fromError(error: unknown): TransportError {\n return new TransportError(\n error instanceof Error ? error.message : 'Request failed',\n {\n cause: error,\n },\n );\n }\n}\n\nexport type RequestRejectedErrorOptions = {\n status: number;\n};\n\n/**\n * Error thrown when a service responds with a non-success status other than\n * rate limiting.\n */\nexport class RequestRejectedError extends PolymarketError {\n override name = 'RequestRejectedError' as const;\n\n readonly status: number;\n\n constructor(\n message: string,\n options: ErrorOptions & RequestRejectedErrorOptions,\n ) {\n super(message, options);\n this.status = options.status;\n }\n}\n\n/**\n * Error thrown when the service rejects a request because the rate limit has\n * been exceeded.\n */\nexport class RateLimitError extends PolymarketError {\n override name = 'RateLimitError' as const;\n}\n\n/**\n * Error thrown when an async wait operation exceeds its allotted polling time.\n */\nexport class TimeoutError extends PolymarketError {\n override name = 'TimeoutError' as const;\n\n constructor(message: string, options: ErrorOptions = {}) {\n super(message, options);\n }\n}\n\n/**\n * Error thrown when a submitted transaction reaches a terminal failure state.\n */\nexport class TransactionFailedError extends PolymarketError {\n override name = 'TransactionFailedError' as const;\n\n constructor(message: string, options: ErrorOptions = {}) {\n super(message, options);\n }\n}\n\n/**\n * Error thrown when the user cancels a required wallet signing action.\n */\nexport class CancelledSigningError extends PolymarketError {\n override name = 'CancelledSigningError' as const;\n\n constructor(message: string, options: ErrorOptions = {}) {\n super(message, options);\n }\n\n static fromError(error: Error): CancelledSigningError {\n return new CancelledSigningError(error.message, {\n cause: error,\n });\n }\n}\n\n/**\n * Error thrown when there is not enough resting market liquidity to satisfy the\n * requested execution semantics.\n */\nexport class InsufficientLiquidityError extends PolymarketError {\n override name = 'InsufficientLiquidityError' as const;\n\n constructor(message: string, options: ErrorOptions = {}) {\n super(message, options);\n }\n}\n\n/**\n * Error thrown when the SDK cannot produce a required signature or\n * authentication payload.\n */\nexport class SigningError extends PolymarketError {\n override name = 'SigningError' as const;\n\n constructor(message: string, options: ErrorOptions = {}) {\n super(message, options);\n }\n\n static fromError(error: unknown, message?: string): SigningError {\n const msg =\n message ?? (error instanceof Error ? error.message : 'Signing failed');\n return new SigningError(msg, { cause: error });\n }\n}\n"]}
@@ -0,0 +1,9 @@
1
+ import '@polymarket/types';
2
+ export { d as AccountActions, f as AccountPublicActions, g as AnalyticsActions, D as DataActions, t as DiscoveryActions, w as PublicActions, z as PublicWalletActions, J as RewardsActions, K as RewardsPublicActions, S as SecureActions, M as SecureWalletActions, V as TradingActions, a3 as accountActions, a4 as allActions, a5 as analyticsActions, a7 as dataActions, a8 as discoveryActions, aa as rewardsActions, ab as tradingActions, ac as walletActions } from '../types-BcwWqAsH.js';
3
+ import '@polymarket/bindings';
4
+ import '@polymarket/bindings/relayer';
5
+ import 'zod';
6
+ import '@polymarket/bindings/clob';
7
+ import '@polymarket/bindings/gamma';
8
+ import '@polymarket/bindings/data';
9
+ import 'ox';
@@ -0,0 +1,2 @@
1
+ export{a as accountActions,h as allActions,b as analyticsActions,c as dataActions,d as discoveryActions,e as rewardsActions,f as tradingActions,g as walletActions}from'../chunk-KLADIGW6.js';import'../chunk-VQMBZJB5.js';import'../chunk-X2E5YUTB.js';//# sourceMappingURL=index.js.map
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
@@ -0,0 +1,37 @@
1
+ import { ethers } from 'ethers-v5';
2
+ import { T as TypedDataPayload, a as TypedData, A as AuthenticateWith, C as CompleteWith } from './types-BcwWqAsH.js';
3
+ import '@polymarket/bindings';
4
+ import '@polymarket/types';
5
+ import '@polymarket/bindings/relayer';
6
+ import 'zod';
7
+ import '@polymarket/bindings/clob';
8
+ import '@polymarket/bindings/gamma';
9
+ import '@polymarket/bindings/data';
10
+ import 'ox';
11
+
12
+ type EthersV5Signer = ethers.Signer & {
13
+ _signTypedData(domain: TypedDataPayload['domain'], types: ReturnType<typeof removeEip712Domain>, value: TypedDataPayload['message']): Promise<string>;
14
+ };
15
+ /**
16
+ * Drives an authentication workflow with an ethers v5 signer.
17
+ *
18
+ * @throws {@link AuthenticateWithError}
19
+ * Thrown when the required wallet signature is rejected or cannot be produced.
20
+ */
21
+ declare function authenticateWith(signer: EthersV5Signer): AuthenticateWith;
22
+ /**
23
+ * Drives a workflow with an ethers v5 signer.
24
+ *
25
+ * Supports the current non-auth workflow set, including order signing,
26
+ * approvals, transfers, redemptions, and gasless wallet preparation.
27
+ *
28
+ * @throws {@link CompleteWithError}
29
+ * Thrown when the required wallet signature or submission is rejected or cannot be produced.
30
+ */
31
+ declare function completeWith(signer: EthersV5Signer): CompleteWith;
32
+ declare function removeEip712Domain(types: TypedData): Record<string, Array<{
33
+ name: string;
34
+ type: string;
35
+ }>>;
36
+
37
+ export { authenticateWith, completeWith };
@@ -0,0 +1,2 @@
1
+ import {j,h,c as c$1,g as g$1}from'./chunk-X2E5YUTB.js';import {expectEvmAddress,expectEvmSignature,expectTxHash}from'@polymarket/types';import {ethers}from'ethers-v5';function H(t){return async function(a){let n=await a.next();for(;!n.done;)try{switch(n.value.kind){case "requestAddress":{let r=await g(t);n=await a.next(r);break}case "signAuthMessage":n=await a.next(await m(t,n.value.payload));break}}catch(r){n=await a.throw(r);}return n.value}}function P(t){return async function(a){let n=await a.next();for(;!n.done;)try{switch(n.value.kind){case "sendErc20ApprovalTransaction":case "sendErc1155ApprovalForAllTransaction":case "sendErc20TransferTransaction":case "sendMergePositionsTransaction":case "sendRedeemPositionsTransaction":case "sendSplitPositionTransaction":{let r=await f(t,n.value.request);n=await a.next(new d(r));break}case "requestAddress":{let r=await g(t);n=await a.next(r);break}case "signGaslessTypedData":case "signOrder":n=await a.next(await m(t,n.value.payload));break;case "signGaslessMessage":n=await a.next(await v(t,n.value.payload));break}}catch(r){n=await a.throw(r);}return n.value}}async function g(t){try{return expectEvmAddress(await t.getAddress())}catch(e){throw j.fromError(e,"Could not resolve signer address")}}async function f(t,e){try{return await t.sendTransaction({chainId:e.chainId,data:e.data,to:e.to,value:e.value?.toString()})}catch(a){u(a);}}async function m(t,e){try{return expectEvmSignature(await t._signTypedData(e.domain,E(e.types),e.message))}catch(a){u(a);}}async function v(t,e){try{let a=ethers.utils._TypedDataEncoder.hash(e.domain,E(e.types),e.message);return expectEvmSignature(await t.signMessage(ethers.utils.arrayify(a)))}catch(a){u(a);}}function E(t){let e=Object.entries(t).filter(([a])=>a!=="EIP712Domain");return Object.fromEntries(e.map(([a,n])=>[a,n.map(r=>({...r}))]))}function u(t){throw c(t)?new h("User rejected the signing request",{cause:t}):j.fromError(t)}function c(t,e=new Set){if(e.has(t)||t===null||typeof t!="object")return false;e.add(t);let a=t;return a.code===4001||a.code==="ACTION_REJECTED"||c(a.error,e)||c(a.cause,e)}function x(t){return T(t,"CALL_EXCEPTION")}function S(t){return T(t,"TRANSACTION_REPLACED")}function T(t,e){return t instanceof Error&&"code"in t&&t.code===e}var d=class{transactionId=null;#e;#t;constructor(e){this.#t=e,this.#e=expectTxHash(e.hash);}get transactionHash(){return this.#e}async wait(){try{let e=await this.#t.wait(),a=expectTxHash(e.transactionHash);return this.#e=a,{transactionHash:a,transactionId:null}}catch(e){if(S(e)){if(e.cancelled)throw c$1.fromError(e);let a=expectTxHash(e.receipt.transactionHash);return this.#e=a,{transactionHash:a,transactionId:null}}throw x(e)?new g$1(`Transaction ${this.#e} reverted`,{cause:e}):c$1.fromError(e)}}};export{H as authenticateWith,P as completeWith};//# sourceMappingURL=ethers-v5.js.map
2
+ //# sourceMappingURL=ethers-v5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ethers-v5.ts"],"names":["authenticateWith","signer","workflow","result","address","getAddress","signTypedData","error","completeWith","response","sendTransaction","DirectTransactionHandle","signMessage","expectEvmAddress","SigningError","request","throwSigningWorkflowError","payload","expectEvmSignature","removeEip712Domain","digest","ethers","types","entries","name","fields","field","isUserRejectedError","CancelledSigningError","seen","candidate","isCallExceptionError","hasErrorCode","isTransactionReplacedError","code","#transactionHash","#transaction","transaction","expectTxHash","receipt","transactionHash","TransportError","TransactionFailedError"],"mappings":"wKA+BO,SAASA,CAAAA,CAAiBC,EAA0C,CACzE,OAAO,eAA4BC,CAAAA,CAAU,CAC3C,IAAIC,CAAAA,CAAS,MAAMD,EAAS,IAAA,EAAK,CAEjC,KAAO,CAACC,CAAAA,CAAO,IAAA,EACb,GAAI,CACF,OAAQA,CAAAA,CAAO,KAAA,CAAM,IAAA,EACnB,KAAK,gBAAA,CAAkB,CACr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AK4B,GAAmBK,CAAAA,CAEjB,CACL,eAAA,CAAAA,CAAAA,CACA,aAAA,CAAe,IACjB,CACF,CAEA,MAAIT,CAAAA,CAAqBxB,CAAK,CAAA,CACtB,IAAImC,GAAAA,CACR,CAAA,YAAA,EAAe,IAAA,CAAKP,EAAgB,YACpC,CAAE,KAAA,CAAO5B,CAAM,CACjB,EAGIkC,GAAAA,CAAe,SAAA,CAAUlC,CAAK,CACtC,CACF,CACF,CAAA","file":"ethers-v5.js","sourcesContent":["import {\n expectEvmAddress,\n expectEvmSignature,\n expectTxHash,\n type HexString,\n type TxHash,\n} from '@polymarket/types';\nimport { ethers } from 'ethers-v5';\nimport {\n CancelledSigningError,\n SigningError,\n TransactionFailedError,\n TransportError,\n} from './errors';\nimport type { TransactionHandle, TypedData, TypedDataPayload } from './types';\nimport type { AuthenticateWith, CompleteWith } from './workflow';\n\ntype EthersV5Signer = ethers.Signer & {\n _signTypedData(\n domain: TypedDataPayload['domain'],\n types: ReturnType<typeof removeEip712Domain>,\n value: TypedDataPayload['message'],\n ): Promise<string>;\n};\n\n/**\n * Drives an authentication workflow with an ethers v5 signer.\n *\n * @throws {@link AuthenticateWithError}\n * Thrown when the required wallet signature is rejected or cannot be produced.\n */\nexport function authenticateWith(signer: EthersV5Signer): AuthenticateWith {\n return async function authenticate(workflow) {\n let result = await workflow.next();\n\n while (!result.done) {\n try {\n switch (result.value.kind) {\n case 'requestAddress': {\n const address = await getAddress(signer);\n result = await workflow.next(address);\n break;\n }\n case 'signAuthMessage':\n result = await workflow.next(\n await signTypedData(signer, result.value.payload),\n );\n break;\n }\n } catch (error) {\n result = await workflow.throw(error);\n }\n }\n\n return result.value;\n };\n}\n\n/**\n * Drives a workflow with an ethers v5 signer.\n *\n * Supports the current non-auth workflow set, including order signing,\n * approvals, transfers, redemptions, and gasless wallet preparation.\n *\n * @throws {@link CompleteWithError}\n * Thrown when the required wallet signature or submission is rejected or cannot be produced.\n */\nexport function completeWith(signer: EthersV5Signer): CompleteWith {\n return async function complete(workflow) {\n let result = await workflow.next();\n\n while (!result.done) {\n try {\n switch (result.value.kind) {\n case 'sendErc20ApprovalTransaction':\n case 'sendErc1155ApprovalForAllTransaction':\n case 'sendErc20TransferTransaction':\n case 'sendMergePositionsTransaction':\n case 'sendRedeemPositionsTransaction':\n case 'sendSplitPositionTransaction': {\n const response = await sendTransaction(\n signer,\n result.value.request,\n );\n result = await workflow.next(new DirectTransactionHandle(response));\n break;\n }\n\n case 'requestAddress': {\n const address = await getAddress(signer);\n result = await workflow.next(address);\n break;\n }\n\n case 'signGaslessTypedData':\n case 'signOrder':\n result = await workflow.next(\n await signTypedData(signer, result.value.payload),\n );\n break;\n\n case 'signGaslessMessage':\n result = await workflow.next(\n await signMessage(signer, result.value.payload),\n );\n break;\n }\n } catch (error) {\n result = await workflow.throw(error);\n }\n }\n\n return result.value;\n };\n}\n\nasync function getAddress(signer: EthersV5Signer) {\n try {\n return expectEvmAddress(await signer.getAddress());\n } catch (error) {\n throw SigningError.fromError(error, 'Could not resolve signer address');\n }\n}\n\nasync function sendTransaction(\n signer: EthersV5Signer,\n request: { chainId: number; data?: HexString; to: string; value?: bigint },\n): Promise<ethers.providers.TransactionResponse> {\n try {\n return await signer.sendTransaction({\n chainId: request.chainId,\n data: request.data,\n to: request.to,\n value: request.value?.toString(),\n });\n } catch (error) {\n throwSigningWorkflowError(error);\n }\n}\n\nasync function signTypedData(\n signer: EthersV5Signer,\n payload: TypedDataPayload,\n) {\n try {\n return expectEvmSignature(\n await signer._signTypedData(\n payload.domain,\n removeEip712Domain(payload.types),\n payload.message,\n ),\n );\n } catch (error) {\n throwSigningWorkflowError(error);\n }\n}\n\nasync function signMessage(signer: EthersV5Signer, payload: TypedDataPayload) {\n try {\n const digest = ethers.utils._TypedDataEncoder.hash(\n payload.domain,\n removeEip712Domain(payload.types),\n payload.message,\n );\n\n return expectEvmSignature(\n await signer.signMessage(ethers.utils.arrayify(digest)),\n );\n } catch (error) {\n throwSigningWorkflowError(error);\n }\n}\n\nfunction removeEip712Domain(\n types: TypedData,\n): Record<string, Array<{ name: string; type: string }>> {\n const entries = Object.entries(types).filter(\n ([name]) => name !== 'EIP712Domain',\n );\n\n return Object.fromEntries(\n entries.map(([name, fields]) => [\n name,\n fields.map((field) => ({ ...field })),\n ]),\n );\n}\n\nfunction throwSigningWorkflowError(error: unknown): never {\n if (isUserRejectedError(error)) {\n throw new CancelledSigningError('User rejected the signing request', {\n cause: error,\n });\n }\n\n throw SigningError.fromError(error);\n}\n\nfunction isUserRejectedError(\n error: unknown,\n seen = new Set<unknown>(),\n): boolean {\n if (seen.has(error) || error === null || typeof error !== 'object') {\n return false;\n }\n\n seen.add(error);\n\n const candidate = error as {\n cause?: unknown;\n code?: unknown;\n error?: unknown;\n };\n\n return (\n // ethers v5 normalizes user-rejected wallet actions to ACTION_REJECTED,\n // but some provider-shaped errors can still surface the raw EIP-1193 4001.\n candidate.code === 4001 ||\n candidate.code === 'ACTION_REJECTED' ||\n isUserRejectedError(candidate.error, seen) ||\n isUserRejectedError(candidate.cause, seen)\n );\n}\n\nfunction isCallExceptionError(error: unknown): error is Error {\n return hasErrorCode(error, 'CALL_EXCEPTION');\n}\n\nfunction isTransactionReplacedError(error: unknown): error is Error & {\n cancelled: boolean;\n receipt: { transactionHash: string };\n} {\n return hasErrorCode(error, 'TRANSACTION_REPLACED');\n}\n\nfunction hasErrorCode(error: unknown, code: string): error is Error {\n return (\n error instanceof Error &&\n 'code' in error &&\n (error as { code?: unknown }).code === code\n );\n}\n\nclass DirectTransactionHandle implements TransactionHandle {\n readonly transactionId = null;\n #transactionHash: TxHash;\n readonly #transaction: ethers.providers.TransactionResponse;\n\n constructor(transaction: ethers.providers.TransactionResponse) {\n this.#transaction = transaction;\n this.#transactionHash = expectTxHash(transaction.hash);\n }\n\n get transactionHash() {\n return this.#transactionHash;\n }\n\n async wait() {\n try {\n const receipt = await this.#transaction.wait();\n\n const transactionHash = expectTxHash(receipt.transactionHash);\n this.#transactionHash = transactionHash;\n\n return {\n transactionHash,\n transactionId: null,\n };\n } catch (error) {\n if (isTransactionReplacedError(error)) {\n if (error.cancelled) {\n throw TransportError.fromError(error);\n }\n\n const transactionHash = expectTxHash(error.receipt.transactionHash);\n this.#transactionHash = transactionHash;\n\n return {\n transactionHash,\n transactionId: null,\n };\n }\n\n if (isCallExceptionError(error)) {\n throw new TransactionFailedError(\n `Transaction ${this.#transactionHash} reverted`,\n { cause: error },\n );\n }\n\n throw TransportError.fromError(error);\n }\n }\n}\n"]}
@@ -0,0 +1,151 @@
1
+ import { ConditionId } from '@polymarket/bindings';
2
+ export * from '@polymarket/bindings';
3
+ export * from '@polymarket/bindings/clob';
4
+ export { OrderSide, OrderType, SignatureType } from '@polymarket/bindings/clob';
5
+ export * from '@polymarket/bindings/data';
6
+ export * from '@polymarket/bindings/gamma';
7
+ export { WalletType } from '@polymarket/bindings/gamma';
8
+ export * from '@polymarket/bindings/relayer';
9
+ import { EvmAddress } from '@polymarket/types';
10
+ import { U as UserInputError, b as TransactionCall, c as ApiKeyAuthorization } from './types-BcwWqAsH.js';
11
+ export { d as AccountActions, e as AccountIdentity, f as AccountPublicActions, g as AnalyticsActions, h as AuthenticateWithError, i as AuthenticationWorkflow, j as AuthenticationWorkflowRequest, B as BaseClient, k as BasePublicClient, l as BaseSecureClient, m as BeginAuthenticationRequest, n as CancelledSigningError, o as Client, p as ClientActions, q as ClientDecorator, r as CompleteWithError, D as DataActions, s as DeployTransactionHandle, t as DiscoveryActions, E as EnvironmentConfig, F as FreshAuthenticationRequest, I as InsufficientLiquidityError, P as Page, u as PageSizeSchema, v as Paginated, w as PublicActions, x as PublicClient, y as PublicClientOptions, z as PublicWalletActions, R as RateLimitError, G as RequestRejectedError, H as RequestRejectedErrorOptions, J as RewardsActions, K as RewardsPublicActions, S as SecureActions, L as SecureClient, M as SecureWalletActions, N as SessionSnapshot, O as SigningError, Q as TimeoutError, V as TradingActions, W as TransactionFailedError, X as TransactionHandle, Y as TransactionOutcome, Z as TransportError, a as TypedData, _ as TypedDataDomain, $ as TypedDataField, T as TypedDataPayload, a0 as UnexpectedResponseError, a1 as WaitForTransactionError, a2 as WalletDerivationConfig, a3 as accountActions, a4 as allActions, a5 as analyticsActions, a6 as createPublicClient, a7 as dataActions, a8 as discoveryActions, a9 as production, aa as rewardsActions, ab as tradingActions, ac as walletActions } from './types-BcwWqAsH.js';
12
+ import 'zod';
13
+ import 'ox';
14
+
15
+ type Erc20ApprovalCallError = UserInputError;
16
+ /**
17
+ * Creates a transaction call for `approve(address,uint256)` on an ERC-20 token.
18
+ *
19
+ * @throws {@link Erc20ApprovalCallError}
20
+ * Thrown when the approval amount is invalid.
21
+ */
22
+ declare function erc20ApprovalCall(tokenAddress: EvmAddress, spender: EvmAddress, amount: bigint): TransactionCall;
23
+ /**
24
+ * Creates a transaction call for `setApprovalForAll(address,bool)` on an ERC-1155 token.
25
+ */
26
+ declare function erc1155ApprovalForAllCall(tokenAddress: EvmAddress, operator: EvmAddress, approved: boolean): TransactionCall;
27
+ type Erc20TransferCallError = UserInputError;
28
+ /**
29
+ * Creates a transaction call for `transfer(address,uint256)` on an ERC-20 token.
30
+ *
31
+ * @throws {@link Erc20TransferCallError}
32
+ * Thrown when the transfer amount is invalid.
33
+ */
34
+ declare function erc20TransferCall(tokenAddress: EvmAddress, recipient: EvmAddress, amount: bigint): TransactionCall;
35
+ type CtfRedeemPositionsCallError = UserInputError;
36
+ type SplitPositionCallError = UserInputError;
37
+ /**
38
+ * Creates a transaction call for `splitPosition(address,bytes32,bytes32,uint256[],uint256)`.
39
+ * Works with both the Conditional Tokens contract and the neg-risk adapter.
40
+ *
41
+ * @remarks
42
+ * This is a low-level transaction builder that most SDK consumers will not need.
43
+ *
44
+ * @throws {@link SplitPositionCallError}
45
+ * Thrown when the amount is invalid.
46
+ */
47
+ declare function splitPositionCall(targetAddress: EvmAddress, collateralTokenAddress: EvmAddress, conditionId: ConditionId, amount: bigint, negRisk?: boolean): TransactionCall;
48
+ type MergePositionsCallError = UserInputError;
49
+ /**
50
+ * Creates a transaction call for `mergePositions(address,bytes32,bytes32,uint256[],uint256)`.
51
+ * Works with both the Conditional Tokens contract and the neg-risk adapter.
52
+ *
53
+ * @remarks
54
+ * This is a low-level transaction builder that most SDK consumers will not need.
55
+ *
56
+ * @throws {@link MergePositionsCallError}
57
+ * Thrown when the amount is invalid.
58
+ */
59
+ declare function mergePositionsCall(targetAddress: EvmAddress, collateralTokenAddress: EvmAddress, conditionId: ConditionId, amount: bigint, negRisk?: boolean): TransactionCall;
60
+ /**
61
+ * Creates a transaction call for `redeemPositions(address,bytes32,bytes32,uint256[])`
62
+ * on the Conditional Tokens contract.
63
+ *
64
+ * @remarks
65
+ * This is a low-level transaction builder that most SDK consumers will not need.
66
+ *
67
+ * @throws {@link CtfRedeemPositionsCallError}
68
+ * Thrown when the condition is invalid.
69
+ */
70
+ declare function ctfRedeemPositionsCall(conditionalTokensAddress: EvmAddress, collateralTokenAddress: EvmAddress, conditionId: ConditionId): TransactionCall;
71
+ type NegRiskRedeemPositionsCallError = UserInputError;
72
+ /**
73
+ * Creates a transaction call for `redeemPositions(bytes32,uint256[])` on the
74
+ * negative-risk adapter contract.
75
+ *
76
+ * @remarks
77
+ * This is a low-level transaction builder that most SDK consumers will not need.
78
+ *
79
+ * @throws {@link NegRiskRedeemPositionsCallError}
80
+ * Thrown when the condition or redeem amounts are invalid.
81
+ */
82
+ declare function negRiskRedeemPositionsCall(negRiskAdapterAddress: EvmAddress, conditionId: ConditionId, amounts: readonly [bigint, bigint]): TransactionCall;
83
+
84
+ type RelayerApiKeyConfig = {
85
+ key: string;
86
+ address: string;
87
+ };
88
+ type RemoteBuilderSigningConfig = {
89
+ /**
90
+ * URL for the application's remote builder-signing endpoint.
91
+ *
92
+ * This may be an absolute `http` or `https` URL, or a root-relative path
93
+ * such as `/api/builder/sign` in browser environments.
94
+ */
95
+ url: string;
96
+ /**
97
+ * Fetch credential mode for requests to the remote signer.
98
+ *
99
+ * Set this when the signer relies on cookie-backed authentication, especially
100
+ * for cross-origin requests that require `include`.
101
+ */
102
+ credentials?: RequestCredentials;
103
+ /**
104
+ * Additional headers to send to the remote signer.
105
+ *
106
+ * Use this for application-specific authorization such as bearer tokens,
107
+ * tenant headers, or CSRF headers. The SDK always sends JSON.
108
+ */
109
+ headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
110
+ };
111
+ declare function remoteBuilderSigning(config: RemoteBuilderSigningConfig): ApiKeyAuthorization;
112
+ declare function relayerApiKey(config: RelayerApiKeyConfig): ApiKeyAuthorization;
113
+
114
+ /**
115
+ * Builds the canonical HMAC signature for authenticated requests.
116
+ *
117
+ * The signed payload is the raw string concatenation of `timestamp`, `method`,
118
+ * `requestPath`, and, when present, the serialized request `body`, matching the
119
+ * remote signing contract.
120
+ *
121
+ * The `secret` is expected to be base64-encoded and is decoded before signing.
122
+ * The returned signature is base64url-encoded with padding preserved.
123
+ *
124
+ * @example
125
+ * Server-side signing example for builder-authenticated requests:
126
+ *
127
+ * ```ts
128
+ * async function handleSignRequest(request: Request): Promise<Response> {
129
+ * const { body, method, path } = await request.json();
130
+ *
131
+ * const timestamp = Math.floor(Date.now() / 1000);
132
+ * const signature = await buildHmacSignature(
133
+ * process.env.POLY_BUILDER_SECRET!,
134
+ * timestamp,
135
+ * method,
136
+ * path,
137
+ * body,
138
+ * );
139
+ *
140
+ * return Response.json({
141
+ * POLY_BUILDER_API_KEY: process.env.POLY_BUILDER_API_KEY!,
142
+ * POLY_BUILDER_PASSPHRASE: process.env.POLY_BUILDER_PASSPHRASE!,
143
+ * POLY_BUILDER_SIGNATURE: signature,
144
+ * POLY_BUILDER_TIMESTAMP: `${timestamp}`,
145
+ * });
146
+ * }
147
+ * ```
148
+ */
149
+ declare function buildHmacSignature(secret: string, timestamp: number, method: string, requestPath: string, body?: string): Promise<string>;
150
+
151
+ export { ApiKeyAuthorization, type CtfRedeemPositionsCallError, type Erc20ApprovalCallError, type Erc20TransferCallError, type MergePositionsCallError, type NegRiskRedeemPositionsCallError, type RelayerApiKeyConfig, type RemoteBuilderSigningConfig, type SplitPositionCallError, TransactionCall, UserInputError, buildHmacSignature, ctfRedeemPositionsCall, erc1155ApprovalForAllCall, erc20ApprovalCall, erc20TransferCall, mergePositionsCall, negRiskRedeemPositionsCall, relayerApiKey, remoteBuilderSigning, splitPositionCall };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import {h as h$1}from'./chunk-KLADIGW6.js';export{a as accountActions,h as allActions,b as analyticsActions,c as dataActions,d as discoveryActions,e as rewardsActions,f as tradingActions,g as walletActions}from'./chunk-KLADIGW6.js';import {s,K as K$1,j as j$2,n,m,o as o$1}from'./chunk-VQMBZJB5.js';export{a as MAX_UINT256,g as ctfRedeemPositionsCall,i as encodeSafeMultisendCall,c as erc1155ApprovalForAllCall,b as erc20ApprovalCall,d as erc20TransferCall,J as expectTransactionHandle,f as mergePositionsCall,h as negRiskRedeemPositionsCall,e as splitPositionCall}from'./chunk-VQMBZJB5.js';import {j as j$1,d,e,c}from'./chunk-X2E5YUTB.js';export{h as CancelledSigningError,i as InsufficientLiquidityError,e as RateLimitError,d as RequestRejectedError,j as SigningError,f as TimeoutError,g as TransactionFailedError,c as TransportError,b as UnexpectedResponseError,a as UserInputError}from'./chunk-X2E5YUTB.js';export{OrderSide,OrderType,SignatureType}from'@polymarket/bindings/clob';export{WalletType}from'@polymarket/bindings/gamma';import {z as z$1}from'zod';import {ApiKeySchema,EvmAddressSchema}from'@polymarket/bindings';import {expectEvmAddress,expectEvmSignature,ResultAsync,invariant}from'@polymarket/types';import Y from'ky';var O=z$1.object({POLY_BUILDER_API_KEY:z$1.string().min(1),POLY_BUILDER_TIMESTAMP:z$1.string().min(1),POLY_BUILDER_PASSPHRASE:z$1.string().min(1),POLY_BUILDER_SIGNATURE:z$1.string().min(1)});function L(n){return new C(n)}function j(n){return new g(n)}var C=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return true}get supportGasless(){return true}async authorize(e){try{return await this.#r(e)}catch(t){throw j$1.fromError(t,"Could not authorize the builder-authenticated request")}}async#t(){let e=this.#e.headers,t=typeof e=="function"?await e():e,r=new Headers(t);return r.set("content-type","application/json"),r}async#r(e){let t=await fetch(this.#e.url,{body:JSON.stringify({body:e.body,method:e.method,path:e.path}),credentials:this.#e.credentials,headers:await this.#t(),method:"POST",mode:"cors"});if(!t.ok)throw new Error(`Remote signer rejected request with status ${t.status}`);return O.parse(await t.json())}},g=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return false}get supportGasless(){return true}authorize(){return Promise.resolve({RELAYER_API_KEY:this.#e.key,RELAYER_API_KEY_ADDRESS:this.#e.address})}};function K(n){return {domain:{chainId:n.chainId,name:"ClobAuthDomain",version:"1"},message:{address:n.address,message:"This message attests that I control the given wallet",nonce:n.nonce??0,timestamp:`${n.timestamp}`},primaryType:"ClobAuth",types:{ClobAuth:[{name:"address",type:"address"},{name:"timestamp",type:"string"},{name:"nonce",type:"uint256"},{name:"message",type:"string"}]}}}var H={name:"production",chainId:137,walletDerivation:{proxyFactory:expectEvmAddress("0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"),proxyImplementation:expectEvmAddress("0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f"),safeFactory:expectEvmAddress("0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"),safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"},collateralToken:expectEvmAddress("0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"),conditionalTokens:expectEvmAddress("0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"),negRiskAdapter:expectEvmAddress("0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"),standardExchange:expectEvmAddress("0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E"),negRiskExchange:expectEvmAddress("0xC5d563A36AE78145C45a50134d48A1215220f80a"),safeMultisend:expectEvmAddress("0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761"),clob:"https://clob.polymarket.com",relayer:"https://relayer-v2.polymarket.com",gamma:"https://gamma-api.polymarket.com",data:"https://data-api.polymarket.com",relayerMaxPolls:100,relayerPollFrequencyMs:2e3};async function I(n,e,t,r,i){let s=`${e}${t}${r}`;i!==void 0&&(s+=i);let a=await globalThis.crypto.subtle.importKey("raw",_(n),{name:"HMAC",hash:"SHA-256"},false,["sign"]),p=await globalThis.crypto.subtle.sign("HMAC",a,new TextEncoder().encode(s));return F(z(p))}function _(n){let e=n.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),t=atob(e),r=new Uint8Array(t.length);for(let i=0;i<t.length;i+=1)r[i]=t.charCodeAt(i);return r.buffer}function z(n){let e=new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t)}function F(n){return n.replace(/\+/g,"-").replace(/\//g,"_")}var o=class{#e;#t;constructor({root:e,resolveHeaders:t}){this.#e=Y.create({prefixUrl:e,throwHttpErrors:false}),this.#t=t;}get(e,t={}){return this.#n("GET",e,t)}post(e,t={}){return this.#n("POST",e,t)}del(e,t={}){return this.#n("DELETE",e,t)}#r(e){return e.startsWith("/")?e.slice(1):e}#n(e,t,r){return this.#a(this.#i(e,t,r))}async#i(e,t,r){let i=this.#o(e,t,r),s=await this.#t?.(i),a=this.#c(i.headers,s);return i.body!==void 0&&!a.has("content-type")&&a.set("content-type","application/json"),this.#e(this.#r(t),{body:i.body,headers:a,method:e,searchParams:i.params})}#o(e,t,r){return {body:"json"in r?this.#s(r.json):void 0,headers:r.headers,json:"json"in r?r.json:void 0,method:e,params:"params"in r?r.params:void 0,path:t}}#s(e){if(e!==void 0)return JSON.stringify(e)}#c(...e){let t=new Headers;for(let r of e)if(r!==void 0)for(let[i,s]of new Headers(r).entries())t.set(i,s);return t}#a(e$1){return ResultAsync.fromPromise(e$1.then(async t=>{if(t.ok)return t;if(t.status===429)throw new e(`Request to ${t.url} was rate limited`);let r=await this.#l(t);throw new d(r,{status:t.status})}),t=>t instanceof e||t instanceof d?t:c.fromError(t))}async#l(e){if(e.headers.get("content-type")?.includes("application/json")){let{error:r}=await e.clone().json().catch(()=>({}));if(r)return String(r)}let t=await e.clone().text().then(r=>r.trim(),()=>"");return t||`Request to ${e.url} failed with status ${e.status} and unreadable response body`}};var A=class{#e;#t;get context(){return this.#e}get decorators(){return this.#t}get environment(){return this.context.environment}get clob(){return this.context.clob}get relayer(){return this.context.relayer}get gamma(){return this.context.gamma}get data(){return this.context.data}get supportsGasless(){return this.context.apiKey?.supportGasless??false}constructor(e){this.#e=e,this.#t=[];}async resolveClobHeaders(e){return this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):Promise.resolve({})}async resolveRelayerHeaders(e){return this.context.apiKey?.supportGasless?this.context.apiKey.authorize(e):Promise.resolve({})}rememberDecorator(e){this.#t.push(e);}},N=z$1.object({key:ApiKeySchema,passphrase:z$1.string(),secret:z$1.string()}),J=z$1.object({wallet:EvmAddressSchema,credentials:N.optional(),nonce:z$1.number().int().positive().optional()}).superRefine((n,e)=>{n.credentials!==void 0&&n.nonce!==void 0&&e.addIssue({code:"custom",message:"`credentials` and `nonce` are mutually exclusive.",path:["nonce"]});}).transform(n=>n.credentials!==void 0?{wallet:n.wallet,credentials:n.credentials}:n.nonce!==void 0?{wallet:n.wallet,nonce:n.nonce}:{wallet:n.wallet}),h=class extends A{constructor(e){super({apiKey:e.apiKey,environment:e.environment,data:new o({root:e.environment.data}),gamma:new o({root:e.environment.gamma}),clob:new o({root:e.environment.clob,resolveHeaders:t=>this.resolveClobHeaders(t)}),relayer:new o({root:e.environment.relayer,resolveHeaders:t=>this.resolveRelayerHeaders(t)})});}isSecureClient(){return false}isPublicClient(){return true}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}beginAuthentication(e){let t=s(e,J);return Promise.resolve(async function*(){let r=Math.floor(Date.now()/1e3),i=t?.nonce??0,s=expectEvmAddress(yield K$1()),a=expectEvmAddress(t.wallet),p=j$2(this.environment,s,a);if(t.credentials!==void 0){let S=this.#e(t.credentials,p);try{if((await n(S)).includes(t.credentials.key))return S}catch(m){if(!(m instanceof d)||m.status!==401)throw m}}let k=yield {kind:"signAuthMessage",payload:K({address:s,chainId:this.environment.chainId,nonce:i,timestamp:r})},q=await m(this,{address:s,nonce:i,signature:expectEvmSignature(k),timestamp:r});return this.#e(q,p)}.call(this))}#e(e,t){let r=new b({account:t,apiKey:this.context.apiKey,credentials:e,environment:this.environment});for(let i of this.decorators)r.extend(i);return r}},b=class extends A{#e=false;get context(){return invariant(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=true;}constructor(e){super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,clob:new o({root:e.environment.clob,resolveHeaders:t=>this.resolveClobHeaders(t)}),relayer:new o({root:e.environment.relayer,resolveHeaders:t=>this.resolveRelayerHeaders(t)}),gamma:new o({root:e.environment.gamma}),data:new o({root:e.environment.data}),secureClob:new o({resolveHeaders:async t=>({...await this.resolveClobHeaders(t),...await this.#t(t)}),root:e.environment.clob})});}get credentials(){return this.context.credentials}get account(){return this.context.account}get secureClob(){return this.context.secureClob}isSecureClient(){return true}isPublicClient(){return false}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}getSessionSnapshot(){return {wallet:this.account.wallet,credentials:this.credentials}}async endAuthentication(){let{apiKey:e,environment:t}=this.context;await o$1(this),this.endAuthenticationLifecycle();let r=new h({apiKey:e,environment:t});for(let i of this.decorators)r.extend(i);return r}async#t(e){try{let t=Math.floor(Date.now()/1e3);return {POLY_ADDRESS:this.account.signer,POLY_API_KEY:this.credentials.key,POLY_PASSPHRASE:this.credentials.passphrase,POLY_SIGNATURE:await I(this.credentials.secret,t,e.method,e.path,e.body),POLY_TIMESTAMP:`${t}`}}catch(t){throw j$1.fromError(t,"Could not sign the L2-authenticated request")}}};function Z(n={}){return new h({environment:n.environment??H,apiKey:n.apiKey}).extend(h$1)}
2
+ export{I as buildHmacSignature,Z as createPublicClient,H as production,j as relayerApiKey,L as remoteBuilderSigning};//# sourceMappingURL=index.js.map
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/authorization.ts","../src/authentication.ts","../src/environments.ts","../src/hmac.ts","../src/ServiceClient.ts","../src/clients.ts"],"names":["RemoteBuilderSigningResponseSchema","z","remoteBuilderSigning","config","RemoteBuilderAuthorization","relayerApiKey","RelayerApiKeyAuthorization","#config","request","#fetchBuilderKeyHeaders","error","SigningError","#resolveHeaders","headers","resolvedHeaders","requestHeaders","response","createApiKeyAuthTypedDataPayload","production","expectEvmAddress","buildHmacSignature","secret","timestamp","method","requestPath","body","message","cryptoKey","base64ToArrayBuffer","signature","toUrlSafeBase64","arrayBufferToBase64","base64","sanitizedBase64","binaryString","bytes","index","buffer","binary","byte","value","ServiceClient","#client","root","resolveHeaders","ky","path","options","#request","#normalizePath","#toResult","#send","#createRequest","#mergeHeaders","#serializeJson","json","sources","source","key","promise","ResultAsync","RateLimitError","#extractResponseErrorMessage","RequestRejectedError","TransportError","text","AbstractClient","#context","#decorators","context","decorator","BeginAuthenticationCredentialsSchema","ApiKeySchema","BeginAuthenticationRequestSchema","EvmAddressSchema","BasePublicClient","params","parseUserInput","nonce","signer","requestAddress","wallet","identity","resolveAccountIdentity","client","#createSecureClient","fetchApiKeys","credentials","createOrDeriveApiKey","expectEvmSignature","account","BaseSecureClient","#hasEndedAuthentication","invariant","#createL2Headers","apiKey","environment","deleteApiKey","createPublicClient","allActions"],"mappings":"mtCAiCA,IAAMA,CAAAA,CAAqCC,GAAAA,CAAE,OAAO,CAClD,oBAAA,CAAsBA,GAAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,CAAA,CACtC,sBAAA,CAAwBA,IAAE,MAAA,EAAO,CAAE,IAAI,CAAC,CAAA,CACxC,uBAAA,CAAyBA,GAAAA,CAAE,MAAA,EAAO,CAAE,IAAI,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CACpC,MAAA,CAAQ6B,CAAAA,CAAQ,MAClB,CAAC,CAAA,CAAE,MAAA,CAAOoD,GAAU,CACtB","file":"index.js","sourcesContent":["import { z } from 'zod';\nimport { SigningError } from './errors';\nimport type { ApiKeyAuthorization, ApiKeyAuthorizationRequest } from './types';\n\nexport type RelayerApiKeyConfig = {\n key: string;\n address: string;\n};\n\nexport type RemoteBuilderSigningConfig = {\n /**\n * URL for the application's remote builder-signing endpoint.\n *\n * This may be an absolute `http` or `https` URL, or a root-relative path\n * such as `/api/builder/sign` in browser environments.\n */\n url: string;\n /**\n * Fetch credential mode for requests to the remote signer.\n *\n * Set this when the signer relies on cookie-backed authentication, especially\n * for cross-origin requests that require `include`.\n */\n credentials?: RequestCredentials;\n /**\n * Additional headers to send to the remote signer.\n *\n * Use this for application-specific authorization such as bearer tokens,\n * tenant headers, or CSRF headers. The SDK always sends JSON.\n */\n headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);\n};\n\nconst RemoteBuilderSigningResponseSchema = z.object({\n POLY_BUILDER_API_KEY: z.string().min(1),\n POLY_BUILDER_TIMESTAMP: z.string().min(1),\n POLY_BUILDER_PASSPHRASE: z.string().min(1),\n POLY_BUILDER_SIGNATURE: z.string().min(1),\n});\n\nexport function remoteBuilderSigning(\n config: RemoteBuilderSigningConfig,\n): ApiKeyAuthorization {\n return new RemoteBuilderAuthorization(config);\n}\n\nexport function relayerApiKey(\n config: RelayerApiKeyConfig,\n): ApiKeyAuthorization {\n return new RelayerApiKeyAuthorization(config);\n}\n\nclass RemoteBuilderAuthorization implements ApiKeyAuthorization {\n readonly #config: RemoteBuilderSigningConfig;\n\n constructor(config: RemoteBuilderSigningConfig) {\n this.#config = config;\n }\n\n get isBuilderKey(): boolean {\n return true;\n }\n\n get supportGasless(): boolean {\n return true;\n }\n\n async authorize(request: ApiKeyAuthorizationRequest): Promise<HeadersInit> {\n try {\n return await this.#fetchBuilderKeyHeaders(request);\n } catch (error) {\n throw SigningError.fromError(\n error,\n 'Could not authorize the builder-authenticated request',\n );\n }\n }\n\n async #resolveHeaders(): Promise<Headers> {\n const headers = this.#config.headers;\n const resolvedHeaders =\n typeof headers === 'function' ? await headers() : headers;\n const requestHeaders = new Headers(resolvedHeaders);\n\n requestHeaders.set('content-type', 'application/json');\n\n return requestHeaders;\n }\n\n async #fetchBuilderKeyHeaders(\n request: ApiKeyAuthorizationRequest,\n ): Promise<HeadersInit> {\n const response = await fetch(this.#config.url, {\n body: JSON.stringify({\n body: request.body,\n method: request.method,\n path: request.path,\n }),\n credentials: this.#config.credentials,\n headers: await this.#resolveHeaders(),\n method: 'POST',\n mode: 'cors',\n });\n\n if (!response.ok) {\n throw new Error(\n `Remote signer rejected request with status ${response.status}`,\n );\n }\n\n return RemoteBuilderSigningResponseSchema.parse(await response.json());\n }\n}\n\nclass RelayerApiKeyAuthorization implements ApiKeyAuthorization {\n readonly #config: RelayerApiKeyConfig;\n\n constructor(config: RelayerApiKeyConfig) {\n this.#config = config;\n }\n\n get isBuilderKey(): boolean {\n return false;\n }\n\n get supportGasless(): boolean {\n return true;\n }\n\n authorize(): Promise<HeadersInit> {\n return Promise.resolve({\n RELAYER_API_KEY: this.#config.key,\n RELAYER_API_KEY_ADDRESS: this.#config.address,\n });\n }\n}\n","import type { EvmAddress } from '@polymarket/types';\nimport type { TypedDataPayload } from './types';\n\n/** @internal */\nexport type CreateApiKeyAuthTypedDataPayloadRequest = {\n address: EvmAddress;\n chainId: number;\n nonce?: number;\n timestamp: number;\n};\n\n/** @internal */\nexport function createApiKeyAuthTypedDataPayload(\n request: CreateApiKeyAuthTypedDataPayloadRequest,\n): TypedDataPayload {\n return {\n domain: {\n chainId: request.chainId,\n name: 'ClobAuthDomain',\n version: '1',\n },\n message: {\n address: request.address,\n message: 'This message attests that I control the given wallet',\n nonce: request.nonce ?? 0,\n timestamp: `${request.timestamp}`,\n },\n primaryType: 'ClobAuth',\n types: {\n ClobAuth: [\n { name: 'address', type: 'address' },\n { name: 'timestamp', type: 'string' },\n { name: 'nonce', type: 'uint256' },\n { name: 'message', type: 'string' },\n ],\n },\n };\n}\n","import { type EvmAddress, expectEvmAddress } from '@polymarket/types';\nimport type { Hex } from 'ox';\n\nexport type WalletDerivationConfig = {\n proxyFactory: EvmAddress;\n proxyImplementation: EvmAddress;\n safeFactory: EvmAddress;\n safeInitCodeHash: Hex.Hex;\n};\n\nexport type EnvironmentConfig = {\n name: string;\n chainId: number;\n /** @internal */\n walletDerivation: WalletDerivationConfig;\n /** @internal */\n collateralToken: EvmAddress;\n /** @internal */\n conditionalTokens: EvmAddress;\n /** @internal */\n negRiskAdapter: EvmAddress;\n /** @internal */\n standardExchange: EvmAddress;\n /** @internal */\n negRiskExchange: EvmAddress;\n /** @internal */\n safeMultisend: EvmAddress;\n /** @internal */\n clob: string;\n /** @internal */\n relayer: string;\n /** @internal */\n gamma: string;\n /** @internal */\n data: string;\n /** @internal */\n relayerMaxPolls: number;\n /** @internal */\n relayerPollFrequencyMs: number;\n};\n\n/**\n * The production environment configuration.\n */\nexport const production: EnvironmentConfig = {\n name: 'production',\n chainId: 137,\n walletDerivation: {\n proxyFactory: expectEvmAddress(\n '0xaB45c5A4B0c941a2F231C04C3f49182e1A254052',\n ),\n proxyImplementation: expectEvmAddress(\n '0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f',\n ),\n safeFactory: expectEvmAddress('0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b'),\n safeInitCodeHash:\n '0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf',\n },\n collateralToken: expectEvmAddress(\n '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174',\n ),\n conditionalTokens: expectEvmAddress(\n '0x4D97DCd97eC945f40cF65F87097ACe5EA0476045',\n ),\n negRiskAdapter: expectEvmAddress(\n '0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296',\n ),\n standardExchange: expectEvmAddress(\n '0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E',\n ),\n negRiskExchange: expectEvmAddress(\n '0xC5d563A36AE78145C45a50134d48A1215220f80a',\n ),\n safeMultisend: expectEvmAddress('0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761'),\n clob: 'https://clob.polymarket.com',\n relayer: 'https://relayer-v2.polymarket.com',\n gamma: 'https://gamma-api.polymarket.com',\n data: 'https://data-api.polymarket.com',\n relayerMaxPolls: 100,\n relayerPollFrequencyMs: 2000,\n};\n","/**\n * Builds the canonical HMAC signature for authenticated requests.\n *\n * The signed payload is the raw string concatenation of `timestamp`, `method`,\n * `requestPath`, and, when present, the serialized request `body`, matching the\n * remote signing contract.\n *\n * The `secret` is expected to be base64-encoded and is decoded before signing.\n * The returned signature is base64url-encoded with padding preserved.\n *\n * @example\n * Server-side signing example for builder-authenticated requests:\n *\n * ```ts\n * async function handleSignRequest(request: Request): Promise<Response> {\n * const { body, method, path } = await request.json();\n *\n * const timestamp = Math.floor(Date.now() / 1000);\n * const signature = await buildHmacSignature(\n * process.env.POLY_BUILDER_SECRET!,\n * timestamp,\n * method,\n * path,\n * body,\n * );\n *\n * return Response.json({\n * POLY_BUILDER_API_KEY: process.env.POLY_BUILDER_API_KEY!,\n * POLY_BUILDER_PASSPHRASE: process.env.POLY_BUILDER_PASSPHRASE!,\n * POLY_BUILDER_SIGNATURE: signature,\n * POLY_BUILDER_TIMESTAMP: `${timestamp}`,\n * });\n * }\n * ```\n */\nexport async function buildHmacSignature(\n secret: string,\n timestamp: number,\n method: string,\n requestPath: string,\n body?: string,\n): Promise<string> {\n let message = `${timestamp}${method}${requestPath}`;\n\n if (body !== undefined) {\n message += body;\n }\n\n const cryptoKey = await globalThis.crypto.subtle.importKey(\n 'raw',\n base64ToArrayBuffer(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const signature = await globalThis.crypto.subtle.sign(\n 'HMAC',\n cryptoKey,\n new TextEncoder().encode(message),\n );\n\n return toUrlSafeBase64(arrayBufferToBase64(signature));\n}\n\nfunction base64ToArrayBuffer(base64: string): ArrayBuffer {\n const sanitizedBase64 = base64\n .replace(/-/g, '+')\n .replace(/_/g, '/')\n .replace(/[^A-Za-z0-9+/=]/g, '');\n const binaryString = atob(sanitizedBase64);\n const bytes = new Uint8Array(binaryString.length);\n\n for (let index = 0; index < binaryString.length; index += 1) {\n bytes[index] = binaryString.charCodeAt(index);\n }\n\n return bytes.buffer;\n}\n\nfunction arrayBufferToBase64(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer);\n let binary = '';\n\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n\n return btoa(binary);\n}\n\nfunction toUrlSafeBase64(value: string): string {\n return value.replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n","import { ResultAsync } from '@polymarket/types';\nimport ky, { type KyInstance } from 'ky';\nimport { RateLimitError, RequestRejectedError, TransportError } from './errors';\n\nexport type ServiceRequest = {\n method: 'DELETE' | 'GET' | 'POST';\n path: string;\n body?: string;\n headers?: HeadersInit;\n json?: unknown;\n params?: URLSearchParams;\n};\n\nexport type RequestHeadersResolver = (\n request: ServiceRequest,\n) => Promise<HeadersInit>;\n\nexport type ServiceClientConfig = {\n root: string;\n resolveHeaders?: RequestHeadersResolver;\n};\n\nexport type ServiceClientGetOptions = {\n headers?: HeadersInit;\n params?: URLSearchParams;\n};\n\nexport type ServiceClientPostOptions = {\n headers?: HeadersInit;\n json?: unknown;\n};\n\nexport type ServiceClientDeleteOptions = {\n headers?: HeadersInit;\n json?: unknown;\n params?: URLSearchParams;\n};\n\n/**\n * Internal wrapper around a service-scoped `ky` instance.\n */\nexport class ServiceClient {\n readonly #client: KyInstance;\n readonly #resolveHeaders?: RequestHeadersResolver;\n\n constructor({ root, resolveHeaders }: ServiceClientConfig) {\n this.#client = ky.create({ prefixUrl: root, throwHttpErrors: false });\n this.#resolveHeaders = resolveHeaders;\n }\n\n get(\n path: string,\n options: ServiceClientGetOptions = {},\n ): ResultAsync<\n Response,\n RateLimitError | RequestRejectedError | TransportError\n > {\n return this.#request('GET', path, options);\n }\n\n post(\n path: string,\n options: ServiceClientPostOptions = {},\n ): ResultAsync<\n Response,\n RateLimitError | RequestRejectedError | TransportError\n > {\n return this.#request('POST', path, options);\n }\n\n del(\n path: string,\n options: ServiceClientDeleteOptions = {},\n ): ResultAsync<\n Response,\n RateLimitError | RequestRejectedError | TransportError\n > {\n return this.#request('DELETE', path, options);\n }\n\n #normalizePath(path: string) {\n return path.startsWith('/') ? path.slice(1) : path;\n }\n\n #request(\n method: ServiceRequest['method'],\n path: string,\n options:\n | ServiceClientDeleteOptions\n | ServiceClientGetOptions\n | ServiceClientPostOptions,\n ): ResultAsync<\n Response,\n RateLimitError | RequestRejectedError | TransportError\n > {\n return this.#toResult(this.#send(method, path, options));\n }\n\n async #send(\n method: ServiceRequest['method'],\n path: string,\n options:\n | ServiceClientDeleteOptions\n | ServiceClientGetOptions\n | ServiceClientPostOptions,\n ): Promise<Response> {\n const request = this.#createRequest(method, path, options);\n const resolvedHeaders = await this.#resolveHeaders?.(request);\n const headers = this.#mergeHeaders(request.headers, resolvedHeaders);\n\n if (request.body !== undefined && !headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n\n return this.#client(this.#normalizePath(path), {\n body: request.body,\n headers,\n method,\n searchParams: request.params,\n });\n }\n\n #createRequest(\n method: ServiceRequest['method'],\n path: string,\n options:\n | ServiceClientDeleteOptions\n | ServiceClientGetOptions\n | ServiceClientPostOptions,\n ): ServiceRequest {\n return {\n body: 'json' in options ? this.#serializeJson(options.json) : undefined,\n headers: options.headers,\n json: 'json' in options ? options.json : undefined,\n method,\n params: 'params' in options ? options.params : undefined,\n path,\n };\n }\n\n #serializeJson(json: unknown): string | undefined {\n if (json === undefined) {\n return undefined;\n }\n\n return JSON.stringify(json);\n }\n\n #mergeHeaders(...sources: Array<HeadersInit | undefined>): Headers {\n const headers = new Headers();\n\n for (const source of sources) {\n if (source === undefined) {\n continue;\n }\n\n for (const [key, value] of new Headers(source).entries()) {\n headers.set(key, value);\n }\n }\n\n return headers;\n }\n\n #toResult(\n promise: Promise<Response>,\n ): ResultAsync<\n Response,\n | RateLimitError\n | RequestRejectedError\n | RequestRejectedError\n | TransportError\n > {\n return ResultAsync.fromPromise(\n promise.then(async (response) => {\n if (response.ok) {\n return response;\n }\n\n if (response.status === 429) {\n throw new RateLimitError(\n `Request to ${response.url} was rate limited`,\n );\n }\n\n const message = await this.#extractResponseErrorMessage(response);\n throw new RequestRejectedError(message, {\n status: response.status,\n });\n }),\n (error) => {\n if (\n error instanceof RateLimitError ||\n error instanceof RequestRejectedError\n ) {\n return error;\n }\n\n return TransportError.fromError(error);\n },\n );\n }\n\n async #extractResponseErrorMessage(response: Response) {\n if (response.headers.get('content-type')?.includes('application/json')) {\n const { error } = await response\n .clone()\n .json()\n .catch(() => ({}));\n if (error) return String(error);\n }\n\n const text = await response\n .clone()\n .text()\n .then(\n (body) => body.trim(),\n () => '',\n );\n\n if (text) {\n return text;\n }\n\n return `Request to ${response.url} failed with status ${response.status} and unreadable response body`;\n }\n}\n","import { ApiKeySchema, EvmAddressSchema } from '@polymarket/bindings';\nimport type { ApiKeyCreds } from '@polymarket/bindings/clob';\nimport {\n expectEvmAddress,\n expectEvmSignature,\n invariant,\n type Prettify,\n} from '@polymarket/types';\nimport { z } from 'zod';\nimport type { AccountIdentity } from './account';\nimport { resolveAccountIdentity } from './account';\nimport {\n createOrDeriveApiKey,\n deleteApiKey,\n fetchApiKeys,\n} from './actions/auth';\nimport { createApiKeyAuthTypedDataPayload } from './authentication';\nimport {\n allActions,\n type PublicActions,\n type SecureActions,\n} from './decorators';\nimport { type EnvironmentConfig, production } from './environments';\nimport { RequestRejectedError, SigningError } from './errors';\nimport { buildHmacSignature } from './hmac';\nimport { parseUserInput } from './input';\nimport type { ServiceRequest } from './ServiceClient';\nimport { ServiceClient } from './ServiceClient';\nimport type { ApiKeyAuthorization } from './types';\nimport { type AuthenticationWorkflow, requestAddress } from './workflow';\n\ntype PublicContext = {\n /** @internal */\n apiKey?: ApiKeyAuthorization;\n /** @internal */\n environment: EnvironmentConfig;\n /** @internal */\n clob: ServiceClient;\n /** @internal */\n relayer: ServiceClient;\n /** @internal */\n gamma: ServiceClient;\n /** @internal */\n data: ServiceClient;\n};\n\n// biome-ignore lint/complexity/noBannedTypes: intentional\nexport type ClientActions = {};\n\nexport type ClientDecorator<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> = {\n (client: BasePublicClient<ClientActions, ClientActions>): TPublicActions;\n (client: BaseSecureClient<ClientActions, ClientActions>): TSecureActions;\n};\n\ntype DecoratorPublicActions<TDecorator extends ClientDecorator> =\n TDecorator extends ClientDecorator<\n infer TPublicActions,\n infer _TSecureActions\n >\n ? TPublicActions\n : never;\n\ntype DecoratorSecureActions<TDecorator extends ClientDecorator> =\n TDecorator extends ClientDecorator<\n infer _TPublicActions,\n infer TSecureActions\n >\n ? TSecureActions\n : never;\n\nabstract class AbstractClient<TContext extends PublicContext> {\n // Keep the backing context off the public object shape so accidental\n // client logs do not print secure credentials.\n readonly #context: TContext;\n readonly #decorators: ClientDecorator[];\n\n protected get context(): TContext {\n return this.#context;\n }\n\n protected get decorators(): readonly ClientDecorator[] {\n return this.#decorators;\n }\n\n /** @internal */\n get environment(): EnvironmentConfig {\n return this.context.environment;\n }\n\n /** @internal */\n get clob(): ServiceClient {\n return this.context.clob;\n }\n\n /** @internal */\n get relayer(): ServiceClient {\n return this.context.relayer;\n }\n\n /** @internal */\n get gamma(): ServiceClient {\n return this.context.gamma;\n }\n\n /** @internal */\n get data(): ServiceClient {\n return this.context.data;\n }\n\n /** @internal */\n get supportsGasless(): boolean {\n return this.context.apiKey?.supportGasless ?? false;\n }\n\n constructor(context: TContext) {\n this.#context = context;\n this.#decorators = [];\n }\n\n protected async resolveClobHeaders(\n request: ServiceRequest,\n ): Promise<HeadersInit> {\n if (this.context.apiKey?.isBuilderKey) {\n return this.context.apiKey.authorize(request);\n }\n return Promise.resolve({});\n }\n\n protected async resolveRelayerHeaders(\n request: ServiceRequest,\n ): Promise<HeadersInit> {\n if (this.context.apiKey?.supportGasless) {\n return this.context.apiKey.authorize(request);\n }\n return Promise.resolve({});\n }\n\n protected rememberDecorator(decorator: ClientDecorator): void {\n this.#decorators.push(decorator);\n }\n}\n\nconst BeginAuthenticationCredentialsSchema = z.object({\n key: ApiKeySchema,\n passphrase: z.string(),\n secret: z.string(),\n});\n\n/**\n * Persistable authenticated session state that can later be passed to\n * {@link PublicClient.beginAuthentication}.\n */\nexport type SessionSnapshot = {\n /**\n * Wallet address to authenticate as.\n *\n * Pass the signer address itself to authenticate as an EOA account.\n */\n wallet: string;\n\n /**\n * Existing API credentials to reuse when they remain valid.\n */\n credentials: ApiKeyCreds;\n nonce?: never;\n};\n\nexport type FreshAuthenticationRequest = {\n /**\n * Wallet address to authenticate as.\n *\n * Pass the signer address itself to authenticate as an EOA account.\n */\n wallet: string;\n\n /**\n * Nonce used when creating or deriving fresh credentials.\n *\n * @defaultValue 0\n */\n nonce?: number;\n credentials?: never;\n};\n\nexport type BeginAuthenticationRequest =\n | SessionSnapshot\n | FreshAuthenticationRequest;\n\nconst BeginAuthenticationRequestSchema: z.ZodType<BeginAuthenticationRequest> =\n z\n .object({\n wallet: EvmAddressSchema,\n credentials: BeginAuthenticationCredentialsSchema.optional(),\n nonce: z.number().int().positive().optional(),\n })\n .superRefine((value, context) => {\n if (value.credentials !== undefined && value.nonce !== undefined) {\n context.addIssue({\n code: 'custom',\n message: '`credentials` and `nonce` are mutually exclusive.',\n path: ['nonce'],\n });\n }\n })\n .transform((value): BeginAuthenticationRequest => {\n if (value.credentials !== undefined) {\n return {\n wallet: value.wallet,\n credentials: value.credentials,\n };\n }\n\n if (value.nonce !== undefined) {\n return {\n wallet: value.wallet,\n nonce: value.nonce,\n };\n }\n\n return {\n wallet: value.wallet,\n };\n });\n\ntype PublicClientConfig = {\n environment: EnvironmentConfig;\n apiKey?: ApiKeyAuthorization;\n};\n\nclass BasePublicClient<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> extends AbstractClient<PublicContext> {\n constructor(config: PublicClientConfig) {\n super({\n apiKey: config.apiKey,\n environment: config.environment,\n data: new ServiceClient({ root: config.environment.data }),\n gamma: new ServiceClient({ root: config.environment.gamma }),\n clob: new ServiceClient({\n root: config.environment.clob,\n resolveHeaders: (request) => this.resolveClobHeaders(request),\n }),\n relayer: new ServiceClient({\n root: config.environment.relayer,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n }),\n });\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link SecureClient}.\n *\n * @example\n * ```ts\n * if (client.isSecureClient()) {\n * client.credentials; // SecureClient\n * }\n * ```\n */\n isSecureClient(): this is BaseSecureClient<TPublicActions, TSecureActions> {\n return false;\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link PublicClient}.\n *\n * @example\n * ```ts\n * if (client.isPublicClient()) {\n * client.beginAuthentication(...); // PublicClient\n * }\n * ```\n */\n isPublicClient(): this is BasePublicClient<TPublicActions, TSecureActions> {\n return true;\n }\n\n /**\n * Returns a client typed with the methods contributed by the decorator.\n */\n extend<TDecorator extends ClientDecorator>(\n decorator: TDecorator,\n ): PublicClient<\n Prettify<TPublicActions & DecoratorPublicActions<TDecorator>>,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n > {\n this.rememberDecorator(decorator);\n Object.assign(this, decorator(this));\n return this as unknown as PublicClient<\n Prettify<TPublicActions & DecoratorPublicActions<TDecorator>>,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n >;\n }\n\n /**\n * Begins an authentication workflow that produces a {@link SecureClient}.\n *\n * @remarks\n * Pass a {@link SessionSnapshot} to reuse stored credentials when they remain\n * valid. If the stored credential is no longer valid, the workflow falls back\n * to fresh authentication.\n */\n beginAuthentication(\n request: BeginAuthenticationRequest,\n ): Promise<\n AuthenticationWorkflow<SecureClient<TPublicActions, TSecureActions>>\n > {\n const params = parseUserInput(request, BeginAuthenticationRequestSchema);\n\n return Promise.resolve(\n async function* (\n this: PublicClient<TPublicActions, TSecureActions>,\n ): AuthenticationWorkflow<SecureClient<TPublicActions, TSecureActions>> {\n const timestamp = Math.floor(Date.now() / 1000);\n const nonce = params?.nonce ?? 0;\n const signer = expectEvmAddress(yield requestAddress());\n const wallet = expectEvmAddress(params.wallet);\n const identity = resolveAccountIdentity(\n this.environment,\n signer,\n wallet,\n );\n\n if (params.credentials !== undefined) {\n const client = this.#createSecureClient(params.credentials, identity);\n\n try {\n const apiKeys = await fetchApiKeys(client);\n if (apiKeys.includes(params.credentials.key)) {\n return client;\n }\n } catch (error) {\n if (\n !(error instanceof RequestRejectedError) ||\n error.status !== 401\n ) {\n throw error;\n }\n }\n }\n\n const signature = yield {\n kind: 'signAuthMessage',\n payload: createApiKeyAuthTypedDataPayload({\n address: signer,\n chainId: this.environment.chainId,\n nonce,\n timestamp,\n }),\n };\n const credentials = await createOrDeriveApiKey(this, {\n address: signer,\n nonce,\n signature: expectEvmSignature(signature),\n timestamp,\n });\n\n return this.#createSecureClient(credentials, identity);\n }.call(this as unknown as PublicClient<TPublicActions, TSecureActions>),\n );\n }\n\n #createSecureClient(\n credentials: ApiKeyCreds,\n account: AccountIdentity,\n ): SecureClient<TPublicActions, TSecureActions> {\n const client = new BaseSecureClient({\n account: account,\n apiKey: this.context.apiKey,\n credentials,\n environment: this.environment,\n });\n\n for (const decorator of this.decorators) {\n client.extend(decorator);\n }\n\n return client as SecureClient<TPublicActions, TSecureActions>;\n }\n}\n\nclass BaseSecureClient<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> extends AbstractClient<SecureContext> {\n #hasEndedAuthentication = false;\n\n /**\n * @remarks This is the choking point for all requests, so we can ensure that once\n * `endAuthentication` is called, no further authenticated requests can be made with this client instance.\n */\n protected override get context(): SecureContext {\n invariant(\n !this.#hasEndedAuthentication,\n 'This client has ended authentication and can no longer be used.',\n );\n\n return super.context;\n }\n\n protected endAuthenticationLifecycle(): void {\n this.#hasEndedAuthentication = true;\n }\n\n constructor(config: SecureClientConfig) {\n super({\n account: config.account,\n credentials: config.credentials,\n apiKey: config.apiKey,\n environment: config.environment,\n clob: new ServiceClient({\n root: config.environment.clob,\n resolveHeaders: (request) => this.resolveClobHeaders(request),\n }),\n relayer: new ServiceClient({\n root: config.environment.relayer,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n }),\n gamma: new ServiceClient({ root: config.environment.gamma }),\n data: new ServiceClient({ root: config.environment.data }),\n secureClob: new ServiceClient({\n resolveHeaders: async (request) => ({\n ...(await this.resolveClobHeaders(request)),\n ...(await this.#createL2Headers(request)),\n }),\n root: config.environment.clob,\n }),\n });\n }\n\n /** @internal */\n get credentials(): ApiKeyCreds {\n return this.context.credentials;\n }\n\n /** @internal */\n get account(): AccountIdentity {\n return this.context.account;\n }\n\n /** @internal */\n get secureClob(): ServiceClient {\n return this.context.secureClob;\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link SecureClient}.\n *\n * @example\n * ```ts\n * if (client.isSecureClient()) {\n * client.credentials; // SecureClient\n * }\n * ```\n */\n isSecureClient(): this is BaseSecureClient<TPublicActions, TSecureActions> {\n return true;\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link PublicClient}.\n *\n * @example\n * ```ts\n * if (client.isPublicClient()) {\n * client.beginAuthentication(...); // PublicClient\n * }\n * ```\n */\n isPublicClient(): this is BasePublicClient<TPublicActions, TSecureActions> {\n return false;\n }\n\n /**\n * Returns a secure client typed with the methods contributed by the decorator.\n */\n extend<TDecorator extends ClientDecorator>(\n decorator: TDecorator,\n ): SecureClient<\n TPublicActions,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n > {\n this.rememberDecorator(decorator);\n Object.assign(this, decorator(this));\n\n return this as unknown as SecureClient<\n TPublicActions,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n >;\n }\n\n /**\n * Returns a persistable snapshot of the current authenticated session.\n *\n * @remarks\n * Pass the returned snapshot to {@link PublicClient.beginAuthentication} to\n * reuse the current session in a later authentication attempt. Capture the\n * snapshot before calling {@link endAuthentication}; ending authentication\n * revokes the current credential, so reusing an older snapshot will fall back\n * to fresh authentication.\n *\n * @example\n * ```ts\n * const snapshot = secureClient.getSessionSnapshot();\n * ```\n */\n getSessionSnapshot(): SessionSnapshot {\n return {\n wallet: this.account.wallet,\n credentials: this.credentials,\n };\n }\n\n /**\n * Ends authentication for this client and returns a public client.\n *\n * @remarks\n * This revokes the current authenticated credential and invalidates the\n * current `SecureClient` instance.\n *\n * @example\n * ```ts\n * const publicClient = await secureClient.endAuthentication();\n * ```\n */\n async endAuthentication(): Promise<\n PublicClient<TPublicActions, TSecureActions>\n > {\n const { apiKey, environment } = this.context;\n\n await deleteApiKey(this);\n this.endAuthenticationLifecycle();\n\n const client = new BasePublicClient({\n apiKey,\n environment,\n });\n\n for (const decorator of this.decorators) {\n client.extend(decorator);\n }\n\n return client as PublicClient<TPublicActions, TSecureActions>;\n }\n\n async #createL2Headers(request: ServiceRequest): Promise<HeadersInit> {\n try {\n const timestamp = Math.floor(Date.now() / 1000);\n\n return {\n POLY_ADDRESS: this.account.signer,\n POLY_API_KEY: this.credentials.key,\n POLY_PASSPHRASE: this.credentials.passphrase,\n POLY_SIGNATURE: await buildHmacSignature(\n this.credentials.secret,\n timestamp,\n request.method,\n request.path,\n request.body,\n ),\n POLY_TIMESTAMP: `${timestamp}`,\n };\n } catch (error) {\n throw SigningError.fromError(\n error,\n 'Could not sign the L2-authenticated request',\n );\n }\n }\n}\n\ntype SecureContext = PublicContext & {\n /** @internal */\n account: AccountIdentity;\n /** @internal */\n credentials: ApiKeyCreds;\n /** @internal */\n secureClob: ServiceClient;\n};\n\ntype SecureClientConfig = PublicClientConfig & {\n account: AccountIdentity;\n credentials: ApiKeyCreds;\n};\n\nexport type PublicClient<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> = BasePublicClient<TPublicActions, TSecureActions> & TPublicActions;\n\nexport type SecureClient<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> = BaseSecureClient<TPublicActions, TSecureActions> & TSecureActions;\n\nexport { BasePublicClient, BaseSecureClient };\n\nexport type BaseClient<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> =\n | BasePublicClient<TPublicActions, TSecureActions>\n | BaseSecureClient<TPublicActions, TSecureActions>;\n\nexport type Client<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> =\n | PublicClient<TPublicActions, TSecureActions>\n | SecureClient<TPublicActions, TSecureActions>;\n\nexport type PublicClientOptions = {\n /**\n * The environment configuration used by the client.\n *\n * @defaultValue `production`\n */\n environment?: EnvironmentConfig;\n\n /**\n * Optional request authorization applied by the client when needed.\n */\n apiKey?: ApiKeyAuthorization;\n};\n\n/**\n * Creates a new `PublicClient` instance.\n *\n * @example\n * ```ts\n * const client = createPublicClient();\n * ```\n */\nexport function createPublicClient(\n options: PublicClientOptions = {},\n): PublicClient<PublicActions, SecureActions> {\n return new BasePublicClient({\n environment: options.environment ?? production,\n apiKey: options.apiKey,\n }).extend(allActions);\n}\n"]}
package/dist/node.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import { A as ApiKeyAuthorization } from './types-Bg5Leu3D.js';
2
+ import '@polymarket/bindings';
3
+ import '@polymarket/types';
4
+
5
+ type BuilderApiKeyCreds = {
6
+ key: string;
7
+ secret: string;
8
+ passphrase: string;
9
+ };
10
+ declare function builderApiKey(options: BuilderApiKeyCreds): ApiKeyAuthorization;
11
+
12
+ export { type BuilderApiKeyCreds, builderApiKey };
package/dist/node.js ADDED
@@ -0,0 +1,3 @@
1
+ import {e}from'./chunk-DBVGNMB5.js';import g from'process';import {invariant}from'@polymarket/types';async function u(t,e,r,i,n){let s=`${e}${r}${i}`;n!==void 0&&(s+=n);let y=await globalThis.crypto.subtle.importKey("raw",l(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),c=await globalThis.crypto.subtle.sign("HMAC",y,new TextEncoder().encode(s));return f(d(c))}function l(t){let e=t.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),r=atob(e),i=new Uint8Array(r.length);for(let n=0;n<r.length;n+=1)i[n]=r.charCodeAt(n);return i.buffer}function d(t){let e=new Uint8Array(t),r="";for(let i of e)r+=String.fromCharCode(i);return btoa(r)}function f(t){return t.replace(/\+/g,"-").replace(/\//g,"_")}invariant(g.release.name==="node","The @polymarket/client/node entrypoint requires a Node.js runtime.");invariant(typeof window>"u"&&typeof document>"u","The @polymarket/client/node entrypoint cannot be imported in a browser-like runtime.");function K(t){return new o(t)}var o=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return true}get supportGasless(){return true}async authorize(e){return this.#r(e)}async#r(e$1){try{let r=Math.floor(Date.now()/1e3);return {POLY_BUILDER_API_KEY:this.#e.key,POLY_BUILDER_PASSPHRASE:this.#e.passphrase,POLY_BUILDER_SIGNATURE:await u(this.#e.secret,r,e$1.method,e$1.path,e$1.body),POLY_BUILDER_TIMESTAMP:`${r}`}}catch(r){throw e.fromError(r,"Could not sign the builder-authenticated request")}}};
2
+ export{K as builderApiKey};//# sourceMappingURL=node.js.map
3
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hmac.ts","../src/node.ts"],"names":["buildHmacSignature","secret","timestamp","method","requestPath","body","message","cryptoKey","base64ToArrayBuffer","signature","toUrlSafeBase64","arrayBufferToBase64","base64","sanitizedBase64","binaryString","bytes","index","buffer","binary","byte","value","invariant","process","builderApiKey","options","LocalBuilderApiKey","#credentials","credentials","request","#authorize","error","SigningError"],"mappings":"qGAmCA,eAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,EACiB,CACjB,IA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A,CAAQ,KACRA,GAAAA,CAAQ,IACV,CAAA,CACA,sBAAA,CAAwB,CAAA,EAAG1B,CAAS,CAAA,CACtC,CACF,OAAS4B,CAAAA,CAAO,CACd,MAAMC,CAAAA,CAAa,SAAA,CACjBD,CAAAA,CACA,kDACF,CACF,CACF,CACF,CAAA","file":"node.js","sourcesContent":["/**\n * Builds the canonical HMAC signature for authenticated requests.\n *\n * The signed payload is the raw string concatenation of `timestamp`, `method`,\n * `requestPath`, and, when present, the serialized request `body`, matching the\n * remote signing contract.\n *\n * The `secret` is expected to be base64-encoded and is decoded before signing.\n * The returned signature is base64url-encoded with padding preserved.\n *\n * @example\n * Server-side signing example for builder-authenticated requests:\n *\n * ```ts\n * async function handleSignRequest(request: Request): Promise<Response> {\n * const { body, method, path } = await request.json();\n *\n * const timestamp = Math.floor(Date.now() / 1000);\n * const signature = await buildHmacSignature(\n * process.env.POLY_BUILDER_SECRET!,\n * timestamp,\n * method,\n * path,\n * body,\n * );\n *\n * return Response.json({\n * POLY_BUILDER_API_KEY: process.env.POLY_BUILDER_API_KEY!,\n * POLY_BUILDER_PASSPHRASE: process.env.POLY_BUILDER_PASSPHRASE!,\n * POLY_BUILDER_SIGNATURE: signature,\n * POLY_BUILDER_TIMESTAMP: `${timestamp}`,\n * });\n * }\n * ```\n */\nexport async function buildHmacSignature(\n secret: string,\n timestamp: number,\n method: string,\n requestPath: string,\n body?: string,\n): Promise<string> {\n let message = `${timestamp}${method}${requestPath}`;\n\n if (body !== undefined) {\n message += body;\n }\n\n const cryptoKey = await globalThis.crypto.subtle.importKey(\n 'raw',\n base64ToArrayBuffer(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const signature = await globalThis.crypto.subtle.sign(\n 'HMAC',\n cryptoKey,\n new TextEncoder().encode(message),\n );\n\n return toUrlSafeBase64(arrayBufferToBase64(signature));\n}\n\nfunction base64ToArrayBuffer(base64: string): ArrayBuffer {\n const sanitizedBase64 = base64\n .replace(/-/g, '+')\n .replace(/_/g, '/')\n .replace(/[^A-Za-z0-9+/=]/g, '');\n const binaryString = atob(sanitizedBase64);\n const bytes = new Uint8Array(binaryString.length);\n\n for (let index = 0; index < binaryString.length; index += 1) {\n bytes[index] = binaryString.charCodeAt(index);\n }\n\n return bytes.buffer;\n}\n\nfunction arrayBufferToBase64(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer);\n let binary = '';\n\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n\n return btoa(binary);\n}\n\nfunction toUrlSafeBase64(value: string): string {\n return value.replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n","import process from 'node:process';\nimport { invariant } from '@polymarket/types';\n\nimport { SigningError } from './errors';\nimport { buildHmacSignature } from './hmac';\nimport type { ApiKeyAuthorization, ApiKeyAuthorizationRequest } from './types';\n\ninvariant(\n process.release.name === 'node',\n 'The @polymarket/client/node entrypoint requires a Node.js runtime.',\n);\ninvariant(\n typeof window === 'undefined' && typeof document === 'undefined',\n 'The @polymarket/client/node entrypoint cannot be imported in a browser-like runtime.',\n);\n\nexport type BuilderApiKeyCreds = {\n key: string;\n secret: string;\n passphrase: string;\n};\n\nexport function builderApiKey(\n options: BuilderApiKeyCreds,\n): ApiKeyAuthorization {\n return new LocalBuilderApiKey(options);\n}\n\nclass LocalBuilderApiKey implements ApiKeyAuthorization {\n readonly #credentials: BuilderApiKeyCreds;\n\n constructor(credentials: BuilderApiKeyCreds) {\n this.#credentials = credentials;\n }\n\n get isBuilderKey(): boolean {\n return true;\n }\n\n get supportGasless(): boolean {\n return true;\n }\n\n async authorize(request: ApiKeyAuthorizationRequest): Promise<HeadersInit> {\n return this.#authorize(request);\n }\n\n async #authorize(request: ApiKeyAuthorizationRequest): Promise<HeadersInit> {\n try {\n const timestamp = Math.floor(Date.now() / 1000);\n\n return {\n POLY_BUILDER_API_KEY: this.#credentials.key,\n POLY_BUILDER_PASSPHRASE: this.#credentials.passphrase,\n POLY_BUILDER_SIGNATURE: await buildHmacSignature(\n this.#credentials.secret,\n timestamp,\n request.method,\n request.path,\n request.body,\n ),\n POLY_BUILDER_TIMESTAMP: `${timestamp}`,\n };\n } catch (error) {\n throw SigningError.fromError(\n error,\n 'Could not sign the builder-authenticated request',\n );\n }\n }\n}\n"]}
@@ -0,0 +1,85 @@
1
+ import { PrivyClient, AuthorizationContext } from '@privy-io/node';
2
+ import { EvmAddress, EvmSignature, HexString } from '@polymarket/types';
3
+ import { T as TypedDataPayload, a as TransactionHandle } from './types-Bg5Leu3D.js';
4
+ import '@polymarket/bindings';
5
+
6
+ type SignerTransactionRequest = {
7
+ chainId: number;
8
+ data?: HexString;
9
+ to: EvmAddress;
10
+ value?: bigint;
11
+ };
12
+ type RequestAddressRequest = {
13
+ kind: 'requestAddress';
14
+ };
15
+ type SignAuthMessageRequest = {
16
+ kind: 'signAuthMessage';
17
+ payload: TypedDataPayload;
18
+ };
19
+ type SendErc20ApprovalTransactionRequest = {
20
+ kind: 'sendErc20ApprovalTransaction';
21
+ request: SignerTransactionRequest;
22
+ };
23
+ type SendErc1155ApprovalForAllTransactionRequest = {
24
+ kind: 'sendErc1155ApprovalForAllTransaction';
25
+ request: SignerTransactionRequest;
26
+ };
27
+ type SendErc20TransferTransactionRequest = {
28
+ kind: 'sendErc20TransferTransaction';
29
+ request: SignerTransactionRequest;
30
+ };
31
+ type SignGaslessTypedDataRequest = {
32
+ kind: 'signGaslessTypedData';
33
+ payload: TypedDataPayload;
34
+ };
35
+ type SignGaslessMessageRequest = {
36
+ kind: 'signGaslessMessage';
37
+ payload: TypedDataPayload;
38
+ };
39
+ type SendSplitPositionTransactionRequest = {
40
+ kind: 'sendSplitPositionTransaction';
41
+ request: SignerTransactionRequest;
42
+ };
43
+ type SendMergePositionsTransactionRequest = {
44
+ kind: 'sendMergePositionsTransaction';
45
+ request: SignerTransactionRequest;
46
+ };
47
+ type SendRedeemPositionsTransactionRequest = {
48
+ kind: 'sendRedeemPositionsTransaction';
49
+ request: SignerTransactionRequest;
50
+ };
51
+ type SignOrderRequest = {
52
+ kind: 'signOrder';
53
+ payload: TypedDataPayload;
54
+ };
55
+ type AuthenticationWorkflowRequest = RequestAddressRequest | SignAuthMessageRequest;
56
+ type AuthenticationWorkflow<TReturn> = AsyncGenerator<AuthenticationWorkflowRequest, TReturn, EvmAddress | EvmSignature>;
57
+ type AuthenticateWith = <TReturn>(workflow: AuthenticationWorkflow<TReturn>) => Promise<TReturn>;
58
+ type CompleteWorkflowRequest = RequestAddressRequest | SendErc20ApprovalTransactionRequest | SendErc1155ApprovalForAllTransactionRequest | SendErc20TransferTransactionRequest | SignGaslessTypedDataRequest | SignGaslessMessageRequest | SendSplitPositionTransactionRequest | SendMergePositionsTransactionRequest | SendRedeemPositionsTransactionRequest | SignOrderRequest;
59
+ type CompleteWorkflowNext = EvmAddress | EvmSignature | TransactionHandle;
60
+ type CompleteWith = <TRequest extends CompleteWorkflowRequest, TReturn>(workflow: AsyncGenerator<TRequest, TReturn, CompleteWorkflowNext>) => Promise<TReturn>;
61
+
62
+ type PrivyWalletConfig = {
63
+ privy: PrivyClient;
64
+ walletId: string;
65
+ authorizationContext?: AuthorizationContext;
66
+ };
67
+ /**
68
+ * Drives an authentication workflow with a Privy Node SDK wallet.
69
+ *
70
+ * @throws {@link AuthenticateWithError}
71
+ * Thrown when the required wallet signature cannot be produced.
72
+ */
73
+ declare function authenticateWith(config: PrivyWalletConfig): AuthenticateWith;
74
+ /**
75
+ * Drives a workflow with a Privy Node SDK wallet.
76
+ *
77
+ * Supports the current non-auth workflow set, including order signing,
78
+ * approvals, transfers, redemptions, and gasless wallet preparation.
79
+ *
80
+ * @throws {@link CompleteWithError}
81
+ * Thrown when the required wallet signature or submission cannot be produced.
82
+ */
83
+ declare function completeWith(config: PrivyWalletConfig): CompleteWith;
84
+
85
+ export { type PrivyWalletConfig, authenticateWith, completeWith };
package/dist/privy.js ADDED
@@ -0,0 +1,2 @@
1
+ import {e,d as d$1,c as c$1,b,a}from'./chunk-DBVGNMB5.js';import v from'process';import {invariant,expectEvmAddress,expectTxHash,expectEvmSignature,never}from'@polymarket/types';import {TypedData}from'ox';import {createPublicClient,http,WaitForTransactionReceiptTimeoutError}from'viem';import {waitForTransactionReceipt}from'viem/actions';import*as W from'viem/chains';invariant(v.release.name==="node","The @polymarket/client/privy entrypoint requires a Node.js runtime.");invariant(typeof window>"u"&&typeof document>"u","The @polymarket/client/privy entrypoint cannot be imported in a browser-like runtime.");var I=Object.values(W);function M(t){return async function(e){let n=await e.next();for(;!n.done;)try{switch(n.value.kind){case "requestAddress":n=await e.next(await T(t));break;case "signAuthMessage":n=await e.next(await f(t,n.value.payload));break}}catch(r){n=await e.throw(r);}return n.value}}function $(t){return async function(e){let n=await e.next();for(;!n.done;)try{switch(n.value.kind){case "sendErc20ApprovalTransaction":case "sendErc1155ApprovalForAllTransaction":case "sendErc20TransferTransaction":case "sendMergePositionsTransaction":case "sendRedeemPositionsTransaction":case "sendSplitPositionTransaction":{let r=await k(t,n.value.request);n=await e.next(new c(r,n.value.request.chainId));break}case "requestAddress":n=await e.next(await T(t));break;case "signGaslessTypedData":case "signOrder":n=await e.next(await f(t,n.value.payload));break;case "signGaslessMessage":n=await e.next(await z(t,n.value.payload));break}}catch(r){n=await e.throw(r);}return n.value}}async function T(t){try{let a=await t.privy.wallets().get(t.walletId);return expectEvmAddress(a.address)}catch(a){throw e.fromError(a,"Could not resolve signer address")}}async function k(t,a){try{let e=await t.privy.wallets().ethereum().sendTransaction(t.walletId,{authorization_context:t.authorizationContext,caip2:`eip155:${a.chainId}`,params:{transaction:{chain_id:a.chainId,data:a.data,to:a.to,value:a.value?.toString()}}});return expectTxHash(e.hash)}catch(e){d(e);}}async function f(t,a){try{let e=await t.privy.wallets().ethereum().signTypedData(t.walletId,{authorization_context:t.authorizationContext,params:{typed_data:{domain:i(a.domain),message:i(a.message),primary_type:a.primaryType,types:a.types}}});return expectEvmSignature(e.signature)}catch(e){d(e);}}async function z(t,a){try{let e=await t.privy.wallets().ethereum().signMessage(t.walletId,{authorization_context:t.authorizationContext,message:TypedData.getSignPayload(a)});return expectEvmSignature(e.signature)}catch(e){d(e);}}function i(t){return typeof t=="bigint"?`${t}`:Array.isArray(t)?t.map(a=>i(a)):typeof t=="object"&&t!==null?Object.fromEntries(Object.entries(t).flatMap(([a,e])=>e===void 0?[]:[[a,i(e)]])):t}function d(t){throw o(t)?new d$1("User rejected the signing request",{cause:t}):e.fromError(t)}function o(t,a=new Set){if(a.has(t)||t===null||typeof t!="object")return false;a.add(t);let e=t;return e.code===4001||e.code==="ACTION_REJECTED"||e.name==="APIUserAbortError"||o(e.error,a)||o(e.cause,a)}var c=class{transactionId=null;#e;#t;constructor(a,e){this.#e=e,this.#t=a;}get transactionHash(){return this.#t}async wait(){try{let a=await waitForTransactionReceipt(createPublicClient({chain:H(this.#e),transport:http()}),{hash:this.#t}),e=expectTxHash(a.transactionHash);if(this.#t=e,a.status==="reverted")throw new c$1(`Transaction ${e} reverted`);return {transactionHash:e,transactionId:null}}catch(a$1){throw a$1 instanceof WaitForTransactionReceiptTimeoutError?new b(`Timed out waiting for transaction ${this.#t} to settle`,{cause:a$1}):a.fromError(a$1)}}};function H(t){let a=I.find(e=>e.id===t);if(a!==void 0)return a;never(`Unsupported chain ID for direct Privy transaction wait: ${t}`);}export{M as authenticateWith,$ as completeWith};//# sourceMappingURL=privy.js.map
2
+ //# sourceMappingURL=privy.js.map