@gala-chain/gswap-sdk 1.2.0 → 2.0.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -8
- package/dist/browser/classes/apply_results.js +1 -1
- package/dist/browser/classes/apply_results.js.map +1 -1
- package/dist/browser/classes/assets.js +1 -1
- package/dist/browser/classes/assets.js.map +1 -1
- package/dist/browser/classes/dex_fees.js +1 -1
- package/dist/browser/classes/dex_fees.js.map +1 -1
- package/dist/browser/classes/gateway.js +1 -1
- package/dist/browser/classes/gateway.js.map +1 -1
- package/dist/browser/classes/gdex_stream.js +1 -1
- package/dist/browser/classes/gdex_stream.js.map +1 -1
- package/dist/browser/classes/gswap.js +1 -1
- package/dist/browser/classes/gswap.js.map +1 -1
- package/dist/browser/classes/gswap_error_catalog.js +2 -0
- package/dist/browser/classes/gswap_error_catalog.js.map +1 -0
- package/dist/browser/classes/gswap_error_phase_table.js +2 -0
- package/dist/browser/classes/gswap_error_phase_table.js.map +1 -0
- package/dist/browser/classes/gswap_sdk_error.js +1 -1
- package/dist/browser/classes/gswap_sdk_error.js.map +1 -1
- package/dist/browser/classes/http_client.js +1 -1
- package/dist/browser/classes/http_client.js.map +1 -1
- package/dist/browser/classes/leaderboard.js +2 -0
- package/dist/browser/classes/leaderboard.js.map +1 -0
- package/dist/browser/classes/market.js +2 -0
- package/dist/browser/classes/market.js.map +1 -0
- package/dist/browser/classes/pending_swap_fate.js.map +1 -1
- package/dist/browser/classes/pending_swaps.js +1 -1
- package/dist/browser/classes/pending_swaps.js.map +1 -1
- package/dist/browser/classes/pools.js +1 -1
- package/dist/browser/classes/pools.js.map +1 -1
- package/dist/browser/classes/positions.js +1 -1
- package/dist/browser/classes/positions.js.map +1 -1
- package/dist/browser/classes/quoting.js +1 -1
- package/dist/browser/classes/quoting.js.map +1 -1
- package/dist/browser/classes/shadow_submit.js.map +1 -1
- package/dist/browser/classes/storage_adapters.js.map +1 -1
- package/dist/browser/classes/submitted_transaction.js +1 -1
- package/dist/browser/classes/submitted_transaction.js.map +1 -1
- package/dist/browser/classes/swaps.js +1 -1
- package/dist/browser/classes/swaps.js.map +1 -1
- package/dist/browser/classes/symbols.js +1 -1
- package/dist/browser/classes/symbols.js.map +1 -1
- package/dist/browser/index.js +1 -1
- package/dist/browser/types/env.js.map +1 -1
- package/dist/browser/types/fees.js.map +1 -1
- package/dist/browser/types/market.js +2 -0
- package/dist/browser/types/market.js.map +1 -0
- package/dist/browser/utils/classification.js.map +1 -1
- package/dist/browser/utils/confirmation_schedule.js.map +1 -1
- package/dist/browser/utils/confirmation_state.js +1 -1
- package/dist/browser/utils/confirmation_state.js.map +1 -1
- package/dist/browser/utils/debug.js.map +1 -1
- package/dist/browser/utils/dto_builders.js +1 -1
- package/dist/browser/utils/dto_builders.js.map +1 -1
- package/dist/browser/utils/failure_classification.js +1 -1
- package/dist/browser/utils/failure_classification.js.map +1 -1
- package/dist/browser/utils/failure_guards.js +1 -1
- package/dist/browser/utils/failure_guards.js.map +1 -1
- package/dist/browser/utils/lenient.js +1 -1
- package/dist/browser/utils/lenient.js.map +1 -1
- package/dist/browser/utils/ordering.js +1 -1
- package/dist/browser/utils/ordering.js.map +1 -1
- package/dist/browser/utils/reconnection.js +1 -1
- package/dist/browser/utils/reconnection.js.map +1 -1
- package/dist/browser/utils/resolve_pre_send.js +2 -0
- package/dist/browser/utils/resolve_pre_send.js.map +1 -0
- package/dist/browser/utils/server_message.js.map +1 -1
- package/dist/browser/utils/shadow_errors.js +1 -1
- package/dist/browser/utils/shadow_errors.js.map +1 -1
- package/dist/browser/utils/submit_state.js.map +1 -1
- package/dist/browser/utils/tick_align.js.map +1 -1
- package/dist/browser/utils/tick_math.js.map +1 -1
- package/dist/browser/utils/tick_range.js.map +1 -1
- package/dist/browser/utils/ticks.js +1 -1
- package/dist/browser/utils/ticks.js.map +1 -1
- package/dist/browser/utils/validation.js +1 -1
- package/dist/browser/utils/validation.js.map +1 -1
- package/dist/index.cjs +1033 -2925
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +439 -1604
- package/dist/index.d.ts +439 -1604
- package/dist/index.mjs +964 -2810
- package/dist/index.mjs.map +1 -1
- package/package.json +36 -60
- package/dist/browser/classes/error_catalog.js +0 -2
- package/dist/browser/classes/error_catalog.js.map +0 -1
- package/dist/browser/classes/error_phase_table.js +0 -2
- package/dist/browser/classes/error_phase_table.js.map +0 -1
- package/dist/browser/classes/error_phases.js +0 -2
- package/dist/browser/classes/error_phases.js.map +0 -1
- package/dist/browser/classes/signers.js +0 -2
- package/dist/browser/classes/signers.js.map +0 -1
- package/dist/browser/utils/axios_requestor.js +0 -2
- package/dist/browser/utils/axios_requestor.js.map +0 -1
- package/dist/browser/utils/chain_dto_signing.js +0 -3
- package/dist/browser/utils/chain_dto_signing.js.map +0 -1
- package/dist/browser/utils/class_key.js +0 -2
- package/dist/browser/utils/class_key.js.map +0 -1
- package/dist/browser/utils/eip712.js +0 -4
- package/dist/browser/utils/eip712.js.map +0 -1
- package/dist/browser/utils/error_brand.js +0 -2
- package/dist/browser/utils/error_brand.js.map +0 -1
- package/dist/browser/utils/ethers_provider.js +0 -2
- package/dist/browser/utils/ethers_provider.js.map +0 -1
- package/dist/browser/utils/failure_outcomes.js +0 -2
- package/dist/browser/utils/failure_outcomes.js.map +0 -1
- package/dist/browser/utils/failure_view.js +0 -2
- package/dist/browser/utils/failure_view.js.map +0 -1
- package/dist/browser/utils/fetch_failure.js +0 -2
- package/dist/browser/utils/fetch_failure.js.map +0 -1
- package/dist/browser/utils/pre_send.js +0 -2
- package/dist/browser/utils/pre_send.js.map +0 -1
- package/dist/browser/utils/signing.js +0 -3
- package/dist/browser/utils/signing.js.map +0 -1
- package/dist/browser/utils/transport.js +0 -2
- package/dist/browser/utils/transport.js.map +0 -1
- package/dist/browser/utils/typed_data.js +0 -2
- package/dist/browser/utils/typed_data.js.map +0 -1
- package/dist/browser/utils/unique_key.js +0 -2
- package/dist/browser/utils/unique_key.js.map +0 -1
- package/dist/browser/utils/unique_key_syntax.js +0 -2
- package/dist/browser/utils/unique_key_syntax.js.map +0 -1
- package/dist/browser/utils/wallet_rejection.js +0 -2
- package/dist/browser/utils/wallet_rejection.js.map +0 -1
- package/dist/browser/version.js +0 -2
- package/dist/browser/version.js.map +0 -1
- package/dist/browser/wallet.js +0 -2
- package/dist/browser/wallet.js.map +0 -1
- package/dist/wallet.cjs +0 -159
- package/dist/wallet.cjs.map +0 -1
- package/dist/wallet.d.cts +0 -74
- package/dist/wallet.d.ts +0 -74
- package/dist/wallet.mjs +0 -156
- package/dist/wallet.mjs.map +0 -1
- /package/dist/browser/_virtual/{_@oxc-project_runtime@0.151.0 → _@oxc-project_runtime@0.153.0}/helpers/esm/defineProperty.js +0 -0
- /package/dist/browser/_virtual/{_@oxc-project_runtime@0.151.0 → _@oxc-project_runtime@0.153.0}/helpers/esm/toPrimitive.js +0 -0
- /package/dist/browser/_virtual/{_@oxc-project_runtime@0.151.0 → _@oxc-project_runtime@0.153.0}/helpers/esm/toPropertyKey.js +0 -0
- /package/dist/browser/_virtual/{_@oxc-project_runtime@0.151.0 → _@oxc-project_runtime@0.153.0}/helpers/esm/typeof.js +0 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gala-chain/gswap-sdk",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0-rc.0",
|
|
4
4
|
"description": "A source development kit for interacting with GSwap.",
|
|
5
5
|
"main": "dist/index.cjs",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -20,57 +20,12 @@
|
|
|
20
20
|
"types": "./dist/index.d.cts",
|
|
21
21
|
"default": "./dist/index.cjs"
|
|
22
22
|
}
|
|
23
|
-
},
|
|
24
|
-
"./wallet": {
|
|
25
|
-
"browser": {
|
|
26
|
-
"types": "./dist/wallet.d.ts",
|
|
27
|
-
"default": "./dist/browser/wallet.js"
|
|
28
|
-
},
|
|
29
|
-
"import": {
|
|
30
|
-
"types": "./dist/wallet.d.ts",
|
|
31
|
-
"default": "./dist/wallet.mjs"
|
|
32
|
-
},
|
|
33
|
-
"require": {
|
|
34
|
-
"types": "./dist/wallet.d.cts",
|
|
35
|
-
"default": "./dist/wallet.cjs"
|
|
36
|
-
}
|
|
37
23
|
}
|
|
38
24
|
},
|
|
39
25
|
"sideEffects": false,
|
|
40
26
|
"files": [
|
|
41
27
|
"dist"
|
|
42
28
|
],
|
|
43
|
-
"scripts": {
|
|
44
|
-
"test": "mocha --spec tests/**/*.test.ts",
|
|
45
|
-
"test:live": "mocha --timeout 300000 --spec 'tests/live/**/*.live.ts'",
|
|
46
|
-
"test:cov": "node scripts/prepare-coverage.mjs && c8 --reporter=text-summary --reporter=json-summary --all --src coverage-build/src --include 'coverage-build/src/**/*.js' --exclude 'coverage-build/src/types/**' mocha --config .mocharc.coverage.json --spec 'coverage-build/tests/**/*.test.js'",
|
|
47
|
-
"test:debug:nospec": "node --import=tsx node_modules/.bin/mocha --exit --timeout 120000",
|
|
48
|
-
"lint": "eslint src tests examples/cli/src --ext .ts,.js --max-warnings=0",
|
|
49
|
-
"lint:fix": "eslint src tests examples/cli/src --ext .ts,.js --fix",
|
|
50
|
-
"format:check": "prettier --check \"src/**/*.ts\" \"tests/**/*.ts\" \"examples/cli/src/**/*.ts\"",
|
|
51
|
-
"prepare": "husky",
|
|
52
|
-
"build": "tsdown",
|
|
53
|
-
"build:node": "tsdown --filter node",
|
|
54
|
-
"build:browser": "tsdown --filter browser",
|
|
55
|
-
"build:dev": "tsdown --watch",
|
|
56
|
-
"build:legacy": "tsc",
|
|
57
|
-
"typecheck": "tsc --noEmit",
|
|
58
|
-
"typecheck:tests": "tsc -p tsconfig.tests.json --noEmit",
|
|
59
|
-
"coverage:goal": "tsx scripts/check-coverage-threshold.ts",
|
|
60
|
-
"check:coverage:goal": "npm run test:cov && npm run coverage:goal",
|
|
61
|
-
"check:clones": "jscpd src tests --min-lines 12 --min-tokens 70 --threshold 0 --reporters console --ignore \"tests/fixtures/*-signing-golden.json\"",
|
|
62
|
-
"check:strict": "npm run typecheck && npm run typecheck:tests && npm run lint && npm run check:clones",
|
|
63
|
-
"check:all": "npm run check:strict && npm run check:coverage:goal && npm run build && npm run check:examples && npm run check:pack",
|
|
64
|
-
"check:examples": "tsx scripts/check-examples.ts",
|
|
65
|
-
"check:pack": "tsx scripts/packed-smoke.ts",
|
|
66
|
-
"clean": "rm -rf dist",
|
|
67
|
-
"docs:error-catalog": "tsx scripts/error-catalog-docs.ts",
|
|
68
|
-
"docs:build": "cd docs && npm run generate-typedoc && npm run build",
|
|
69
|
-
"docs:dev": "cd docs && npm run start",
|
|
70
|
-
"docs:serve": "cd docs && npm run serve",
|
|
71
|
-
"docs:deploy": "cd docs && npm run deploy",
|
|
72
|
-
"builddocs": "npm run docs:build"
|
|
73
|
-
},
|
|
74
29
|
"keywords": [
|
|
75
30
|
"dex",
|
|
76
31
|
"gala",
|
|
@@ -94,25 +49,22 @@
|
|
|
94
49
|
"eslint-config-prettier": "^10.1.5",
|
|
95
50
|
"eslint-plugin-unused-imports": "^4.4.1",
|
|
96
51
|
"ethers": "^6.17.0",
|
|
97
|
-
"husky": "^9.1.7",
|
|
98
52
|
"jscpd": "^5.1.2",
|
|
99
53
|
"json-stringify-deterministic": "^1.0.12",
|
|
100
|
-
"lint-staged": "^17.4.1",
|
|
101
54
|
"mocha": "^12.0.0",
|
|
102
55
|
"prettier": "^3.5.3",
|
|
56
|
+
"rolldown": "1.2.10",
|
|
103
57
|
"tsdown": "^0.23.0",
|
|
104
58
|
"tsx": "^4.23.13",
|
|
105
59
|
"typescript": "npm:@typescript/typescript6@^6.0.2",
|
|
106
60
|
"typescript-eslint": "^8.34.0",
|
|
107
|
-
"ws": "^8.21.0"
|
|
61
|
+
"ws": "^8.21.0",
|
|
62
|
+
"@gala-chain/gala-core-sdk": "^1.0.0-rc.4"
|
|
108
63
|
},
|
|
109
|
-
"
|
|
110
|
-
"
|
|
111
|
-
"*.ts": "prettier --write"
|
|
64
|
+
"peerDependencies": {
|
|
65
|
+
"@gala-chain/gala-core-sdk": ">=1.0.0-rc.4 <2"
|
|
112
66
|
},
|
|
113
67
|
"dependencies": {
|
|
114
|
-
"@noble/curves": "^1.9.7",
|
|
115
|
-
"@noble/hashes": "^1.8.0",
|
|
116
68
|
"bignumber.js": "^11.1.5",
|
|
117
69
|
"debug": "^4.4.1",
|
|
118
70
|
"decimal.js": "^10.6.0"
|
|
@@ -127,10 +79,34 @@
|
|
|
127
79
|
"onFail": "error"
|
|
128
80
|
}
|
|
129
81
|
},
|
|
130
|
-
"
|
|
131
|
-
"
|
|
132
|
-
"
|
|
133
|
-
"
|
|
134
|
-
"
|
|
82
|
+
"scripts": {
|
|
83
|
+
"test": "mocha --spec tests/**/*.test.ts",
|
|
84
|
+
"test:live": "mocha --timeout 300000 --spec 'tests/live/**/*.live.ts'",
|
|
85
|
+
"test:cov": "node scripts/prepare-coverage.mjs && c8 --reporter=text-summary --reporter=json-summary --all --src coverage-build/src --include 'coverage-build/src/**/*.js' --exclude 'coverage-build/src/types/**' mocha --config .mocharc.coverage.json --spec 'coverage-build/tests/**/*.test.js'",
|
|
86
|
+
"test:debug:nospec": "node --import=tsx node_modules/.bin/mocha --exit --timeout 120000",
|
|
87
|
+
"lint": "eslint src tests examples/cli/src --ext .ts,.js --max-warnings=0",
|
|
88
|
+
"lint:fix": "eslint src tests examples/cli/src --ext .ts,.js --fix",
|
|
89
|
+
"format:check": "prettier --check \"src/**/*.ts\" \"tests/**/*.ts\" \"examples/cli/src/**/*.ts\"",
|
|
90
|
+
"build": "tsdown",
|
|
91
|
+
"build:node": "tsdown --filter node",
|
|
92
|
+
"build:browser": "tsdown --filter browser",
|
|
93
|
+
"build:dev": "tsdown --watch",
|
|
94
|
+
"build:legacy": "tsc",
|
|
95
|
+
"typecheck": "tsc --noEmit",
|
|
96
|
+
"typecheck:tests": "tsc -p tsconfig.tests.json --noEmit",
|
|
97
|
+
"coverage:goal": "tsx scripts/check-coverage-threshold.ts",
|
|
98
|
+
"check:coverage:goal": "pnpm run test:cov && pnpm run coverage:goal",
|
|
99
|
+
"check:clones": "jscpd src tests --min-lines 12 --min-tokens 70 --threshold 0 --reporters console --ignore \"tests/fixtures/*-signing-golden.json,tests/fixtures/*-recorded.json\"",
|
|
100
|
+
"check:strict": "pnpm run typecheck && pnpm run typecheck:tests && pnpm run lint && pnpm run check:clones",
|
|
101
|
+
"check:all": "pnpm run check:strict && pnpm run check:coverage:goal && pnpm run build && pnpm run check:examples && pnpm run check:pack",
|
|
102
|
+
"check:examples": "tsx scripts/check-examples.ts",
|
|
103
|
+
"check:pack": "tsx scripts/packed-smoke.ts",
|
|
104
|
+
"clean": "rm -rf dist",
|
|
105
|
+
"docs:error-catalog": "tsx scripts/error-catalog-docs.ts",
|
|
106
|
+
"docs:build": "cd docs && npm run generate-typedoc && npm run build",
|
|
107
|
+
"docs:dev": "cd docs && npm run start",
|
|
108
|
+
"docs:serve": "cd docs && npm run serve",
|
|
109
|
+
"docs:deploy": "cd docs && npm run deploy",
|
|
110
|
+
"builddocs": "pnpm run docs:build"
|
|
135
111
|
}
|
|
136
|
-
}
|
|
112
|
+
}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=[`wrong_length`,`bad_encoding`,`not_on_curve`,`no_key_provided`],t=[`timeout`,`transport`],n=[`user_rejected`,`failed`],r=`0,500,3000,10000`,i={HTTP_ERROR:{phase:`post_send`,template:`Unexpected HTTP error {status} from {url}.`,params:{status:`number`,url:`string`,serverMessage:`string`},unrendered:[`serverMessage`]},UPDATE_REQUIRED:{phase:`post_send`,template:`The backend refused this app version and requires an update (HTTP {status}); nothing was queued.`,params:{status:`number`}},REQUEST_TIMEOUT:{phase:`in_flight`,template:`Request to {url} timed out after {timeoutMs} ms.`,params:{url:`string`,timeoutMs:`number`}},TRANSPORT_ERROR:{phase:`in_flight`,template:`The request to {url} failed before the server answered.`,params:{url:`string`}},REQUEST_FAILED:{phase:`in_flight`,template:`The {operation} request failed.`,params:{operation:`string`}},INVALID_TIMEOUT:{phase:`pre_send`,template:`{field} must be a positive number of milliseconds, or Infinity for no timeout (got {value}).`,params:{field:`string`,value:`number`}},METHOD_NOT_SUPPORTED:{phase:`pre_send`,template:`The method {method} is not supported; swaps are queued through RequestTrade.`,params:{method:`string`}},SUBMISSION_OUTCOME_UNKNOWN:{phase:`in_flight`,template:`The submission outcome is unknown ({reason}): the request may have reached the gateway. Confirm before retrying.`,params:{reason:t}},GATEWAY_REPORTED_ERROR:{phase:`post_send`,template:`The gateway reported an error for this write: {serverMessage}`,params:{serverMessage:`string`}},GATEWAY_DATA_MISSING:{phase:`post_send`,template:`The gateway response is missing its data object.`,params:{}},GATEWAY_MODE_INVALID:{phase:`post_send`,template:`Gateway response must contain data.mode="sync" with data.result, or data.mode="queued".`,params:{}},GATEWAY_SYNC_REQUEST_TRADE:{phase:`post_send`,template:`The gateway executed RequestTrade synchronously, which this SDK refuses; RequestTrade must be queued.`,params:{}},MISSING_UNIQUE_KEY:{phase:`post_send`,template:`The gateway acknowledged RequestTrade without echoing its uniqueKey, so it cannot be tied to the signed request.`,params:{}},UNIQUE_KEY_MISMATCH:{phase:`post_send`,template:`Gateway response data.uniqueKey must match the signed RequestTrade uniqueKey.`,params:{}},SHADOW_NOT_QUEUED:{phase:`post_send`,template:`The swap backend did not queue the shadow request.`,params:{}},SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS:{phase:`pre_send`,template:`A shadow submission needs a walletAddress (the X-Wallet-Address header): pass one to the GSwap constructor or to this call.`,params:{}},METHOD_NOT_ALLOWED:{phase:`post_send`,template:`The gateway does not expose this contract method: {serverMessage}`,params:{serverMessage:`string`}},SIGNATURE_INVALID:{phase:`post_send`,template:`The gateway could not verify the signature: {serverMessage}`,params:{serverMessage:`string`}},SIGNER_MISMATCH:{phase:`post_send`,template:`The recovered signer does not match an actor named by the operation: {serverMessage}`,params:{serverMessage:`string`}},DTO_INVALID:{phase:`post_send`,template:`The gateway rejected the DTO shape: {serverMessage}`,params:{serverMessage:`string`}},BOUNDS_VIOLATION:{phase:`post_send`,template:`The gateway rejected a numeric, tick, symbol or range bound: {serverMessage}`,params:{serverMessage:`string`}},SYMBOL_CONFLICT:{phase:`post_send`,template:`The CreatePool symbol is already owned by another class: {serverMessage}`,params:{serverMessage:`string`}},RATE_LIMITED:{phase:`post_send`,template:`The gateway rate-limited this signer: {serverMessage}`,params:{serverMessage:`string`}},CHAIN_DISPATCH_FAILED:{phase:`post_send`,template:`The chain dispatch failed (chain error key "{errorKey}"): {serverMessage}`,params:{errorKey:`string`,serverMessage:`string`}},GATEWAY_REJECTED:{phase:`post_send`,template:`Gateway rejected {gatewayCode}: {serverMessage}`,params:{gatewayCode:`string`,serverMessage:`string`}},CHAIN_REJECTED:{phase:`post_send`,template:`GalaChain error {errorKey}: {serverMessage}`,params:{errorKey:`string`,serverMessage:`string`}},INVALID_CHAIN_RESPONSE:{phase:`post_send`,template:`Backend returned an invalid {resource}.`,params:{resource:`string`}},INVALID_POSITION_RESPONSE:{phase:`post_send`,template:`Backend returned an invalid position ({reason}).`,params:{reason:`string`}},CONFIRMATION_TIMEOUT:{phase:`post_send`,template:`Transaction confirmation timed out; the trade may still apply. Confirm the same uniqueKey again later instead of resubmitting.`,params:{}},CONFIRMATION_ABORTED:{phase:`post_send`,template:`Transaction confirmation was aborted.`,params:{}},CONFIRMATION_FAILED:{phase:`post_send`,template:`Transaction confirmation failed with HTTP {status}.`,params:{status:`number`,serverMessage:`string`},unrendered:[`serverMessage`]},CONFIRMATION_MALFORMED:{phase:`post_send`,template:`Transaction confirmation returned a malformed body.`,params:{}},CONFIRMATION_KEY_MISMATCH:{phase:`post_send`,template:`Apply result key did not match the requested key.`,params:{}},NO_SIGNER:{phase:`pre_send`,template:`This method requires a signer. Please provide a signer to the GSwap constructor.`,params:{}},NO_WALLET_ADDRESS:{phase:`post_send`,template:`Cannot confirm this write: no walletAddress was provided to the GSwap constructor, so the resulting position cannot be looked up to confirm it landed on chain.`,params:{}},NO_POOL_AVAILABLE:{phase:`post_send`,template:`No pool is available for {tokenIn}/{tokenOut} (fee tier {fee}).`,params:{tokenIn:`string`,tokenOut:`string`,fee:`string`}},INSUFFICIENT_LIQUIDITY:{phase:`post_send`,template:`The selected pool has insufficient liquidity for {tokenIn}/{tokenOut} (fee tier {fee}).`,params:{tokenIn:`string`,tokenOut:`string`,fee:`string`}},UNKNOWN_TOKEN:{phase:`pre_send`,template:`Token {token} is not registered on the DEX contract: it has no trading symbol.`,params:{token:`string`}},SYMBOL_NOT_FOUND:{phase:`pre_send`,template:`Token {token} could not be resolved to a trading symbol.`,params:{token:`string`}},STREAM_API_KEY_UNUSABLE:{phase:`pre_send`,template:`GdexStreamConfig.apiKey needs a non-empty key and an explicit webSocketImpl that accepts upgrade headers as its third argument (the "ws" package, or React Native). A browser WebSocket cannot send x-api-key, so the key would be silently dropped.`,params:{}},STREAM_WEBSOCKET_UNAVAILABLE:{phase:`pre_send`,template:`GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the "ws" package).`,params:{}},STREAM_NOT_CONNECTED:{phase:`pre_send`,template:`GDEX stream is not connected. Call connect() first.`,params:{}},STREAM_DISCONNECTED:{phase:`in_flight`,template:`GDEX stream disconnected.`,params:{}},STREAM_REQUEST_TIMEOUT:{phase:`in_flight`,template:`GDEX request "{method}" timed out after {timeoutMs} ms.`,params:{method:`string`,timeoutMs:`number`}},STREAM_CONNECT_FAILED:{phase:`in_flight`,template:`Failed to connect to GDEX stream at {url}.`,params:{url:`string`}},STREAM_CLOSED_BEFORE_CONNECT:{phase:`in_flight`,template:`GDEX stream closed before connecting (code {closeCode}).`,params:{closeCode:`number`}},STREAM_CONNECTION_CLOSED:{phase:`in_flight`,template:`GDEX stream connection closed (code {closeCode}).`,params:{closeCode:`number`}},GALA_WALLET_NOT_AVAILABLE:{phase:`pre_send`,template:`Gala wallet is not available. Please ensure the Gala wallet is connected.`,params:{}},WALLET_UNAVAILABLE:{phase:`pre_send`,template:`No wallet is connected.`,params:{}},MALFORMED_WALLET_REQUEST:{phase:`pre_send`,template:`Wallet {method} request is malformed.`,params:{method:`string`}},UNSUPPORTED_WALLET_METHOD:{phase:`pre_send`,template:`Unsupported wallet method {method}.`,params:{method:`string`}},INVALID_SIGNATURE:{phase:`pre_send`,template:`Wallet returned an invalid {scheme} signature.`,params:{scheme:`string`}},INVALID_CHAIN_ID:{phase:`pre_send`,template:`Wallet returned an invalid chain id ({chainId}).`,params:{chainId:`string`}},SIGNER_ADDRESS_MISMATCH:{phase:`pre_send`,template:`The signing key does not belong to the expected account.`,params:{}},INVALID_PRIVATE_KEY:{phase:`pre_send`,template:`Invalid private key: {reason}.`,params:{reason:e}},SIGNING_FAILED:{phase:`pre_send`,template:`Signing the {method} request failed ({reason}); nothing was sent.`,params:{method:`string`,reason:n}},KEY_PROVIDER_FAILED:{phase:`pre_send`,template:`The signing key could not be fetched; nothing was sent.`,params:{}},TOKEN_RESOLUTION_FAILED:{phase:`pre_send`,template:`Token {token} could not be looked up; nothing was sent.`,params:{token:`string`}},INVALID_SIGNING_HASH_LENGTH:{phase:`pre_send`,template:`secp256k1 can only sign a 32-byte hash (got {length}).`,params:{length:`number`}},MISSING_WALLET_ADDRESS:{phase:`pre_send`,template:`Invalid wallet address: No wallet address provided. Either provide a wallet address to the function you are calling, or set one when instantiating GSwapSDK.`,params:{}},INVALID_WALLET_ADDRESS:{phase:`pre_send`,template:`Invalid {field}: "{value}" is not an accepted wallet address form.`,params:{field:`string`,value:`string`}},INVALID_DECIMAL:{phase:`pre_send`,template:`Invalid decimal quantity: {value}`,params:{value:`string`}},PERSONAL_SIGN_NOT_JSON:{phase:`pre_send`,template:`Personal-sign DTO is not valid JSON`,params:{}},PERSONAL_SIGN_NOT_OBJECT:{phase:`pre_send`,template:`Personal-sign DTO must be a JSON object`,params:{}},PERSONAL_SIGN_BAD_PREFIX:{phase:`pre_send`,template:`Personal-sign DTO prefix is not an EIP-191 "Ethereum Signed Message" header`,params:{}},PERSONAL_SIGN_ENVELOPE_FIELDS:{phase:`pre_send`,template:`Personal-sign DTO carries signing-envelope field(s): {fields}`,params:{fields:`string`}},PERSONAL_SIGN_NOT_CANONICAL:{phase:`pre_send`,template:`Personal-sign DTO is not in canonical serialized form`,params:{}},EIP712_NAME_COLLISION:{phase:`pre_send`,template:`Name collisions are not supported when deriving EIP-712 types ({name}).`,params:{name:`string`}},EIP712_UNSUPPORTED_VALUE:{phase:`pre_send`,template:`Unsupported EIP-712 value of type {valueType}.`,params:{valueType:`string`}},TYPED_DATA_NOT_STRING:{phase:`pre_send`,template:`Invalid typed data: {what} must be a string`,params:{what:`string`}},TYPED_DATA_UNPAIRED_SURROGATE:{phase:`pre_send`,template:`Invalid typed data: {what} has an unpaired surrogate`,params:{what:`string`}},TYPED_DATA_NOT_HEX_BYTES:{phase:`pre_send`,template:`Invalid typed data: {what} must be an even-length 0x hex string`,params:{what:`string`}},TYPED_DATA_NOT_SAFE_INTEGER:{phase:`pre_send`,template:`Invalid typed data: {what} must be a safe integer`,params:{what:`string`}},TYPED_DATA_NOT_INTEGER:{phase:`pre_send`,template:`Invalid typed data: {what} must be an integer`,params:{what:`string`}},TYPED_DATA_NOT_BOOLEAN:{phase:`pre_send`,template:`Invalid typed data: bool must be a boolean`,params:{}},TYPED_DATA_BAD_ADDRESS:{phase:`pre_send`,template:`Invalid typed data: address must be 0x followed by 40 hex digits`,params:{}},TYPED_DATA_BAD_CHECKSUM:{phase:`pre_send`,template:`Invalid typed data: address has a bad checksum`,params:{}},TYPED_DATA_BYTES_LENGTH:{phase:`pre_send`,template:`Invalid typed data: {type} must be exactly {width} bytes`,params:{type:`string`,width:`number`}},TYPED_DATA_OUT_OF_BOUNDS:{phase:`pre_send`,template:`Invalid typed data: value out of bounds for {type}`,params:{type:`string`}},TYPED_DATA_UNSUPPORTED_TYPE:{phase:`pre_send`,template:`Invalid typed data: unsupported type "{type}"`,params:{type:`string`}},TYPED_DATA_FIELDS_NOT_LIST:{phase:`pre_send`,template:`Invalid typed data: type {typeName} must be a list of fields`,params:{typeName:`string`}},TYPED_DATA_FIELD_MALFORMED:{phase:`pre_send`,template:`Invalid typed data: type {typeName} has a field without a string name and type`,params:{typeName:`string`}},TYPED_DATA_INVALID_FIELD_NAME:{phase:`pre_send`,template:`Invalid typed data: invalid field name "{name}"`,params:{name:`string`}},TYPED_DATA_DUPLICATE_FIELD:{phase:`pre_send`,template:`Invalid typed data: duplicate field "{name}" in {typeName}`,params:{name:`string`,typeName:`string`}},TYPED_DATA_INVALID_TYPE_NAME:{phase:`pre_send`,template:`Invalid typed data: invalid type name "{name}"`,params:{name:`string`}},TYPED_DATA_CIRCULAR_TYPE:{phase:`pre_send`,template:`Invalid typed data: circular type reference in {typeName}`,params:{typeName:`string`}},TYPED_DATA_UNKNOWN_FIELD_TYPE:{phase:`pre_send`,template:`Invalid typed data: unknown type "{type}" in {typeName}`,params:{type:`string`,typeName:`string`}},TYPED_DATA_NO_PRIMARY_TYPE:{phase:`pre_send`,template:`Invalid typed data: missing primary type`,params:{}},TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE:{phase:`pre_send`,template:`Invalid typed data: ambiguous primary types or unused types ({roots})`,params:{roots:`string`}},TYPED_DATA_ARRAY_EXPECTED:{phase:`pre_send`,template:`Invalid typed data: {type} array value must be an array`,params:{type:`string`}},TYPED_DATA_ARRAY_LENGTH_MISMATCH:{phase:`pre_send`,template:`Invalid typed data: array length mismatch`,params:{}},TYPED_DATA_STRUCT_NOT_OBJECT:{phase:`pre_send`,template:`Invalid typed data: {typeName} value must be an object`,params:{typeName:`string`}},TYPED_DATA_MISSING_FIELD:{phase:`pre_send`,template:`Invalid typed data: {typeName} value is missing field "{field}"`,params:{typeName:`string`,field:`string`}},TYPED_DATA_DOMAIN_NOT_OBJECT:{phase:`pre_send`,template:`Invalid typed data: domain must be an object`,params:{}},TYPED_DATA_INVALID_DOMAIN_KEY:{phase:`pre_send`,template:`Invalid typed data: invalid typed-data domain key {key}`,params:{key:`string`}},NON_CANONICAL_PAIR:{phase:`pre_send`,template:`The pair {token0}/{token1} is not in canonical order: token0 must sort before token1.`,params:{token0:`string`,token1:`string`}},UNORDERABLE_SYMBOLS:{phase:`pre_send`,template:`Unable to order trading symbols: expected a pair of symbols, got {received}.`,params:{received:`string`}},INVALID_TOKEN_CLASS_KEY:{phase:`pre_send`,template:`Invalid token class key "{tokenClassKey}": expected a collection followed by category, type and additionalKey`,params:{tokenClassKey:`string`}},INCOMPLETE_TOKEN_CLASS_KEY:{phase:`pre_send`,template:`Token class key "{compositeKey}" is missing {part}.`,params:{compositeKey:`string`,part:`string`}},INVALID_TRADING_SYMBOL:{phase:`pre_send`,template:`Invalid trading symbol "{symbol}": must be 1-32 ASCII letters and digits and not a reserved word (Token, Unit, none).`,params:{symbol:`string`}},NO_VALID_TRADING_SYMBOL:{phase:`pre_send`,template:`No valid trading symbol for token class {classKey}: "{displaySymbol}" is not an acceptable symbol and none is registered`,params:{classKey:`string`,displaySymbol:`string`}},TOKEN_SYMBOL_NOT_REGISTERED:{phase:`pre_send`,template:`Token {token} is not registered in the trading-symbol registry yet; pass token0Symbol/token1Symbol (the token class symbol) to propose one. A symbol cannot be derived from a class key.`,params:{token:`string`}},SYMBOL_DISAGREES_WITH_REGISTRY:{phase:`pre_send`,template:`Supplied symbol {suppliedSymbol} for {token} disagrees with the registered trading symbol {registeredSymbol}.`,params:{token:`string`,suppliedSymbol:`string`,registeredSymbol:`string`}},CREATE_POOL_NEEDS_CLASS_KEY:{phase:`pre_send`,template:`createPool needs each token as a class key; {token} is a bare trading symbol, which does not carry one.`,params:{token:`string`}},INVALID_UNIQUE_KEY:{phase:`pre_send`,template:`The uniqueKey "{uniqueKey}" must be 1-128 characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".`,params:{uniqueKey:`string`}},INVALID_UNIQUE_KEY_PREFIX:{phase:`pre_send`,template:`uniqueKeyPrefix "{uniqueKeyPrefix}" must be at most {maxLength} characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".`,params:{uniqueKeyPrefix:`string`,maxLength:`number`}},AMOUNT_IS_JS_NUMBER:{phase:`pre_send`,template:`Invalid {field}: use a decimal string or BigNumber, not a JavaScript number`,params:{field:`string`}},AMOUNT_NOT_FINITE:{phase:`pre_send`,template:`Invalid {field}: must be a finite number (got {value})`,params:{field:`string`,value:`string`}},AMOUNT_NOT_POSITIVE:{phase:`pre_send`,template:`Invalid {field}: must be positive (got {value})`,params:{field:`string`,value:`string`}},AMOUNT_NEGATIVE:{phase:`pre_send`,template:`Invalid {field}: must not be negative (got {value})`,params:{field:`string`,value:`string`}},PRICE_VALUES_IS_JS_NUMBER:{phase:`pre_send`,template:`Invalid price values: use decimal strings or BigNumber values, not JavaScript numbers`,params:{}},INVALID_PRICE_VALUES:{phase:`pre_send`,template:`Invalid price values: all prices must be finite and positive (spot {spotPrice}, lower {lowerPrice}, upper {upperPrice})`,params:{spotPrice:`string`,lowerPrice:`string`,upperPrice:`string`}},INVALID_PRICE_RANGE:{phase:`pre_send`,template:`Invalid price range: lower price {lowerPrice} must be less than or equal to upper price {upperPrice}`,params:{lowerPrice:`string`,upperPrice:`string`}},INVALID_PRICE_BOUNDS:{phase:`pre_send`,template:`Price bounds must be finite and positive (minPrice {minPrice}, maxPrice {maxPrice}).`,params:{minPrice:`string`,maxPrice:`string`}},PRICE_BOUNDS_ORDER:{phase:`pre_send`,template:`minPrice {minPrice} must be less than or equal to maxPrice {maxPrice}.`,params:{minPrice:`string`,maxPrice:`string`}},INVALID_STARTING_PRICE:{phase:`pre_send`,template:`Starting price must be finite and positive (got {value}).`,params:{value:`string`}},INVALID_SQRT_PRICE:{phase:`pre_send`,template:`Cannot invert a non-positive sqrt price ({sqrtPrice}).`,params:{sqrtPrice:`string`}},INVALID_TOKEN_DECIMALS:{phase:`pre_send`,template:`Invalid {field}: must be a non-negative integer (got {value})`,params:{field:`string`,value:`number`}},TICKS_NOT_INTEGERS:{phase:`pre_send`,template:`Invalid tick values: ticks must be integers (got {tickLower} and {tickUpper})`,params:{tickLower:`number`,tickUpper:`number`}},INVALID_TICK_RANGE:{phase:`pre_send`,template:`Invalid tick range: tickLower {tickLower} must be less than tickUpper {tickUpper}`,params:{tickLower:`number`,tickUpper:`number`}},TICKS_OUT_OF_BOUNDS:{phase:`pre_send`,template:`Invalid tick range: ticks {tickLower} and {tickUpper} must be between {minTick} and {maxTick}`,params:{tickLower:`number`,tickUpper:`number`,minTick:`number`,maxTick:`number`}},TICKS_NOT_ALIGNED:{phase:`pre_send`,template:`Ticks {tickLower} and {tickUpper} must be aligned to spacing {spacing}.`,params:{tickLower:`number`,tickUpper:`number`,spacing:`number`}},INVALID_TICK_SPACING:{phase:`pre_send`,template:`Invalid tick spacing: must be a positive integer (got {value})`,params:{value:`number`}},INVALID_FEE:{phase:`pre_send`,template:`Invalid {field}: {value} is not a supported fee tier; must be one of {allowed}.`,params:{field:`string`,value:`number`,allowed:`string`}},EXACT_AMOUNT_REQUIRED:{phase:`pre_send`,template:`{field} is required for this swap.`,params:{field:`string`}},EXACTLY_ONE_OF_REQUIRED:{phase:`pre_send`,template:`Provide exactly one of {first} or {second}.`,params:{first:`string`,second:`string`}},AT_MOST_ONE_OF_ALLOWED:{phase:`pre_send`,template:`Provide at most one of {first} or {second}.`,params:{first:`string`,second:`string`}},POOL_MISMATCH:{phase:`pre_send`,template:`tokenIn {tokenIn} and tokenOut {tokenOut} must be the two tokens of the pinned pool {poolToken0}/{poolToken1}.`,params:{tokenIn:`string`,tokenOut:`string`,poolToken0:`string`,poolToken1:`string`}},INVALID_DTO:{phase:`pre_send`,template:`{method} DTO field {field} is invalid (expected {expected}).`,params:{method:`string`,field:`string`,expected:`string`}},DTO_NOT_CANONICAL:{phase:`pre_send`,template:`The {method} DTO is not in the form the SDK builders produce; build it with the matching build function and submit that.`,params:{method:`string`}},SEARCH_TOO_LONG:{phase:`pre_send`,template:`search must be at most {maxLength} characters (got {length}).`,params:{length:`number`,maxLength:`number`}},INVALID_SORT_BY:{phase:`pre_send`,template:`sortBy "{value}" is not allowed; it must be one of {allowed}.`,params:{value:`string`,allowed:`string`}},INVALID_SORT_ORDER:{phase:`pre_send`,template:`sortOrder "{value}" is not allowed; it must be asc or desc.`,params:{value:`string`}},INVALID_PAGE:{phase:`pre_send`,template:`page must be an integer of at least 1 (got {value}).`,params:{value:`number`}},INVALID_LIMIT:{phase:`pre_send`,template:`limit must be an integer from {min} to {max} (got {value}).`,params:{value:`number`,min:`number`,max:`number`}}},a=Object.fromEntries(Object.entries(i).map(([e,t])=>[e,t.template])),o=/\{([A-Za-z0-9_]+)\}/gu;function s(e,t){return e.replace(o,(e,n)=>{let r=t[n];return typeof r==`string`||typeof r==`number`||typeof r==`boolean`?String(r):e})}export{r as ALLOWED_FEE_TIERS_TEXT,i as GSWAP_ERROR_CATALOG,e as INVALID_PRIVATE_KEY_REASONS,n as SIGNING_FAILURE_REASONS,t as SUBMISSION_OUTCOME_UNKNOWN_REASONS,a as gswapErrorTemplates,s as renderGSwapErrorTemplate};
|
|
2
|
-
//# sourceMappingURL=error_catalog.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"error_catalog.js","names":[],"sources":["../../../src/classes/error_catalog.ts"],"sourcesContent":["/**\n * The catalog of every error the SDK throws: the SINGLE source of truth for its `code`, the\n * named parameters it carries and the English template its `message` is generated from.\n *\n * - `code` is the only discriminator. It is stable: apps branch on it, never on message text.\n * - `params` are the named placeholders of the error: a flat object of primitives (string,\n * number, boolean) that an app feeds to its own localization (i18next, ICU, FormatJS).\n * Raw server payloads are never params (they are `error.body` / `error.bodyText`), and no\n * secret (private key, signature, raw DTO) ever is.\n * - `template` is English with `{placeholder}` markers. `error.message` is generated from it\n * and the params, so the two cannot drift. It is for logs and developers: it is not stable and\n * must not be shown to users or matched on.\n *\n * Every placeholder in a template is a declared param and every declared param is a placeholder,\n * except the few `unrendered` params that carry server text for the app and are kept out of\n * `message` on purpose (pinned by tests/error_catalog.test.ts). Facts that are not placeholders (HTTP status, URL,\n * `uniqueKey`, transaction ids, the raw body, the cause) are typed properties of the error, see\n * {@link GSwapErrorContext}.\n */\n\nimport type { GSwapErrorPhase } from './error_phases.js';\n\n/**\n * The kinds a param can have: a primitive, or a CLOSED set of string tokens (a readonly tuple).\n * A closed set is a documented union: an app maps each member to its own text and can check that\n * it covered all of them, and a new member is a compile error until it does.\n */\nexport type GSwapErrorParamKind = 'string' | 'number' | 'boolean' | readonly string[];\n\n/** One catalog entry. */\nexport interface GSwapErrorCatalogEntry {\n /** The phase this code is thrown in, unless a throw site says otherwise (see {@link GSwapErrorPhase}). */\n readonly phase: GSwapErrorPhase;\n /** English message template with `{placeholder}` markers. */\n readonly template: string;\n /** Param name to kind. Every param is required and appears in the template, except `unrendered`. */\n readonly params: Readonly<Record<string, GSwapErrorParamKind>>;\n /**\n * Params that are carried for the app but deliberately NOT placeholders of the template. Used\n * for `serverMessage` on the codes whose failing answer may be anything (a proxy's page, a\n * validation list): the server's text is data for the app to relay or ignore, and keeping it out\n * of `message` means it cannot reach a log line or a user interface by accident.\n */\n readonly unrendered?: readonly string[];\n}\n\n/**\n * Why a private key was refused (`INVALID_PRIVATE_KEY.params.reason`). A token for the app to map\n * to its own text, never English and never any part of the key.\n *\n * - `wrong_length`: raw bytes that are not 32 bytes long.\n * - `bad_encoding`: a string that is neither 64 hex characters (optionally `0x`-prefixed, 63 is\n * left-padded) nor a 44-character base64 string.\n * - `not_on_curve`: 32 bytes that are not a valid secp256k1 secret scalar.\n * - `no_key_provided`: a lazy key provider returned something that is not a string.\n */\nexport const INVALID_PRIVATE_KEY_REASONS = [\n 'wrong_length',\n 'bad_encoding',\n 'not_on_curve',\n 'no_key_provided',\n] as const;\n\n/** One member of {@link INVALID_PRIVATE_KEY_REASONS}. */\nexport type InvalidPrivateKeyReason = (typeof INVALID_PRIVATE_KEY_REASONS)[number];\n\n/**\n * Why the outcome of a write submission is unknown (`SUBMISSION_OUTCOME_UNKNOWN.params.reason`).\n * Both say the same thing about the swap (it MAY have been queued: never resubmit under a fresh\n * key, confirm `error.uniqueKey` instead) and differ only in what happened to the request.\n *\n * - `timeout`: the POST exceeded the gateway's timeout; the request may still be running.\n * - `transport`: the POST failed before an HTTP answer was read (offline, connection reset, DNS,\n * CORS, a body that broke off). The bytes may have reached the server and been queued, so this\n * does NOT prove the swap was not sent.\n */\nexport const SUBMISSION_OUTCOME_UNKNOWN_REASONS = ['timeout', 'transport'] as const;\n\n/** One member of {@link SUBMISSION_OUTCOME_UNKNOWN_REASONS}. */\nexport type SubmissionOutcomeUnknownReason = (typeof SUBMISSION_OUTCOME_UNKNOWN_REASONS)[number];\n\n/**\n * Why a signer could not produce a signature (`SIGNING_FAILED.params.reason`). A token for the\n * app to map to its own text.\n *\n * - `user_rejected`: the person declined in their wallet (an EIP-1193 `4001`, an ethers\n * `ACTION_REJECTED`, or a wallet that words it \"User rejected/denied ...\"). Nothing is wrong:\n * they may simply try again.\n * - `failed`: anything else the signer threw (a locked wallet, an unreachable extension, a wallet\n * that refused). The original error is `cause`.\n */\nexport const SIGNING_FAILURE_REASONS = ['user_rejected', 'failed'] as const;\n\n/** One member of {@link SIGNING_FAILURE_REASONS}. */\nexport type SigningFailureReason = (typeof SIGNING_FAILURE_REASONS)[number];\n\n/** The fee tiers as they appear in `INVALID_FEE.allowed`. */\nexport const ALLOWED_FEE_TIERS_TEXT = '0,500,3000,10000';\n\n/** The whole catalog. Add a code here before throwing it anywhere. */\nexport const GSWAP_ERROR_CATALOG = {\n // ---------------------------------------------------------------------------------- transport\n HTTP_ERROR: {\n phase: 'post_send',\n template: 'Unexpected HTTP error {status} from {url}.',\n params: { status: 'number', url: 'string', serverMessage: 'string' },\n unrendered: ['serverMessage'],\n },\n UPDATE_REQUIRED: {\n phase: 'post_send',\n template:\n 'The backend refused this app version and requires an update (HTTP {status}); nothing was queued.',\n params: { status: 'number' },\n },\n REQUEST_TIMEOUT: {\n phase: 'in_flight',\n template: 'Request to {url} timed out after {timeoutMs} ms.',\n params: { url: 'string', timeoutMs: 'number' },\n },\n TRANSPORT_ERROR: {\n phase: 'in_flight',\n template: 'The request to {url} failed before the server answered.',\n params: { url: 'string' },\n },\n REQUEST_FAILED: {\n phase: 'in_flight',\n template: 'The {operation} request failed.',\n params: { operation: 'string' },\n },\n INVALID_TIMEOUT: {\n phase: 'pre_send',\n template:\n '{field} must be a positive number of milliseconds, or Infinity for no timeout (got {value}).',\n params: { field: 'string', value: 'number' },\n },\n\n // ----------------------------------------------------------------------------------- gateway\n METHOD_NOT_SUPPORTED: {\n phase: 'pre_send',\n template: 'The method {method} is not supported; swaps are queued through RequestTrade.',\n params: { method: 'string' },\n },\n SUBMISSION_OUTCOME_UNKNOWN: {\n phase: 'in_flight',\n template:\n 'The submission outcome is unknown ({reason}): the request may have reached the gateway. Confirm before retrying.',\n params: { reason: SUBMISSION_OUTCOME_UNKNOWN_REASONS },\n },\n GATEWAY_REPORTED_ERROR: {\n phase: 'post_send',\n template: 'The gateway reported an error for this write: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n GATEWAY_DATA_MISSING: {\n phase: 'post_send',\n template: 'The gateway response is missing its data object.',\n params: {},\n },\n GATEWAY_MODE_INVALID: {\n phase: 'post_send',\n template:\n 'Gateway response must contain data.mode=\"sync\" with data.result, or data.mode=\"queued\".',\n params: {},\n },\n GATEWAY_SYNC_REQUEST_TRADE: {\n phase: 'post_send',\n template:\n 'The gateway executed RequestTrade synchronously, which this SDK refuses; RequestTrade must be queued.',\n params: {},\n },\n MISSING_UNIQUE_KEY: {\n phase: 'post_send',\n template:\n 'The gateway acknowledged RequestTrade without echoing its uniqueKey, so it cannot be tied to the signed request.',\n params: {},\n },\n UNIQUE_KEY_MISMATCH: {\n phase: 'post_send',\n template: 'Gateway response data.uniqueKey must match the signed RequestTrade uniqueKey.',\n params: {},\n },\n SHADOW_NOT_QUEUED: {\n phase: 'post_send',\n template: 'The swap backend did not queue the shadow request.',\n params: {},\n },\n SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS: {\n phase: 'pre_send',\n template:\n 'A shadow submission needs a walletAddress (the X-Wallet-Address header): pass one to the GSwap constructor or to this call.',\n params: {},\n },\n METHOD_NOT_ALLOWED: {\n phase: 'post_send',\n template: 'The gateway does not expose this contract method: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n SIGNATURE_INVALID: {\n phase: 'post_send',\n template: 'The gateway could not verify the signature: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n SIGNER_MISMATCH: {\n phase: 'post_send',\n template:\n 'The recovered signer does not match an actor named by the operation: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n DTO_INVALID: {\n phase: 'post_send',\n template: 'The gateway rejected the DTO shape: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n BOUNDS_VIOLATION: {\n phase: 'post_send',\n template: 'The gateway rejected a numeric, tick, symbol or range bound: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n SYMBOL_CONFLICT: {\n phase: 'post_send',\n template: 'The CreatePool symbol is already owned by another class: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n RATE_LIMITED: {\n phase: 'post_send',\n template: 'The gateway rate-limited this signer: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n CHAIN_DISPATCH_FAILED: {\n phase: 'post_send',\n template: 'The chain dispatch failed (chain error key \"{errorKey}\"): {serverMessage}',\n params: { errorKey: 'string', serverMessage: 'string' },\n },\n GATEWAY_REJECTED: {\n phase: 'post_send',\n template: 'Gateway rejected {gatewayCode}: {serverMessage}',\n params: { gatewayCode: 'string', serverMessage: 'string' },\n },\n CHAIN_REJECTED: {\n phase: 'post_send',\n template: 'GalaChain error {errorKey}: {serverMessage}',\n params: { errorKey: 'string', serverMessage: 'string' },\n },\n INVALID_CHAIN_RESPONSE: {\n phase: 'post_send',\n template: 'Backend returned an invalid {resource}.',\n params: { resource: 'string' },\n },\n INVALID_POSITION_RESPONSE: {\n phase: 'post_send',\n template: 'Backend returned an invalid position ({reason}).',\n params: { reason: 'string' },\n },\n\n // -------------------------------------------------------------------------------- confirmation\n CONFIRMATION_TIMEOUT: {\n phase: 'post_send',\n template:\n 'Transaction confirmation timed out; the trade may still apply. Confirm the same uniqueKey again later instead of resubmitting.',\n params: {},\n },\n CONFIRMATION_ABORTED: {\n phase: 'post_send',\n template: 'Transaction confirmation was aborted.',\n params: {},\n },\n CONFIRMATION_FAILED: {\n phase: 'post_send',\n template: 'Transaction confirmation failed with HTTP {status}.',\n params: { status: 'number', serverMessage: 'string' },\n unrendered: ['serverMessage'],\n },\n CONFIRMATION_MALFORMED: {\n phase: 'post_send',\n template: 'Transaction confirmation returned a malformed body.',\n params: {},\n },\n CONFIRMATION_KEY_MISMATCH: {\n phase: 'post_send',\n template: 'Apply result key did not match the requested key.',\n params: {},\n },\n\n // ----------------------------------------------------------------------------------- services\n NO_SIGNER: {\n phase: 'pre_send',\n template: 'This method requires a signer. Please provide a signer to the GSwap constructor.',\n params: {},\n },\n NO_WALLET_ADDRESS: {\n phase: 'post_send',\n template:\n 'Cannot confirm this write: no walletAddress was provided to the GSwap constructor, so the resulting position cannot be looked up to confirm it landed on chain.',\n params: {},\n },\n NO_POOL_AVAILABLE: {\n phase: 'post_send',\n template: 'No pool is available for {tokenIn}/{tokenOut} (fee tier {fee}).',\n params: { tokenIn: 'string', tokenOut: 'string', fee: 'string' },\n },\n INSUFFICIENT_LIQUIDITY: {\n phase: 'post_send',\n template:\n 'The selected pool has insufficient liquidity for {tokenIn}/{tokenOut} (fee tier {fee}).',\n params: { tokenIn: 'string', tokenOut: 'string', fee: 'string' },\n },\n UNKNOWN_TOKEN: {\n phase: 'pre_send',\n template: 'Token {token} is not registered on the DEX contract: it has no trading symbol.',\n params: { token: 'string' },\n },\n SYMBOL_NOT_FOUND: {\n phase: 'pre_send',\n template: 'Token {token} could not be resolved to a trading symbol.',\n params: { token: 'string' },\n },\n STREAM_API_KEY_UNUSABLE: {\n phase: 'pre_send',\n template:\n 'GdexStreamConfig.apiKey needs a non-empty key and an explicit webSocketImpl that accepts upgrade headers as its third argument (the \"ws\" package, or React Native). A browser WebSocket cannot send x-api-key, so the key would be silently dropped.',\n params: {},\n },\n STREAM_WEBSOCKET_UNAVAILABLE: {\n phase: 'pre_send',\n template:\n 'GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the \"ws\" package).',\n params: {},\n },\n STREAM_NOT_CONNECTED: {\n phase: 'pre_send',\n template: 'GDEX stream is not connected. Call connect() first.',\n params: {},\n },\n STREAM_DISCONNECTED: {\n phase: 'in_flight',\n template: 'GDEX stream disconnected.',\n params: {},\n },\n STREAM_REQUEST_TIMEOUT: {\n phase: 'in_flight',\n template: 'GDEX request \"{method}\" timed out after {timeoutMs} ms.',\n params: { method: 'string', timeoutMs: 'number' },\n },\n STREAM_CONNECT_FAILED: {\n phase: 'in_flight',\n template: 'Failed to connect to GDEX stream at {url}.',\n params: { url: 'string' },\n },\n STREAM_CLOSED_BEFORE_CONNECT: {\n phase: 'in_flight',\n template: 'GDEX stream closed before connecting (code {closeCode}).',\n params: { closeCode: 'number' },\n },\n STREAM_CONNECTION_CLOSED: {\n phase: 'in_flight',\n template: 'GDEX stream connection closed (code {closeCode}).',\n params: { closeCode: 'number' },\n },\n\n // ------------------------------------------------------------------------------ wallet / keys\n GALA_WALLET_NOT_AVAILABLE: {\n phase: 'pre_send',\n template: 'Gala wallet is not available. Please ensure the Gala wallet is connected.',\n params: {},\n },\n WALLET_UNAVAILABLE: {\n phase: 'pre_send',\n template: 'No wallet is connected.',\n params: {},\n },\n MALFORMED_WALLET_REQUEST: {\n phase: 'pre_send',\n template: 'Wallet {method} request is malformed.',\n params: { method: 'string' },\n },\n UNSUPPORTED_WALLET_METHOD: {\n phase: 'pre_send',\n template: 'Unsupported wallet method {method}.',\n params: { method: 'string' },\n },\n INVALID_SIGNATURE: {\n phase: 'pre_send',\n template: 'Wallet returned an invalid {scheme} signature.',\n params: { scheme: 'string' },\n },\n INVALID_CHAIN_ID: {\n phase: 'pre_send',\n template: 'Wallet returned an invalid chain id ({chainId}).',\n params: { chainId: 'string' },\n },\n SIGNER_ADDRESS_MISMATCH: {\n phase: 'pre_send',\n template: 'The signing key does not belong to the expected account.',\n params: {},\n },\n INVALID_PRIVATE_KEY: {\n phase: 'pre_send',\n template: 'Invalid private key: {reason}.',\n params: { reason: INVALID_PRIVATE_KEY_REASONS },\n },\n SIGNING_FAILED: {\n phase: 'pre_send',\n template: 'Signing the {method} request failed ({reason}); nothing was sent.',\n params: { method: 'string', reason: SIGNING_FAILURE_REASONS },\n },\n KEY_PROVIDER_FAILED: {\n phase: 'pre_send',\n template: 'The signing key could not be fetched; nothing was sent.',\n params: {},\n },\n TOKEN_RESOLUTION_FAILED: {\n phase: 'pre_send',\n template: 'Token {token} could not be looked up; nothing was sent.',\n params: { token: 'string' },\n },\n INVALID_SIGNING_HASH_LENGTH: {\n phase: 'pre_send',\n template: 'secp256k1 can only sign a 32-byte hash (got {length}).',\n params: { length: 'number' },\n },\n MISSING_WALLET_ADDRESS: {\n phase: 'pre_send',\n template:\n 'Invalid wallet address: No wallet address provided. Either provide a wallet address to the function you are calling, or set one when instantiating GSwapSDK.',\n params: {},\n },\n INVALID_WALLET_ADDRESS: {\n phase: 'pre_send',\n template: 'Invalid {field}: \"{value}\" is not an accepted wallet address form.',\n params: { field: 'string', value: 'string' },\n },\n INVALID_DECIMAL: {\n phase: 'pre_send',\n template: 'Invalid decimal quantity: {value}',\n params: { value: 'string' },\n },\n\n // ------------------------------------------------------------------------- personal-sign DTOs\n PERSONAL_SIGN_NOT_JSON: {\n phase: 'pre_send',\n template: 'Personal-sign DTO is not valid JSON',\n params: {},\n },\n PERSONAL_SIGN_NOT_OBJECT: {\n phase: 'pre_send',\n template: 'Personal-sign DTO must be a JSON object',\n params: {},\n },\n PERSONAL_SIGN_BAD_PREFIX: {\n phase: 'pre_send',\n template: 'Personal-sign DTO prefix is not an EIP-191 \"Ethereum Signed Message\" header',\n params: {},\n },\n PERSONAL_SIGN_ENVELOPE_FIELDS: {\n phase: 'pre_send',\n template: 'Personal-sign DTO carries signing-envelope field(s): {fields}',\n params: { fields: 'string' },\n },\n PERSONAL_SIGN_NOT_CANONICAL: {\n phase: 'pre_send',\n template: 'Personal-sign DTO is not in canonical serialized form',\n params: {},\n },\n\n // ------------------------------------------------------------------ EIP-712 payload derivation\n EIP712_NAME_COLLISION: {\n phase: 'pre_send',\n template: 'Name collisions are not supported when deriving EIP-712 types ({name}).',\n params: { name: 'string' },\n },\n EIP712_UNSUPPORTED_VALUE: {\n phase: 'pre_send',\n template: 'Unsupported EIP-712 value of type {valueType}.',\n params: { valueType: 'string' },\n },\n\n // ----------------------------------------------------------------------------- EIP-712 typed data\n TYPED_DATA_NOT_STRING: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be a string',\n params: { what: 'string' },\n },\n TYPED_DATA_UNPAIRED_SURROGATE: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} has an unpaired surrogate',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_HEX_BYTES: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be an even-length 0x hex string',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_SAFE_INTEGER: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be a safe integer',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_INTEGER: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be an integer',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_BOOLEAN: {\n phase: 'pre_send',\n template: 'Invalid typed data: bool must be a boolean',\n params: {},\n },\n TYPED_DATA_BAD_ADDRESS: {\n phase: 'pre_send',\n template: 'Invalid typed data: address must be 0x followed by 40 hex digits',\n params: {},\n },\n TYPED_DATA_BAD_CHECKSUM: {\n phase: 'pre_send',\n template: 'Invalid typed data: address has a bad checksum',\n params: {},\n },\n TYPED_DATA_BYTES_LENGTH: {\n phase: 'pre_send',\n template: 'Invalid typed data: {type} must be exactly {width} bytes',\n params: { type: 'string', width: 'number' },\n },\n TYPED_DATA_OUT_OF_BOUNDS: {\n phase: 'pre_send',\n template: 'Invalid typed data: value out of bounds for {type}',\n params: { type: 'string' },\n },\n TYPED_DATA_UNSUPPORTED_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: unsupported type \"{type}\"',\n params: { type: 'string' },\n },\n TYPED_DATA_FIELDS_NOT_LIST: {\n phase: 'pre_send',\n template: 'Invalid typed data: type {typeName} must be a list of fields',\n params: { typeName: 'string' },\n },\n TYPED_DATA_FIELD_MALFORMED: {\n phase: 'pre_send',\n template: 'Invalid typed data: type {typeName} has a field without a string name and type',\n params: { typeName: 'string' },\n },\n TYPED_DATA_INVALID_FIELD_NAME: {\n phase: 'pre_send',\n template: 'Invalid typed data: invalid field name \"{name}\"',\n params: { name: 'string' },\n },\n TYPED_DATA_DUPLICATE_FIELD: {\n phase: 'pre_send',\n template: 'Invalid typed data: duplicate field \"{name}\" in {typeName}',\n params: { name: 'string', typeName: 'string' },\n },\n TYPED_DATA_INVALID_TYPE_NAME: {\n phase: 'pre_send',\n template: 'Invalid typed data: invalid type name \"{name}\"',\n params: { name: 'string' },\n },\n TYPED_DATA_CIRCULAR_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: circular type reference in {typeName}',\n params: { typeName: 'string' },\n },\n TYPED_DATA_UNKNOWN_FIELD_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: unknown type \"{type}\" in {typeName}',\n params: { type: 'string', typeName: 'string' },\n },\n TYPED_DATA_NO_PRIMARY_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: missing primary type',\n params: {},\n },\n TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: ambiguous primary types or unused types ({roots})',\n params: { roots: 'string' },\n },\n TYPED_DATA_ARRAY_EXPECTED: {\n phase: 'pre_send',\n template: 'Invalid typed data: {type} array value must be an array',\n params: { type: 'string' },\n },\n TYPED_DATA_ARRAY_LENGTH_MISMATCH: {\n phase: 'pre_send',\n template: 'Invalid typed data: array length mismatch',\n params: {},\n },\n TYPED_DATA_STRUCT_NOT_OBJECT: {\n phase: 'pre_send',\n template: 'Invalid typed data: {typeName} value must be an object',\n params: { typeName: 'string' },\n },\n TYPED_DATA_MISSING_FIELD: {\n phase: 'pre_send',\n template: 'Invalid typed data: {typeName} value is missing field \"{field}\"',\n params: { typeName: 'string', field: 'string' },\n },\n TYPED_DATA_DOMAIN_NOT_OBJECT: {\n phase: 'pre_send',\n template: 'Invalid typed data: domain must be an object',\n params: {},\n },\n TYPED_DATA_INVALID_DOMAIN_KEY: {\n phase: 'pre_send',\n template: 'Invalid typed data: invalid typed-data domain key {key}',\n params: { key: 'string' },\n },\n\n // ------------------------------------------------------------------------ input validation\n NON_CANONICAL_PAIR: {\n phase: 'pre_send',\n template:\n 'The pair {token0}/{token1} is not in canonical order: token0 must sort before token1.',\n params: { token0: 'string', token1: 'string' },\n },\n UNORDERABLE_SYMBOLS: {\n phase: 'pre_send',\n template: 'Unable to order trading symbols: expected a pair of symbols, got {received}.',\n params: { received: 'string' },\n },\n INVALID_TOKEN_CLASS_KEY: {\n phase: 'pre_send',\n template:\n 'Invalid token class key \"{tokenClassKey}\": expected a collection followed by category, type and additionalKey',\n params: { tokenClassKey: 'string' },\n },\n INCOMPLETE_TOKEN_CLASS_KEY: {\n phase: 'pre_send',\n template: 'Token class key \"{compositeKey}\" is missing {part}.',\n params: { compositeKey: 'string', part: 'string' },\n },\n INVALID_TRADING_SYMBOL: {\n phase: 'pre_send',\n template:\n 'Invalid trading symbol \"{symbol}\": must be 1-32 ASCII letters and digits and not a reserved word (Token, Unit, none).',\n params: { symbol: 'string' },\n },\n NO_VALID_TRADING_SYMBOL: {\n phase: 'pre_send',\n template:\n 'No valid trading symbol for token class {classKey}: \"{displaySymbol}\" is not an acceptable symbol and none is registered',\n params: { classKey: 'string', displaySymbol: 'string' },\n },\n TOKEN_SYMBOL_NOT_REGISTERED: {\n phase: 'pre_send',\n template:\n 'Token {token} is not registered in the trading-symbol registry yet; pass token0Symbol/token1Symbol (the token class symbol) to propose one. A symbol cannot be derived from a class key.',\n params: { token: 'string' },\n },\n SYMBOL_DISAGREES_WITH_REGISTRY: {\n phase: 'pre_send',\n template:\n 'Supplied symbol {suppliedSymbol} for {token} disagrees with the registered trading symbol {registeredSymbol}.',\n params: { token: 'string', suppliedSymbol: 'string', registeredSymbol: 'string' },\n },\n CREATE_POOL_NEEDS_CLASS_KEY: {\n phase: 'pre_send',\n template:\n 'createPool needs each token as a class key; {token} is a bare trading symbol, which does not carry one.',\n params: { token: 'string' },\n },\n INVALID_UNIQUE_KEY: {\n phase: 'pre_send',\n template:\n 'The uniqueKey \"{uniqueKey}\" must be 1-128 characters of A-Z, a-z, 0-9, \".\", \"_\", \":\" or \"-\".',\n params: { uniqueKey: 'string' },\n },\n INVALID_UNIQUE_KEY_PREFIX: {\n phase: 'pre_send',\n template:\n 'uniqueKeyPrefix \"{uniqueKeyPrefix}\" must be at most {maxLength} characters of A-Z, a-z, 0-9, \".\", \"_\", \":\" or \"-\".',\n params: { uniqueKeyPrefix: 'string', maxLength: 'number' },\n },\n AMOUNT_IS_JS_NUMBER: {\n phase: 'pre_send',\n template: 'Invalid {field}: use a decimal string or BigNumber, not a JavaScript number',\n params: { field: 'string' },\n },\n AMOUNT_NOT_FINITE: {\n phase: 'pre_send',\n template: 'Invalid {field}: must be a finite number (got {value})',\n params: { field: 'string', value: 'string' },\n },\n AMOUNT_NOT_POSITIVE: {\n phase: 'pre_send',\n template: 'Invalid {field}: must be positive (got {value})',\n params: { field: 'string', value: 'string' },\n },\n AMOUNT_NEGATIVE: {\n phase: 'pre_send',\n template: 'Invalid {field}: must not be negative (got {value})',\n params: { field: 'string', value: 'string' },\n },\n PRICE_VALUES_IS_JS_NUMBER: {\n phase: 'pre_send',\n template:\n 'Invalid price values: use decimal strings or BigNumber values, not JavaScript numbers',\n params: {},\n },\n INVALID_PRICE_VALUES: {\n phase: 'pre_send',\n template:\n 'Invalid price values: all prices must be finite and positive (spot {spotPrice}, lower {lowerPrice}, upper {upperPrice})',\n params: { spotPrice: 'string', lowerPrice: 'string', upperPrice: 'string' },\n },\n INVALID_PRICE_RANGE: {\n phase: 'pre_send',\n template:\n 'Invalid price range: lower price {lowerPrice} must be less than or equal to upper price {upperPrice}',\n params: { lowerPrice: 'string', upperPrice: 'string' },\n },\n INVALID_PRICE_BOUNDS: {\n phase: 'pre_send',\n template:\n 'Price bounds must be finite and positive (minPrice {minPrice}, maxPrice {maxPrice}).',\n params: { minPrice: 'string', maxPrice: 'string' },\n },\n PRICE_BOUNDS_ORDER: {\n phase: 'pre_send',\n template: 'minPrice {minPrice} must be less than or equal to maxPrice {maxPrice}.',\n params: { minPrice: 'string', maxPrice: 'string' },\n },\n INVALID_STARTING_PRICE: {\n phase: 'pre_send',\n template: 'Starting price must be finite and positive (got {value}).',\n params: { value: 'string' },\n },\n INVALID_SQRT_PRICE: {\n phase: 'pre_send',\n template: 'Cannot invert a non-positive sqrt price ({sqrtPrice}).',\n params: { sqrtPrice: 'string' },\n },\n INVALID_TOKEN_DECIMALS: {\n phase: 'pre_send',\n template: 'Invalid {field}: must be a non-negative integer (got {value})',\n params: { field: 'string', value: 'number' },\n },\n TICKS_NOT_INTEGERS: {\n phase: 'pre_send',\n template: 'Invalid tick values: ticks must be integers (got {tickLower} and {tickUpper})',\n params: { tickLower: 'number', tickUpper: 'number' },\n },\n INVALID_TICK_RANGE: {\n phase: 'pre_send',\n template: 'Invalid tick range: tickLower {tickLower} must be less than tickUpper {tickUpper}',\n params: { tickLower: 'number', tickUpper: 'number' },\n },\n TICKS_OUT_OF_BOUNDS: {\n phase: 'pre_send',\n template:\n 'Invalid tick range: ticks {tickLower} and {tickUpper} must be between {minTick} and {maxTick}',\n params: { tickLower: 'number', tickUpper: 'number', minTick: 'number', maxTick: 'number' },\n },\n TICKS_NOT_ALIGNED: {\n phase: 'pre_send',\n template: 'Ticks {tickLower} and {tickUpper} must be aligned to spacing {spacing}.',\n params: { tickLower: 'number', tickUpper: 'number', spacing: 'number' },\n },\n INVALID_TICK_SPACING: {\n phase: 'pre_send',\n template: 'Invalid tick spacing: must be a positive integer (got {value})',\n params: { value: 'number' },\n },\n INVALID_FEE: {\n phase: 'pre_send',\n template: 'Invalid {field}: {value} is not a supported fee tier; must be one of {allowed}.',\n params: { field: 'string', value: 'number', allowed: 'string' },\n },\n EXACT_AMOUNT_REQUIRED: {\n phase: 'pre_send',\n template: '{field} is required for this swap.',\n params: { field: 'string' },\n },\n EXACTLY_ONE_OF_REQUIRED: {\n phase: 'pre_send',\n template: 'Provide exactly one of {first} or {second}.',\n params: { first: 'string', second: 'string' },\n },\n AT_MOST_ONE_OF_ALLOWED: {\n phase: 'pre_send',\n template: 'Provide at most one of {first} or {second}.',\n params: { first: 'string', second: 'string' },\n },\n POOL_MISMATCH: {\n phase: 'pre_send',\n template:\n 'tokenIn {tokenIn} and tokenOut {tokenOut} must be the two tokens of the pinned pool {poolToken0}/{poolToken1}.',\n params: {\n tokenIn: 'string',\n tokenOut: 'string',\n poolToken0: 'string',\n poolToken1: 'string',\n },\n },\n INVALID_DTO: {\n phase: 'pre_send',\n template: '{method} DTO field {field} is invalid (expected {expected}).',\n params: { method: 'string', field: 'string', expected: 'string' },\n },\n DTO_NOT_CANONICAL: {\n phase: 'pre_send',\n template:\n 'The {method} DTO is not in the form the SDK builders produce; build it with the matching build function and submit that.',\n params: { method: 'string' },\n },\n SEARCH_TOO_LONG: {\n phase: 'pre_send',\n template: 'search must be at most {maxLength} characters (got {length}).',\n params: { length: 'number', maxLength: 'number' },\n },\n INVALID_SORT_BY: {\n phase: 'pre_send',\n template: 'sortBy \"{value}\" is not allowed; it must be one of {allowed}.',\n params: { value: 'string', allowed: 'string' },\n },\n INVALID_SORT_ORDER: {\n phase: 'pre_send',\n template: 'sortOrder \"{value}\" is not allowed; it must be asc or desc.',\n params: { value: 'string' },\n },\n INVALID_PAGE: {\n phase: 'pre_send',\n template: 'page must be an integer of at least 1 (got {value}).',\n params: { value: 'number' },\n },\n INVALID_LIMIT: {\n phase: 'pre_send',\n template: 'limit must be an integer from {min} to {max} (got {value}).',\n params: { value: 'number', min: 'number', max: 'number' },\n },\n} as const satisfies Record<string, GSwapErrorCatalogEntry>;\n\n/** Every error code the SDK can throw. */\nexport type GSwapErrorCode = keyof typeof GSWAP_ERROR_CATALOG;\n\ninterface KindToType {\n string: string;\n number: number;\n boolean: boolean;\n}\n\n/** The value type of a param kind: a primitive, or the union of a closed set's members. */\ntype ParamValue<K> = K extends readonly (infer Member)[]\n ? Member\n : K extends keyof KindToType\n ? KindToType[K]\n : never;\n\n/** The named params of one error code: a flat object of primitives (or closed string tokens). */\nexport type GSwapErrorParams<C extends GSwapErrorCode> = {\n readonly [P in keyof (typeof GSWAP_ERROR_CATALOG)[C]['params']]: ParamValue<\n (typeof GSWAP_ERROR_CATALOG)[C]['params'][P]\n >;\n};\n\n/**\n * The English template of every error code, `{placeholder}` markers included. An optional seed\n * or fallback for an app's own translations; the SDK's `message` is generated from it.\n */\nexport const gswapErrorTemplates: { readonly [C in GSwapErrorCode]: string } = Object.fromEntries(\n Object.entries(GSWAP_ERROR_CATALOG).map(([code, entry]) => [code, entry.template]),\n) as { readonly [C in GSwapErrorCode]: string };\n\nconst PLACEHOLDER = /\\{([A-Za-z0-9_]+)\\}/gu;\n\n/** Fills a template's `{placeholders}` from `params`; an unknown placeholder is left as written. */\nexport function renderGSwapErrorTemplate(\n template: string,\n params: Readonly<Record<string, unknown>>,\n): string {\n return template.replace(PLACEHOLDER, (whole, name: string) => {\n const value = params[name];\n return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'\n ? String(value)\n : whole;\n });\n}\n\n/** The placeholder names a template uses, in order of first appearance. */\nexport function templatePlaceholders(template: string): string[] {\n return [...new Set([...template.matchAll(PLACEHOLDER)].map((match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V,OAAQ,CAAE,OAAQ,SAAU,MAAO,SAAU,SAAU,QAAS,CAClE,EACA,kBAAmB,CACjB,MAAO,WACP,SACE,2HACF,OAAQ,CAAE,OAAQ,QAAS,CAC7B,EACA,gBAAiB,CACf,MAAO,WACP,SAAU,gEACV,OAAQ,CAAE,OAAQ,SAAU,UAAW,QAAS,CAClD,EACA,gBAAiB,CACf,MAAO,WACP,SAAU,gEACV,OAAQ,CAAE,MAAO,SAAU,QAAS,QAAS,CAC/C,EACA,mBAAoB,CAClB,MAAO,WACP,SAAU,8DACV,OAAQ,CAAE,MAAO,QAAS,CAC5B,EACA,aAAc,CACZ,MAAO,WACP,SAAU,uDACV,OAAQ,CAAE,MAAO,QAAS,CAC5B,EACA,cAAe,CACb,MAAO,WACP,SAAU,8DACV,OAAQ,CAAE,MAAO,SAAU,IAAK,SAAU,IAAK,QAAS,CAC1D,CACF,EA6Ba,EAAkE,OAAO,YACpF,OAAO,QAAQ,CAAmB,CAAC,CAAC,KAAK,CAAC,EAAM,KAAW,CAAC,EAAM,EAAM,QAAQ,CAAC,CACnF,EAEM,EAAc,wBAGpB,SAAgB,EACd,EACA,EACQ,CACR,OAAO,EAAS,QAAQ,GAAc,EAAO,IAAiB,CAC5D,IAAM,EAAQ,EAAO,GACrB,OAAO,OAAO,GAAU,UAAY,OAAO,GAAU,UAAY,OAAO,GAAU,UAC9E,OAAO,CAAK,EACZ,CACN,CAAC,CACH"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e={HTTP_ERROR:`post_send`,UPDATE_REQUIRED:`post_send`,REQUEST_TIMEOUT:`in_flight`,TRANSPORT_ERROR:`in_flight`,REQUEST_FAILED:`in_flight`,INVALID_TIMEOUT:`pre_send`,METHOD_NOT_SUPPORTED:`pre_send`,SUBMISSION_OUTCOME_UNKNOWN:`in_flight`,GATEWAY_REPORTED_ERROR:`post_send`,GATEWAY_DATA_MISSING:`post_send`,GATEWAY_MODE_INVALID:`post_send`,GATEWAY_SYNC_REQUEST_TRADE:`post_send`,MISSING_UNIQUE_KEY:`post_send`,UNIQUE_KEY_MISMATCH:`post_send`,SHADOW_NOT_QUEUED:`post_send`,SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS:`pre_send`,METHOD_NOT_ALLOWED:`post_send`,SIGNATURE_INVALID:`post_send`,SIGNER_MISMATCH:`post_send`,DTO_INVALID:`post_send`,BOUNDS_VIOLATION:`post_send`,SYMBOL_CONFLICT:`post_send`,RATE_LIMITED:`post_send`,CHAIN_DISPATCH_FAILED:`post_send`,GATEWAY_REJECTED:`post_send`,CHAIN_REJECTED:`post_send`,INVALID_CHAIN_RESPONSE:`post_send`,INVALID_POSITION_RESPONSE:`post_send`,CONFIRMATION_TIMEOUT:`post_send`,CONFIRMATION_ABORTED:`post_send`,CONFIRMATION_FAILED:`post_send`,CONFIRMATION_MALFORMED:`post_send`,CONFIRMATION_KEY_MISMATCH:`post_send`,NO_SIGNER:`pre_send`,NO_WALLET_ADDRESS:`post_send`,NO_POOL_AVAILABLE:`post_send`,INSUFFICIENT_LIQUIDITY:`post_send`,UNKNOWN_TOKEN:`pre_send`,SYMBOL_NOT_FOUND:`pre_send`,STREAM_API_KEY_UNUSABLE:`pre_send`,STREAM_WEBSOCKET_UNAVAILABLE:`pre_send`,STREAM_NOT_CONNECTED:`pre_send`,STREAM_DISCONNECTED:`in_flight`,STREAM_REQUEST_TIMEOUT:`in_flight`,STREAM_CONNECT_FAILED:`in_flight`,STREAM_CLOSED_BEFORE_CONNECT:`in_flight`,STREAM_CONNECTION_CLOSED:`in_flight`,GALA_WALLET_NOT_AVAILABLE:`pre_send`,WALLET_UNAVAILABLE:`pre_send`,MALFORMED_WALLET_REQUEST:`pre_send`,UNSUPPORTED_WALLET_METHOD:`pre_send`,INVALID_SIGNATURE:`pre_send`,INVALID_CHAIN_ID:`pre_send`,SIGNER_ADDRESS_MISMATCH:`pre_send`,INVALID_PRIVATE_KEY:`pre_send`,SIGNING_FAILED:`pre_send`,KEY_PROVIDER_FAILED:`pre_send`,TOKEN_RESOLUTION_FAILED:`pre_send`,INVALID_SIGNING_HASH_LENGTH:`pre_send`,MISSING_WALLET_ADDRESS:`pre_send`,INVALID_WALLET_ADDRESS:`pre_send`,INVALID_DECIMAL:`pre_send`,PERSONAL_SIGN_NOT_JSON:`pre_send`,PERSONAL_SIGN_NOT_OBJECT:`pre_send`,PERSONAL_SIGN_BAD_PREFIX:`pre_send`,PERSONAL_SIGN_ENVELOPE_FIELDS:`pre_send`,PERSONAL_SIGN_NOT_CANONICAL:`pre_send`,EIP712_NAME_COLLISION:`pre_send`,EIP712_UNSUPPORTED_VALUE:`pre_send`,TYPED_DATA_NOT_STRING:`pre_send`,TYPED_DATA_UNPAIRED_SURROGATE:`pre_send`,TYPED_DATA_NOT_HEX_BYTES:`pre_send`,TYPED_DATA_NOT_SAFE_INTEGER:`pre_send`,TYPED_DATA_NOT_INTEGER:`pre_send`,TYPED_DATA_NOT_BOOLEAN:`pre_send`,TYPED_DATA_BAD_ADDRESS:`pre_send`,TYPED_DATA_BAD_CHECKSUM:`pre_send`,TYPED_DATA_BYTES_LENGTH:`pre_send`,TYPED_DATA_OUT_OF_BOUNDS:`pre_send`,TYPED_DATA_UNSUPPORTED_TYPE:`pre_send`,TYPED_DATA_FIELDS_NOT_LIST:`pre_send`,TYPED_DATA_FIELD_MALFORMED:`pre_send`,TYPED_DATA_INVALID_FIELD_NAME:`pre_send`,TYPED_DATA_DUPLICATE_FIELD:`pre_send`,TYPED_DATA_INVALID_TYPE_NAME:`pre_send`,TYPED_DATA_CIRCULAR_TYPE:`pre_send`,TYPED_DATA_UNKNOWN_FIELD_TYPE:`pre_send`,TYPED_DATA_NO_PRIMARY_TYPE:`pre_send`,TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE:`pre_send`,TYPED_DATA_ARRAY_EXPECTED:`pre_send`,TYPED_DATA_ARRAY_LENGTH_MISMATCH:`pre_send`,TYPED_DATA_STRUCT_NOT_OBJECT:`pre_send`,TYPED_DATA_MISSING_FIELD:`pre_send`,TYPED_DATA_DOMAIN_NOT_OBJECT:`pre_send`,TYPED_DATA_INVALID_DOMAIN_KEY:`pre_send`,NON_CANONICAL_PAIR:`pre_send`,UNORDERABLE_SYMBOLS:`pre_send`,INVALID_TOKEN_CLASS_KEY:`pre_send`,INCOMPLETE_TOKEN_CLASS_KEY:`pre_send`,INVALID_TRADING_SYMBOL:`pre_send`,NO_VALID_TRADING_SYMBOL:`pre_send`,TOKEN_SYMBOL_NOT_REGISTERED:`pre_send`,SYMBOL_DISAGREES_WITH_REGISTRY:`pre_send`,CREATE_POOL_NEEDS_CLASS_KEY:`pre_send`,INVALID_UNIQUE_KEY:`pre_send`,INVALID_UNIQUE_KEY_PREFIX:`pre_send`,AMOUNT_IS_JS_NUMBER:`pre_send`,AMOUNT_NOT_FINITE:`pre_send`,AMOUNT_NOT_POSITIVE:`pre_send`,AMOUNT_NEGATIVE:`pre_send`,PRICE_VALUES_IS_JS_NUMBER:`pre_send`,INVALID_PRICE_VALUES:`pre_send`,INVALID_PRICE_RANGE:`pre_send`,INVALID_PRICE_BOUNDS:`pre_send`,PRICE_BOUNDS_ORDER:`pre_send`,INVALID_STARTING_PRICE:`pre_send`,INVALID_SQRT_PRICE:`pre_send`,INVALID_TOKEN_DECIMALS:`pre_send`,TICKS_NOT_INTEGERS:`pre_send`,INVALID_TICK_RANGE:`pre_send`,TICKS_OUT_OF_BOUNDS:`pre_send`,TICKS_NOT_ALIGNED:`pre_send`,INVALID_TICK_SPACING:`pre_send`,INVALID_FEE:`pre_send`,EXACT_AMOUNT_REQUIRED:`pre_send`,EXACTLY_ONE_OF_REQUIRED:`pre_send`,AT_MOST_ONE_OF_ALLOWED:`pre_send`,POOL_MISMATCH:`pre_send`,INVALID_DTO:`pre_send`,DTO_NOT_CANONICAL:`pre_send`,SEARCH_TOO_LONG:`pre_send`,INVALID_SORT_BY:`pre_send`,INVALID_SORT_ORDER:`pre_send`,INVALID_PAGE:`pre_send`,INVALID_LIMIT:`pre_send`};function t(t){return Object.hasOwn(e,t)}function n(n){return n.phase===void 0?t(n.code)?e[n.code]:void 0:n.phase}export{e as GSWAP_ERROR_PHASE_BY_CODE,t as isCatalogCode,n as phaseOfView};
|
|
2
|
-
//# sourceMappingURL=error_phase_table.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"error_phase_table.js","names":[],"sources":["../../../src/classes/error_phase_table.ts"],"sourcesContent":["import type { GSWAP_ERROR_CATALOG, GSwapErrorCode } from './error_catalog.js';\nimport type { GSwapErrorPhase } from './error_phases.js';\nimport type { FailureView } from '../utils/failure_view.js';\n\n/**\n * The phase of every catalog code, WITHOUT the catalog. The failure guards (`classifyFailure`,\n * `mayHaveBeenQueued`, ...) need only a code's phase, and the catalog's English templates are\n * ~20 kB: reading the phase from here keeps an app shell that imports a guard from loading them.\n * The catalog entry is still where a code is declared; this table is checked against it AT\n * COMPILE TIME, in both directions (a missing code, an extra code or a different phase is a type\n * error), so the two cannot drift.\n */\nexport const GSWAP_ERROR_PHASE_BY_CODE = {\n HTTP_ERROR: 'post_send',\n UPDATE_REQUIRED: 'post_send',\n REQUEST_TIMEOUT: 'in_flight',\n TRANSPORT_ERROR: 'in_flight',\n REQUEST_FAILED: 'in_flight',\n INVALID_TIMEOUT: 'pre_send',\n METHOD_NOT_SUPPORTED: 'pre_send',\n SUBMISSION_OUTCOME_UNKNOWN: 'in_flight',\n GATEWAY_REPORTED_ERROR: 'post_send',\n GATEWAY_DATA_MISSING: 'post_send',\n GATEWAY_MODE_INVALID: 'post_send',\n GATEWAY_SYNC_REQUEST_TRADE: 'post_send',\n MISSING_UNIQUE_KEY: 'post_send',\n UNIQUE_KEY_MISMATCH: 'post_send',\n SHADOW_NOT_QUEUED: 'post_send',\n SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS: 'pre_send',\n METHOD_NOT_ALLOWED: 'post_send',\n SIGNATURE_INVALID: 'post_send',\n SIGNER_MISMATCH: 'post_send',\n DTO_INVALID: 'post_send',\n BOUNDS_VIOLATION: 'post_send',\n SYMBOL_CONFLICT: 'post_send',\n RATE_LIMITED: 'post_send',\n CHAIN_DISPATCH_FAILED: 'post_send',\n GATEWAY_REJECTED: 'post_send',\n CHAIN_REJECTED: 'post_send',\n INVALID_CHAIN_RESPONSE: 'post_send',\n INVALID_POSITION_RESPONSE: 'post_send',\n CONFIRMATION_TIMEOUT: 'post_send',\n CONFIRMATION_ABORTED: 'post_send',\n CONFIRMATION_FAILED: 'post_send',\n CONFIRMATION_MALFORMED: 'post_send',\n CONFIRMATION_KEY_MISMATCH: 'post_send',\n NO_SIGNER: 'pre_send',\n NO_WALLET_ADDRESS: 'post_send',\n NO_POOL_AVAILABLE: 'post_send',\n INSUFFICIENT_LIQUIDITY: 'post_send',\n UNKNOWN_TOKEN: 'pre_send',\n SYMBOL_NOT_FOUND: 'pre_send',\n STREAM_API_KEY_UNUSABLE: 'pre_send',\n STREAM_WEBSOCKET_UNAVAILABLE: 'pre_send',\n STREAM_NOT_CONNECTED: 'pre_send',\n STREAM_DISCONNECTED: 'in_flight',\n STREAM_REQUEST_TIMEOUT: 'in_flight',\n STREAM_CONNECT_FAILED: 'in_flight',\n STREAM_CLOSED_BEFORE_CONNECT: 'in_flight',\n STREAM_CONNECTION_CLOSED: 'in_flight',\n GALA_WALLET_NOT_AVAILABLE: 'pre_send',\n WALLET_UNAVAILABLE: 'pre_send',\n MALFORMED_WALLET_REQUEST: 'pre_send',\n UNSUPPORTED_WALLET_METHOD: 'pre_send',\n INVALID_SIGNATURE: 'pre_send',\n INVALID_CHAIN_ID: 'pre_send',\n SIGNER_ADDRESS_MISMATCH: 'pre_send',\n INVALID_PRIVATE_KEY: 'pre_send',\n SIGNING_FAILED: 'pre_send',\n KEY_PROVIDER_FAILED: 'pre_send',\n TOKEN_RESOLUTION_FAILED: 'pre_send',\n INVALID_SIGNING_HASH_LENGTH: 'pre_send',\n MISSING_WALLET_ADDRESS: 'pre_send',\n INVALID_WALLET_ADDRESS: 'pre_send',\n INVALID_DECIMAL: 'pre_send',\n PERSONAL_SIGN_NOT_JSON: 'pre_send',\n PERSONAL_SIGN_NOT_OBJECT: 'pre_send',\n PERSONAL_SIGN_BAD_PREFIX: 'pre_send',\n PERSONAL_SIGN_ENVELOPE_FIELDS: 'pre_send',\n PERSONAL_SIGN_NOT_CANONICAL: 'pre_send',\n EIP712_NAME_COLLISION: 'pre_send',\n EIP712_UNSUPPORTED_VALUE: 'pre_send',\n TYPED_DATA_NOT_STRING: 'pre_send',\n TYPED_DATA_UNPAIRED_SURROGATE: 'pre_send',\n TYPED_DATA_NOT_HEX_BYTES: 'pre_send',\n TYPED_DATA_NOT_SAFE_INTEGER: 'pre_send',\n TYPED_DATA_NOT_INTEGER: 'pre_send',\n TYPED_DATA_NOT_BOOLEAN: 'pre_send',\n TYPED_DATA_BAD_ADDRESS: 'pre_send',\n TYPED_DATA_BAD_CHECKSUM: 'pre_send',\n TYPED_DATA_BYTES_LENGTH: 'pre_send',\n TYPED_DATA_OUT_OF_BOUNDS: 'pre_send',\n TYPED_DATA_UNSUPPORTED_TYPE: 'pre_send',\n TYPED_DATA_FIELDS_NOT_LIST: 'pre_send',\n TYPED_DATA_FIELD_MALFORMED: 'pre_send',\n TYPED_DATA_INVALID_FIELD_NAME: 'pre_send',\n TYPED_DATA_DUPLICATE_FIELD: 'pre_send',\n TYPED_DATA_INVALID_TYPE_NAME: 'pre_send',\n TYPED_DATA_CIRCULAR_TYPE: 'pre_send',\n TYPED_DATA_UNKNOWN_FIELD_TYPE: 'pre_send',\n TYPED_DATA_NO_PRIMARY_TYPE: 'pre_send',\n TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE: 'pre_send',\n TYPED_DATA_ARRAY_EXPECTED: 'pre_send',\n TYPED_DATA_ARRAY_LENGTH_MISMATCH: 'pre_send',\n TYPED_DATA_STRUCT_NOT_OBJECT: 'pre_send',\n TYPED_DATA_MISSING_FIELD: 'pre_send',\n TYPED_DATA_DOMAIN_NOT_OBJECT: 'pre_send',\n TYPED_DATA_INVALID_DOMAIN_KEY: 'pre_send',\n NON_CANONICAL_PAIR: 'pre_send',\n UNORDERABLE_SYMBOLS: 'pre_send',\n INVALID_TOKEN_CLASS_KEY: 'pre_send',\n INCOMPLETE_TOKEN_CLASS_KEY: 'pre_send',\n INVALID_TRADING_SYMBOL: 'pre_send',\n NO_VALID_TRADING_SYMBOL: 'pre_send',\n TOKEN_SYMBOL_NOT_REGISTERED: 'pre_send',\n SYMBOL_DISAGREES_WITH_REGISTRY: 'pre_send',\n CREATE_POOL_NEEDS_CLASS_KEY: 'pre_send',\n INVALID_UNIQUE_KEY: 'pre_send',\n INVALID_UNIQUE_KEY_PREFIX: 'pre_send',\n AMOUNT_IS_JS_NUMBER: 'pre_send',\n AMOUNT_NOT_FINITE: 'pre_send',\n AMOUNT_NOT_POSITIVE: 'pre_send',\n AMOUNT_NEGATIVE: 'pre_send',\n PRICE_VALUES_IS_JS_NUMBER: 'pre_send',\n INVALID_PRICE_VALUES: 'pre_send',\n INVALID_PRICE_RANGE: 'pre_send',\n INVALID_PRICE_BOUNDS: 'pre_send',\n PRICE_BOUNDS_ORDER: 'pre_send',\n INVALID_STARTING_PRICE: 'pre_send',\n INVALID_SQRT_PRICE: 'pre_send',\n INVALID_TOKEN_DECIMALS: 'pre_send',\n TICKS_NOT_INTEGERS: 'pre_send',\n INVALID_TICK_RANGE: 'pre_send',\n TICKS_OUT_OF_BOUNDS: 'pre_send',\n TICKS_NOT_ALIGNED: 'pre_send',\n INVALID_TICK_SPACING: 'pre_send',\n INVALID_FEE: 'pre_send',\n EXACT_AMOUNT_REQUIRED: 'pre_send',\n EXACTLY_ONE_OF_REQUIRED: 'pre_send',\n AT_MOST_ONE_OF_ALLOWED: 'pre_send',\n POOL_MISMATCH: 'pre_send',\n INVALID_DTO: 'pre_send',\n DTO_NOT_CANONICAL: 'pre_send',\n SEARCH_TOO_LONG: 'pre_send',\n INVALID_SORT_BY: 'pre_send',\n INVALID_SORT_ORDER: 'pre_send',\n INVALID_PAGE: 'pre_send',\n INVALID_LIMIT: 'pre_send',\n} as const satisfies {\n readonly [C in GSwapErrorCode]: (typeof GSWAP_ERROR_CATALOG)[C]['phase'];\n};\n\n/** True for a code the SDK catalog defines. */\nexport function isCatalogCode(code: string): code is GSwapErrorCode {\n return Object.hasOwn(GSWAP_ERROR_PHASE_BY_CODE, code);\n}\n\n/** The phase of a view: the one it states, else the catalog's phase for its code, else `undefined`. */\nexport function phaseOfView(view: FailureView): GSwapErrorPhase | undefined {\n if (view.phase !== undefined) return view.phase;\n return isCatalogCode(view.code) ? GSWAP_ERROR_PHASE_BY_CODE[view.code] : undefined;\n}\n"],"mappings":"AAYA,MAAa,EAA4B,CACvC,WAAY,YACZ,gBAAiB,YACjB,gBAAiB,YACjB,gBAAiB,YACjB,eAAgB,YAChB,gBAAiB,WACjB,qBAAsB,WACtB,2BAA4B,YAC5B,uBAAwB,YACxB,qBAAsB,YACtB,qBAAsB,YACtB,2BAA4B,YAC5B,mBAAoB,YACpB,oBAAqB,YACrB,kBAAmB,YACnB,mCAAoC,WACpC,mBAAoB,YACpB,kBAAmB,YACnB,gBAAiB,YACjB,YAAa,YACb,iBAAkB,YAClB,gBAAiB,YACjB,aAAc,YACd,sBAAuB,YACvB,iBAAkB,YAClB,eAAgB,YAChB,uBAAwB,YACxB,0BAA2B,YAC3B,qBAAsB,YACtB,qBAAsB,YACtB,oBAAqB,YACrB,uBAAwB,YACxB,0BAA2B,YAC3B,UAAW,WACX,kBAAmB,YACnB,kBAAmB,YACnB,uBAAwB,YACxB,cAAe,WACf,iBAAkB,WAClB,wBAAyB,WACzB,6BAA8B,WAC9B,qBAAsB,WACtB,oBAAqB,YACrB,uBAAwB,YACxB,sBAAuB,YACvB,6BAA8B,YAC9B,yBAA0B,YAC1B,0BAA2B,WAC3B,mBAAoB,WACpB,yBAA0B,WAC1B,0BAA2B,WAC3B,kBAAmB,WACnB,iBAAkB,WAClB,wBAAyB,WACz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,OAAO,EAA2B,CAAI,CACtD,CAGA,SAAgB,EAAY,EAAgD,CAE1E,OADI,EAAK,QAAU,IAAA,GACZ,EAAc,EAAK,IAAI,EAAI,EAA0B,EAAK,MAAQ,IAAA,GADpC,EAAK,KAE5C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"error_phases.js","names":[],"sources":["../../../src/classes/error_phases.ts"],"sourcesContent":["/**\n * How far an operation had got when it failed, measured against the request it exists to send:\n * for a write, the POST that carries the signed DTO to the gateway; for a read, the GET.\n *\n * - `pre_send`: NOTHING was transmitted. Everything up to the request (validation, symbol\n * resolution, the signer, the wallet, a key provider) ran and failed, so no write can have been\n * queued. A write that failed `pre_send` is never \"maybe applied\".\n * - `in_flight`: the request left (or may have left) and no answer was read: a timeout, a broken\n * connection, a stream that dropped. For a write the outcome is unknown.\n * - `post_send`: an answer was read, or the write was already accepted: a refusal, an\n * acknowledgement that proves nothing, an unusable body, and every failure of a confirmation.\n *\n * Each catalog entry declares the phase its code is thrown in; a throw site where the same code\n * can occur in another phase overrides it (`GSwapErrorContext.phase`). It is a typed property of\n * every `GSwapSDKError` (`error.phase`) and `isPreSendError(error)` reads it.\n *\n * This module has no imports, on purpose: it is the closed set of phases, shared by the catalog,\n * the light phase table (`error_phase_table.ts`) and the failure view.\n */\nexport const GSWAP_ERROR_PHASES = ['pre_send', 'in_flight', 'post_send'] as const;\n\n/** One member of {@link GSWAP_ERROR_PHASES}. */\nexport type GSwapErrorPhase = (typeof GSWAP_ERROR_PHASES)[number];\n"],"mappings":"AAmBA,MAAa,EAAqB,CAAC,WAAY,YAAa,WAAW"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import e from"../_virtual/_@oxc-project_runtime@0.151.0/helpers/esm/defineProperty.js";import{GSwapSDKError as t,isGSwapError as n}from"./gswap_sdk_error.js";import{EIP712_CAPABLE_METHODS as r,buildEIP712Payload as i,eip712DomainFor as a}from"../utils/eip712.js";import{ethAddressOfPrivateKey as o,fixpointPrefixFor as s,normalizePrivateKey as c,personalSignPrefixFor as l,serialize as u,signNative as d}from"../utils/signing.js";function f(){let e=globalThis.window?.gala;if(!e)throw new t(`GALA_WALLET_NOT_AVAILABLE`,{});return e}function p(e){if(typeof e!=`string`||!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(e))throw new t(`INVALID_SIGNATURE`,{scheme:`native`});return e}function m(e){if(typeof e!=`string`||!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(e))throw new t(`INVALID_SIGNATURE`,{scheme:`personal-sign`});return e}function h(e){let t=/^(?:eth\|(?:0x)?|0x)([0-9a-fA-F]{40})$/u.exec(e);return t?.[1]===void 0?void 0:`0x${t[1]}`}function g(e,n){let r=n?h(e)??e:e;if(!/^0x[0-9a-fA-F]{40}$/u.test(r))throw new t(`INVALID_WALLET_ADDRESS`,{field:`walletAddress`,value:e});return r}function _(e){let n=/^eth\|(?:0x)?([0-9a-fA-F]{40})$/u.exec(e);if(n?.[1]!==void 0)return`0x${n[1]}`;if(/^0x[0-9a-fA-F]{40}$/u.test(e)||/^(?:client\|)?[0-9a-fA-F]{24}$/u.test(e))return e;throw new t(`INVALID_WALLET_ADDRESS`,{field:`walletAddress`,value:e})}function v(e){if(!/^(?:eth\|(?:0x)?[0-9a-fA-F]{40}|0x[0-9a-fA-F]{40}|(?:client\|)?[0-9a-fA-F]{24})$/u.test(e))throw new t(`INVALID_WALLET_ADDRESS`,{field:`selectAddress`,value:e})}const y=/* @__PURE__ */ new WeakMap;function b(e,t,n){let{setAddress:r}=e;if(t===void 0||typeof r!=`function`)return n();let i=(y.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>(await r.call(e,t),n()));return y.set(e,i),i}function x(e,t,n,r){let i=l(t),a={...t,prefix:i},o=r===void 0?[u(t),n]:[u(a),n,r];return e.request({method:r===void 0?`personal_sign`:`gala_signChainDto`,params:o}).then(e=>({...a,signature:m(e)}))}async function S(e,t,n,r){let{completedDto:o,types:c}=i(t,n),l=a(await e.request({method:`eth_chainId`,params:[]})),u=s(o),d={...o,prefix:u},f=[{name:`name`,type:`string`},{name:`chainId`,type:`uint256`}],p={domain:l,types:{...c,EIP712Domain:f},primaryType:t,message:d},h=await e.request({method:`eth_signTypedData_v4`,params:[r,JSON.stringify(p)]});return{...d,signature:m(h),types:c,domain:l}}var C=class{constructor(t){e(this,`privateKey`,void 0),this.privateKey=c(t)}signObject(e,t){let n=d(this.privateKey,t);return Promise.resolve({...t,signature:n})}};async function w(e){try{return await e()}catch(e){throw n(e)?e:new t(`KEY_PROVIDER_FAILED`,{},{cause:e})}}function T(e,n={}){let r=n.expectedAddress,i=r===void 0?void 0:g(r,!0).toLowerCase();return{async signObject(n,r){let a=await w(e);if(typeof a!=`string`||a===``)throw new t(`INVALID_PRIVATE_KEY`,{reason:`no_key_provided`});let s=c(a);try{if(i!==void 0&&o(s)!==i)throw new t(`SIGNER_ADDRESS_MISMATCH`,{});return{...r,signature:d(s,r)}}finally{s.fill(0)}}}}var E=class{constructor(t,n={}){e(this,`walletAddress`,void 0),e(this,`scheme`,void 0),e(this,`selectAddress`,void 0),this.walletAddress=_(t),this.scheme=n.scheme??`native`,n.selectAddress!==void 0&&v(n.selectAddress),this.selectAddress=n.selectAddress}async signObject(e,t){let n=f();return b(n,this.selectAddress,async()=>{if(this.scheme===`personal-sign`)return x(n,t,this.walletAddress,e);let r=await n.request({method:`gala_signChainDto`,params:[u(t),this.walletAddress,e,`native`]});return{...t,signature:p(r)}})}},D=class{constructor(t,n,r={}){this.provider=t,e(this,`walletAddress`,void 0),e(this,`scheme`,void 0),this.walletAddress=g(n,!1),this.scheme=r.scheme??`personal-sign`}signObject(e,t){return this.scheme===`eip712`&&r.has(e)?S(this.provider,e,t,this.walletAddress):x(this.provider,t,this.walletAddress)}};export{D as BrowserWalletSigner,E as GalaWalletSigner,C as PrivateKeySigner,T as createLazyPrivateKeySigner,h as ethereumAddressOfAccount};
|
|
2
|
-
//# sourceMappingURL=signers.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"signers.js","names":["globalObject"],"sources":["../../../src/classes/signers.ts"],"sourcesContent":["import { GSwapSDKError, isGSwapError } from './gswap_sdk_error.js';\nimport {\n buildEIP712Payload,\n EIP712_CAPABLE_METHODS,\n eip712DomainFor,\n type EIP712DomainValue,\n type EIP712Types,\n} from '../utils/eip712.js';\nimport {\n ethAddressOfPrivateKey,\n fixpointPrefixFor,\n normalizePrivateKey,\n personalSignPrefixFor,\n serialize,\n signNative,\n} from '../utils/signing.js';\n\n// Personal-sign prefix, computed the way THE CHAIN verifies it.\n//\n// GalaChain (SDK 3.x) recovers a personal-signed DTO from\n// keccak256(<prefix field> + <canonical JSON of the DTO WITHOUT the prefix field>)\n// and a browser wallet's `personal_sign` (EIP-191) hashes\n// \"\\u0019Ethereum Signed Message:\\n\" + <byte length of message> + <message>.\n// They agree exactly when the wallet signs the bare canonical DTO and `prefix` is the EIP-191\n// header for that message's UTF-8 BYTE length. Any other message still yields a valid-looking\n// signature — it just recovers to an address nobody holds. This SDK used to embed `prefix` in\n// the signed message (the SDK 1.10 client recipe): observed on stage 2026-09-23, such a\n// MetaMask-signed CreatePool executed on chain under a phantom creator, and defi-backend's\n// bouncer now rejects that shape outright.\n//\n// `@gala-chain/connect`'s prefix helper must NOT be used for wallet `personal_sign`: its\n// fixpoint counts the prefix itself and targets the SDK's raw-payload signer. The same header\n// is also what Gala Wallet's `gala_signChainDto` (personal-sign scheme) prepends before hashing,\n// so one value serves both paths.\n//\n// The header itself is computed by `personalSignPrefixFor` in ../utils/signing.ts.\n\n/** The signing schemes supported by the Gala Wallet signer. */\nexport type GalaWalletScheme = 'native' | 'personal-sign';\n\n/** The request surface used by an EIP-1193 browser wallet. */\nexport interface BrowserWalletProvider {\n request(args: { method: string; params?: unknown[] }): Promise<unknown>;\n}\n\ninterface GalaWalletProvider {\n request(args: { method: string; params?: unknown[] }): Promise<unknown>;\n /** Gala Wallet's \"act as this account\" switch; absent on other providers. */\n setAddress?: (address: string) => Promise<void>;\n}\n\ninterface WindowWithGala {\n gala?: GalaWalletProvider;\n}\n\ninterface GlobalWithWindow {\n window?: WindowWithGala;\n}\n\n/** A DTO together with the signature that belongs in the gateway request body. */\nexport type SignedDto<T extends Record<string, unknown>> = T & { signature: string };\n\n/**\n * A signer for complete GalaChain write bodies.\n *\n * Implementations return the DTO fields together with the signature that belongs in the\n * gateway request body. Signer identity is recovered from that signature; implementations do\n * not add signer hints, typed-data metadata, or a domain.\n */\nexport interface GalaChainSigner {\n /**\n * Signs a DTO for a named GalaChain contract method.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n */\n signObject<T extends Record<string, unknown>>(methodName: string, dto: T): Promise<SignedDto<T>>;\n}\n\nfunction getWalletProvider(): GalaWalletProvider {\n const globalObject = globalThis as GlobalWithWindow;\n const wallet = globalObject.window?.gala;\n if (!wallet) {\n throw new GSwapSDKError('GALA_WALLET_NOT_AVAILABLE', {});\n }\n return wallet;\n}\n\nfunction getNativeSignature(value: unknown): string {\n if (typeof value !== 'string') {\n throw new GSwapSDKError('INVALID_SIGNATURE', { scheme: 'native' });\n }\n // 130 hex digits (r || s || v), bare as Gala Wallet returns it or `0x`-prefixed; passed on\n // verbatim, because the backend recovers the signer from either spelling.\n if (!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(value)) {\n throw new GSwapSDKError('INVALID_SIGNATURE', { scheme: 'native' });\n }\n return value;\n}\n\nfunction getPersonalSignature(value: unknown): string {\n if (typeof value !== 'string' || !/^(?:0x)?[0-9a-fA-F]{130}$/u.test(value)) {\n throw new GSwapSDKError('INVALID_SIGNATURE', { scheme: 'personal-sign' });\n }\n return value;\n}\n\n/**\n * The `0x`-prefixed Ethereum address a Gala account is signed by, or `undefined` when the account\n * names no key (a `client|` alias or a bare GalaChain id is not derivable from a key). Accepts\n * `0x` plus 40 hex digits and `eth|` plus 40 hex digits, with or without `0x`; the caller's casing\n * is kept. For {@link LazyPrivateKeySignerOptions.expectedAddress}, which should only be set for\n * an account whose key can be checked.\n *\n * @example\n * ```ts\n * createLazyPrivateKeySigner(getKey, { expectedAddress: ethereumAddressOfAccount(account) });\n * ```\n */\nexport function ethereumAddressOfAccount(account: string): string | undefined {\n const match = /^(?:eth\\|(?:0x)?|0x)([0-9a-fA-F]{40})$/u.exec(account);\n return match?.[1] === undefined ? undefined : `0x${match[1]}`;\n}\n\nfunction normalizeEthereumAccount(address: string, allowGalaPrefix: boolean): string {\n const normalized = allowGalaPrefix ? (ethereumAddressOfAccount(address) ?? address) : address;\n if (!/^0x[0-9a-fA-F]{40}$/u.test(normalized)) {\n throw new GSwapSDKError('INVALID_WALLET_ADDRESS', { field: 'walletAddress', value: address });\n }\n // The caller's casing is kept on purpose: frontend_v2 and the wallet hand the wallet the\n // checksummed account, and EIP-1193 / Gala Wallet accept any case, so passing the value through\n // unchanged is the only choice that cannot differ from what they send.\n return normalized;\n}\n\n/**\n * The account handed to Gala Wallet as the signer address. An Ethereum account is held to the\n * same strict check as ever (`0x` plus 40 hex digits; `eth|` plus 40 hex digits, with or without\n * `0x`, is normalized to it). A GalaChain id the wallet can also be asked to sign for is passed\n * through verbatim: `client|` plus 24 hex digits, or the bare 24 hex digits that frontend_v2 keeps\n * in `state.user.wallet` after a direct `client|` login. Nothing else is accepted.\n */\nfunction normalizeGalaWalletAccount(address: string): string {\n const eth = /^eth\\|(?:0x)?([0-9a-fA-F]{40})$/u.exec(address);\n if (eth?.[1] !== undefined) return `0x${eth[1]}`;\n if (/^0x[0-9a-fA-F]{40}$/u.test(address) || /^(?:client\\|)?[0-9a-fA-F]{24}$/u.test(address)) {\n return address;\n }\n throw new GSwapSDKError('INVALID_WALLET_ADDRESS', { field: 'walletAddress', value: address });\n}\n\n/** An identity Gala Wallet can act as: an account form above, any `eth|`/`client|` alias, verbatim. */\nfunction assertWalletIdentity(identity: string): void {\n if (\n !/^(?:eth\\|(?:0x)?[0-9a-fA-F]{40}|0x[0-9a-fA-F]{40}|(?:client\\|)?[0-9a-fA-F]{24})$/u.test(\n identity,\n )\n ) {\n throw new GSwapSDKError('INVALID_WALLET_ADDRESS', { field: 'selectAddress', value: identity });\n }\n}\n\n/** Provider-wide queue: `setAddress` + the signature request must not interleave across signers. */\nconst walletIdentityQueue = new WeakMap<object, Promise<unknown>>();\n\n/**\n * Runs `signWith` with `identity` selected on a Gala Wallet that supports `setAddress`. Gala\n * Wallet holds ONE current account, so two signatures for different identities in flight at once\n * would sign as whichever selection came last; the pair (select, sign) is therefore serialized\n * per provider. A failed selection fails the signature (nothing is requested).\n */\nfunction withSelectedIdentity<T>(\n wallet: GalaWalletProvider,\n identity: string | undefined,\n signWith: () => Promise<T>,\n): Promise<T> {\n const { setAddress } = wallet;\n if (identity === undefined || typeof setAddress !== 'function') return signWith();\n const previous = walletIdentityQueue.get(wallet) ?? Promise.resolve();\n const run = previous\n .catch(() => undefined)\n .then(async () => {\n await setAddress.call(wallet, identity);\n return signWith();\n });\n walletIdentityQueue.set(wallet, run);\n return run;\n}\n\nfunction personalSign<T extends Record<string, unknown>>(\n provider: GalaWalletProvider | BrowserWalletProvider,\n dto: T,\n walletAddress: string,\n methodName?: string,\n): Promise<T & { prefix: string; signature: string }> {\n const prefix = personalSignPrefixFor(dto);\n const payload = { ...dto, prefix };\n // A browser wallet's `personal_sign` applies the EIP-191 header ITSELF, so it must sign the\n // bare DTO; Gala Wallet's `gala_signChainDto` (personal-sign scheme) instead extracts the\n // `prefix` field from what it is handed and prepends it before hashing, so it is handed the\n // prefixed payload. Both submit `{ ...dto, prefix, signature }`.\n const params =\n methodName !== undefined\n ? [serialize(payload), walletAddress, methodName]\n : [serialize(dto), walletAddress];\n\n return provider\n .request({ method: methodName !== undefined ? 'gala_signChainDto' : 'personal_sign', params })\n .then((value) => ({ ...payload, signature: getPersonalSignature(value) }));\n}\n\n/**\n * Signs a DTO via genuine EIP-712 (`eth_signTypedData_v4`) — correctly resolves the `client|`\n * identity, unlike `personal_sign`, for the operations in `EIP712_CAPABLE_METHODS`.\n *\n * Constructs the raw JSON-RPC payload by hand (`{domain, types: {...types, EIP712Domain},\n * primaryType, message}`) rather than depending on ethers.js, matching exactly what\n * `ethers.TypedDataEncoder.getPayload`/`Wallet.signTypedData` produce internally — verified\n * byte-for-byte equivalent (same recovered address from the same signature against both\n * constructions) before this shipped, since gswap-sdk deliberately has no ethers dependency.\n */\nasync function signEIP712<T extends Record<string, unknown>>(\n provider: BrowserWalletProvider,\n methodName: string,\n dto: T,\n walletAddress: string,\n): Promise<T & { types: EIP712Types; domain: EIP712DomainValue; signature: string }> {\n const { completedDto, types } = buildEIP712Payload(methodName, dto);\n // The wallet's LIVE chain id, read on every signature: a user can switch networks after\n // connecting, and a cached or hardcoded id would sign a domain MetaMask itself rejects.\n const domain = eip712DomainFor(await provider.request({ method: 'eth_chainId', params: [] }));\n // The body `prefix` is not part of the EIP-712 `types`, so it is never hashed; it carries the\n // connect-style fixpoint value only to keep the submitted body byte-identical to frontend_v2's.\n const prefix = fixpointPrefixFor(completedDto);\n const message = { ...completedDto, prefix };\n const eip712Domain = [\n { name: 'name', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n ];\n const payload = {\n domain,\n types: { ...types, EIP712Domain: eip712Domain },\n primaryType: methodName,\n message,\n };\n\n const value = await provider.request({\n method: 'eth_signTypedData_v4',\n params: [walletAddress, JSON.stringify(payload)],\n });\n // Key order matches frontend_v2's submitted body: ..., prefix, signature, types, domain.\n return {\n ...(message as T & { prefix: string }),\n signature: getPersonalSignature(value),\n types,\n domain,\n };\n}\n\n/**\n * A GalaChain native signer backed by a secp256k1 private key.\n *\n * Native signing produces the bare GalaChain signature format, without a personal-sign prefix\n * or EIP-712 metadata. The private-key identity is recovered by the chain.\n */\nexport class PrivateKeySigner implements GalaChainSigner {\n private readonly privateKey: Uint8Array;\n\n /**\n * Creates a native signer from a hex or base64 secp256k1 private key.\n *\n * @example\n * ```typescript\n * const signer = new PrivateKeySigner('1'.padStart(64, '0'));\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n */\n constructor(privateKey: string) {\n this.privateKey = normalizePrivateKey(privateKey);\n }\n\n /**\n * Signs the DTO with GalaChain native signing.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * fee: 3000,\n * });\n * ```\n */\n public signObject<T extends Record<string, unknown>>(\n _methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const signature = signNative(this.privateKey, dto);\n return Promise.resolve({ ...dto, signature });\n }\n}\n\n/** Supplies a private key at sign time: a hex/base64 string, possibly fetched asynchronously. */\nexport type PrivateKeyProvider = () => Promise<string> | string;\n\n/** Options for {@link createLazyPrivateKeySigner}. */\nexport interface LazyPrivateKeySignerOptions {\n /**\n * When set, every signature first checks that the fetched key belongs to this account (`0x...`\n * or the Gala `eth|0x...` / `eth|<40 hex>` form, case-insensitive) and refuses to sign otherwise\n * (`SIGNER_ADDRESS_MISMATCH`). Use it when the key lives in a slot another surface can switch\n * between the moment a request was approved and the moment it is signed.\n */\n expectedAddress?: string | undefined;\n}\n\n/**\n * Calls the app's key provider. Whatever it throws or rejects with is the app's own failure to\n * produce a key before anything was signed or sent, so it becomes `KEY_PROVIDER_FAILED` (the\n * original is `cause`); an SDK error is already catalogued and passes through.\n */\nasync function keyFrom(getPrivateKey: PrivateKeyProvider): Promise<unknown> {\n try {\n return await getPrivateKey();\n } catch (cause: unknown) {\n throw isGSwapError(cause) ? cause : new GSwapSDKError('KEY_PROVIDER_FAILED', {}, { cause });\n }\n}\n\n/**\n * Creates the native-signing equivalent of {@link PrivateKeySigner} for apps that must not hold a\n * key in a long-lived object (an extension that reads its session key at sign time).\n *\n * `getPrivateKey` is called once per `signObject` call, never cached, never shared between calls\n * (concurrent signatures each fetch their own key), and the normalized key bytes are zeroed\n * before `signObject` settles, also on failure. A rejection or exception from `getPrivateKey` (the\n * app's \"wallet is locked\", a storage read that failed) is a `KEY_PROVIDER_FAILED` error with the\n * original error as `cause`: nothing has been sent, so `classifyFailure` says `not_sent` and Retry\n * is safe, and the app needs no error class of its own to tell this apart. A provider that returns\n * no usable string (`''`, `undefined`) is `INVALID_PRIVATE_KEY` with `reason: 'no_key_provided'`,\n * classified the same way; any other key that is not a valid secp256k1 key string is an\n * `INVALID_PRIVATE_KEY` error. An SDK error the provider throws itself is passed through.\n * Signatures are byte-identical to `new PrivateKeySigner(key).signObject(...)`.\n *\n * A JavaScript string cannot be wiped; the provider owns the lifetime of the string it returns.\n *\n * @example\n * ```typescript\n * const signer = createLazyPrivateKeySigner(\n * () => SecurityHelper.getSessionSecret(SecurityHelper.SESSION_PRIVATE_KEY_KEY),\n * { expectedAddress: account.address },\n * );\n * const gswap = new GSwap({ signer });\n * ```\n */\nexport function createLazyPrivateKeySigner(\n getPrivateKey: PrivateKeyProvider,\n options: LazyPrivateKeySignerOptions = {},\n): GalaChainSigner {\n const expected = options.expectedAddress;\n const expectedLower =\n expected === undefined ? undefined : normalizeEthereumAccount(expected, true).toLowerCase();\n\n return {\n async signObject<T extends Record<string, unknown>>(\n _methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const provided: unknown = await keyFrom(getPrivateKey);\n if (typeof provided !== 'string' || provided === '') {\n throw new GSwapSDKError('INVALID_PRIVATE_KEY', { reason: 'no_key_provided' });\n }\n const key = normalizePrivateKey(provided);\n try {\n if (expectedLower !== undefined && ethAddressOfPrivateKey(key) !== expectedLower) {\n throw new GSwapSDKError('SIGNER_ADDRESS_MISMATCH', {});\n }\n return { ...dto, signature: signNative(key, dto) };\n } finally {\n key.fill(0);\n }\n },\n };\n}\n\n/**\n * A Gala Wallet signer using native GalaChain signing, with an opt-in personal-sign mode.\n *\n * The selected Ethereum account is passed to Gala Wallet. There is NO automatic fallback: a\n * wallet that rejects `native` surfaces its error to the caller, because the only alternative,\n * `personal-sign`, silently recovers a phantom signer on every released Gala Wallet.\n *\n * `scheme: 'personal-sign'` calls\n * `gala_signChainDto([serialize({ ...dto, prefix }), walletAddress, methodName])` and REQUIRES\n * a wallet build that contains wallet_extension commit 34ca4e4 (strips the embedded `prefix`\n * field and hashes `prefix` + the prefix-less canonical body, the chain's scheme). Wallets\n * released before that fix hash the string with the `prefix` field still inside it and the\n * signature recovers to an address nobody holds, so only opt in once the fixed wallet is\n * released. See SIGNING-PARITY.md.\n */\nexport class GalaWalletSigner implements GalaChainSigner {\n /** The wallet address supplied to Gala Wallet for each signing request. */\n public readonly walletAddress: string;\n\n /** The signing scheme used for every request; it never changes after construction. */\n public readonly scheme: GalaWalletScheme;\n\n /**\n * Creates a Gala Wallet signer.\n *\n * @example\n * ```typescript\n * const signer = new GalaWalletSigner('0x0123456789012345678901234567890123456789');\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n *\n * @param walletAddress - The account passed to Gala Wallet as the signer address. An Ethereum\n * account is `0x` plus 40 hex digits (Gala Wallet's `eth|...` form is normalized to it and held\n * to the same check); a GalaChain id is `client|` plus 24 hex digits, or the bare 24 hex digits\n * frontend_v2 keeps for a direct `client|` login, and is passed through unchanged.\n * @param options - Select native signing (default) or personal-sign explicitly.\n * `'personal-sign'` requires a Gala Wallet build with wallet_extension commit 34ca4e4.\n * `selectAddress` is the identity (`client|...` / `eth|...`) Gala Wallet is switched to with\n * `window.gala.setAddress` before every signature, when the wallet offers it.\n */\n constructor(\n walletAddress: string,\n options: { scheme?: GalaWalletScheme | undefined; selectAddress?: string | undefined } = {},\n ) {\n this.walletAddress = normalizeGalaWalletAccount(walletAddress);\n this.scheme = options.scheme ?? 'native';\n if (options.selectAddress !== undefined) assertWalletIdentity(options.selectAddress);\n this.selectAddress = options.selectAddress;\n }\n\n /** The identity Gala Wallet is switched to before each signature, if one was given. */\n public readonly selectAddress: string | undefined;\n\n /**\n * Signs a DTO through `gala_signChainDto`.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('AddLiquidity', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * tickLower: -60,\n * tickUpper: 60,\n * });\n * ```\n */\n public async signObject<T extends Record<string, unknown>>(\n methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const wallet = getWalletProvider();\n\n return withSelectedIdentity(wallet, this.selectAddress, async () => {\n if (this.scheme === 'personal-sign') {\n return personalSign(wallet, dto, this.walletAddress, methodName);\n }\n const signature = await wallet.request({\n method: 'gala_signChainDto',\n params: [serialize(dto), this.walletAddress, methodName, 'native'],\n });\n return { ...dto, signature: getNativeSignature(signature) };\n });\n }\n}\n\n/**\n * A personal-sign signer for MetaMask and other EIP-1193 browser wallets.\n *\n * The chain recovers this signature using the EIP-191 wrap applied by the wallet to\n * `personal_sign`. This is the browser-wallet path used by the v2 frontend and resolves the\n * bare `eth|` identity.\n */\nexport class BrowserWalletSigner implements GalaChainSigner {\n /**\n * Creates a browser-wallet signer.\n *\n * Defaults to `personal_sign` — unchanged from every existing integration, since it only ever\n * resolves the bare `eth|` identity and changing that silently would be a real behavior\n * break for anyone already depending on it. Pass `{ scheme: 'eip712' }` to correctly resolve\n * a registered `client|` alias instead, for `RequestTrade`/`AddLiquidity`/`RemoveLiquidity`/\n * `CollectPositionFees` (`EIP712_CAPABLE_METHODS`) — `CreatePool` and any other method still\n * falls back to `personal_sign` even in `'eip712'` mode, since its EIP-712 signing is a\n * separate, unsolved chain-side problem.\n *\n * @example\n * ```typescript\n * const signer = new BrowserWalletSigner(window.ethereum, '0x0123456789012345678901234567890123456789');\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n * @example\n * ```typescript\n * // Correctly resolves a registered client| alias instead of the bare eth| address.\n * const signer = new BrowserWalletSigner(window.ethereum, walletAddress, { scheme: 'eip712' });\n * ```\n */\n constructor(\n private readonly provider: BrowserWalletProvider,\n walletAddress: string,\n options: { scheme?: 'personal-sign' | 'eip712' } = {},\n ) {\n this.walletAddress = normalizeEthereumAccount(walletAddress, false);\n this.scheme = options.scheme ?? 'personal-sign';\n }\n\n /** The selected `0x` Ethereum account every signature is requested for. */\n public readonly walletAddress: string;\n private readonly scheme: 'personal-sign' | 'eip712';\n\n /**\n * Signs the DTO with `eth_signTypedData_v4` (when constructed with `{ scheme: 'eip712' }` and\n * `methodName` is in `EIP712_CAPABLE_METHODS`) or the EIP-1193 `personal_sign` method\n * (otherwise — the default).\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * fee: 3000,\n * });\n * ```\n */\n public signObject<T extends Record<string, unknown>>(\n methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n if (this.scheme === 'eip712' && EIP712_CAPABLE_METHODS.has(methodName)) {\n return signEIP712(this.provider, methodName, dto, this.walletAddress);\n }\n return personalSign(this.provider, dto, this.walletAddress);\n }\n}\n"],"mappings":"8aAiFA,SAAS,GAAwC,CAE/C,IAAM,EAASA,WAAa,QAAQ,KACpC,GAAI,CAAC,EACH,MAAM,IAAI,EAAc,4BAA6B,CAAC,CAAC,EAEzD,OAAO,CACT,CAEA,SAAS,EAAmB,EAAwB,CAMlD,GALI,OAAO,GAAU,UAKjB,CAAC,6BAA6B,KAAK,CAAK,EAC1C,MAAM,IAAI,EAAc,oBAAqB,CAAE,OAAQ,QAAS,CAAC,EAEnE,OAAO,CACT,CAEA,SAAS,EAAqB,EAAwB,CACpD,GAAI,OAAO,GAAU,UAAY,CAAC,6BAA6B,KAAK,CAAK,EACvE,MAAM,IAAI,EAAc,oBAAqB,CAAE,OAAQ,eAAgB,CAAC,EAE1E,OAAO,CACT,CAcA,SAAgB,EAAyB,EAAqC,CAC5E,IAAM,EAAQ,0CAA0C,KAAK,CAAO,EACpE,OAAO,IAAQ,KAAO,IAAA,GAAY,IAAA,GAAY,KAAK,EAAM,IAC3D,CAEA,SAAS,EAAyB,EAAiB,EAAkC,CACnF,IAAM,EAAa,EAAmB,EAAyB,CAAO,GA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,gBAAA,IAAA,EAAA,EACC,EAAA,KAAA,SAAA,IAAA,EAAA,EANf,KAAK,cAAgB,EAAyB,EAAe,EAAK,EAClE,KAAK,OAAS,EAAQ,QAAU,eAClC,CAoBA,WACE,EACA,EACuB,CAIvB,OAHI,KAAK,SAAW,UAAY,EAAuB,IAAI,CAAU,EAC5D,EAAW,KAAK,SAAU,EAAY,EAAK,KAAK,aAAa,EAE/D,EAAa,KAAK,SAAU,EAAK,KAAK,aAAa,CAC5D,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{GSwapSDKError as e}from"../classes/gswap_sdk_error.js";function t(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function n(e){return t(e)&&typeof e.status==`number`}function r(e,n){if(!t(e))return null;let r=e.get;if(typeof r==`function`){let t=r.call(e,n);return typeof t==`string`?t:null}let i=Object.entries(e).find(([e])=>e.toLowerCase()===n.toLowerCase());return typeof i?.[1]==`string`?i[1]:null}function i(t,i){if(!n(t))throw new e(`TRANSPORT_ERROR`,{url:i},{url:i});let{status:a,data:o,headers:s}=t;return{ok:a>=200&&a<300,status:a,json:()=>Promise.resolve(o),text:()=>Promise.resolve(typeof o==`string`?o:JSON.stringify(o)),headers:{get:e=>r(s,e)}}}function a(e,t){let n=new Set(t.map(e=>e.toLowerCase())),r=e?.headers,i=r===void 0?[]:r instanceof Headers?[...r.entries()]:Array.isArray(r)?r.map(([e,t])=>[String(e),String(t)]):Object.entries(r).map(([e,t])=>[e,String(t)]);return Object.fromEntries(i.filter(([e])=>!n.has(e.toLowerCase())))}function o(t,n){let r=n.omitHeaders??[`content-type`];return async(o,c)=>{let l=c?.signal??void 0,u={headers:a(c,r),...l?{signal:l}:{},...n.rejectOnHttpError?{}:{validateStatus:()=>!0}},d=(c?.method??`GET`).toUpperCase()===`POST`,f=d&&typeof c?.body==`string`?JSON.parse(c.body):void 0,p;try{p=await(d?t.post(o,f,u):t.get(o,u))}catch(t){throw l?.aborted===!0||!s(t,n.rejectOnHttpError)?t:new e(`TRANSPORT_ERROR`,{url:o},{url:o,cause:t})}return i(p,o)}}function s(e,n){return!n||t(e)&&e.isAxiosError===!0&&e.response===void 0}export{o as httpRequestorFromAxios};
|
|
2
|
-
//# sourceMappingURL=axios_requestor.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"axios_requestor.js","names":[],"sources":["../../../src/utils/axios_requestor.ts"],"sourcesContent":["import { GSwapSDKError } from '../classes/gswap_sdk_error.js';\nimport type { HttpRequestor, HTTPResponse } from '../types/http_requestor.js';\n\n/** What the adapter reads of an axios response. */\nexport interface AxiosLikeResponse {\n status: number;\n data?: unknown;\n /** axios' `AxiosHeaders` (has `get`) or a plain header record. */\n headers?: unknown;\n}\n\n/** The request config the adapter hands to axios. */\nexport interface AxiosLikeConfig {\n headers: Record<string, string>;\n signal?: AbortSignal;\n validateStatus?: () => boolean;\n}\n\n/**\n * The part of an axios instance the adapter calls. Declared structurally, so the SDK takes no\n * dependency on axios and any axios instance (with its interceptors) satisfies it.\n */\nexport interface AxiosLikeInstance {\n get(url: string, config?: AxiosLikeConfig): Promise<unknown>;\n post(url: string, data?: unknown, config?: AxiosLikeConfig): Promise<unknown>;\n}\n\n/** Options of {@link httpRequestorFromAxios}. */\nexport interface AxiosRequestorOptions {\n /**\n * `true`: leave axios' default status validation alone, so a 4xx/5xx REJECTS through the\n * instance's own interceptors and the SDK rethrows what the app's error handling produced.\n * `false`: every HTTP status resolves, so the SDK classifies it itself (shadow submits,\n * apply-results reads); transport failures still reject.\n */\n rejectOnHttpError: boolean;\n /**\n * Request headers NOT to hand to axios, matched case-insensitively. Default `['content-type']`:\n * axios derives `Content-Type: application/json` from the object body it is given, and an\n * interceptor may set its own, so the SDK's copy would only be a second opinion.\n */\n omitHeaders?: readonly string[] | undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * An axios interceptor may resolve something that is not a response at all (for example a string\n * for ECONNREFUSED). That is a transport failure, not an HTTP answer.\n */\nfunction isAxiosLikeResponse(value: unknown): value is AxiosLikeResponse {\n return isRecord(value) && typeof value['status'] === 'number';\n}\n\nfunction readAxiosHeader(headers: unknown, name: string): string | null {\n if (!isRecord(headers)) return null;\n const getter = headers['get'];\n if (typeof getter === 'function') {\n const value: unknown = getter.call(headers, name);\n return typeof value === 'string' ? value : null;\n }\n const match = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase());\n return typeof match?.[1] === 'string' ? match[1] : null;\n}\n\nfunction toHttpResponse(answer: unknown, url: string): HTTPResponse {\n if (!isAxiosLikeResponse(answer)) {\n throw new GSwapSDKError('TRANSPORT_ERROR', { url }, { url });\n }\n const { status, data, headers } = answer;\n return {\n ok: status >= 200 && status < 300,\n status,\n json: () => Promise.resolve(data),\n text: () => Promise.resolve(typeof data === 'string' ? data : JSON.stringify(data)),\n headers: { get: (name: string) => readAxiosHeader(headers, name) },\n };\n}\n\nfunction headersFor(\n init: RequestInit | undefined,\n omit: readonly string[],\n): Record<string, string> {\n const omitted = new Set(omit.map((name) => name.toLowerCase()));\n const raw = init?.headers;\n const entries: Array<[string, string]> =\n raw === undefined\n ? []\n : raw instanceof Headers\n ? [...raw.entries()]\n : Array.isArray(raw)\n ? raw.map(([name, value]): [string, string] => [String(name), String(value)])\n : Object.entries(raw).map(([name, value]): [string, string] => [name, String(value)]);\n return Object.fromEntries(entries.filter(([name]) => !omitted.has(name.toLowerCase())));\n}\n\n/**\n * An SDK {@link HttpRequestor} over an axios instance, so the SDK's requests travel through the\n * app's own base URL, interceptors and error handling.\n *\n * A POST's string body is parsed back to the object the SDK serialized it from (axios serializes\n * again, and an interceptor may read the object); a GET goes through `instance.get`. The answer\n * is an HTTP response whose `json()`/`text()` read `response.data`. An answer that is not an\n * axios response is a `TRANSPORT_ERROR` rejection, and so is a rejection that means no HTTP\n * answer arrived (the original error is `cause`): any rejection with `rejectOnHttpError: false`\n * (every status resolves there), an axios error without a `response` with `true`. Any other\n * rejection (an interceptor's error for a 4xx, say) is rethrown unchanged, and so is an abort.\n *\n * Pair it with `ChainGateway`'s `dexBackendBaseUrl: ''` when the instance owns the base URL.\n *\n * @example\n * ```ts\n * const submitGateway = new ChainGateway({\n * dexBackendBaseUrl: '',\n * httpRequestor: httpRequestorFromAxios(chainGatewayInstance, { rejectOnHttpError: true }),\n * });\n * ```\n */\nexport function httpRequestorFromAxios(\n instance: AxiosLikeInstance,\n options: AxiosRequestorOptions,\n): HttpRequestor {\n const omit = options.omitHeaders ?? ['content-type'];\n return async (uri, init) => {\n const signal = init?.signal ?? undefined;\n const config: AxiosLikeConfig = {\n headers: headersFor(init, omit),\n ...(signal ? { signal } : {}),\n ...(options.rejectOnHttpError ? {} : { validateStatus: () => true }),\n };\n const isPost = (init?.method ?? 'GET').toUpperCase() === 'POST';\n const body: unknown =\n isPost && typeof init?.body === 'string' ? JSON.parse(init.body) : undefined;\n let answer: unknown;\n try {\n answer = await (isPost ? instance.post(uri, body, config) : instance.get(uri, config));\n } catch (error: unknown) {\n // An abort is the caller's or the SDK's timeout, and the request layer knows which.\n if (signal?.aborted === true || !isTransportRejection(error, options.rejectOnHttpError)) {\n throw error;\n }\n throw new GSwapSDKError('TRANSPORT_ERROR', { url: uri }, { url: uri, cause: error });\n }\n return toHttpResponse(answer, uri);\n };\n}\n\n/**\n * Whether an axios rejection means no HTTP answer arrived. With `rejectOnHttpError: false` every\n * status resolves, so any rejection is one. With `true`, a 4xx/5xx rejects too, so only an axios\n * error that carries no `response` is (an interceptor's own error is an app answer and passes\n * through; an app whose interceptors turn network errors into their own class names it in\n * `ChainGatewayOptions.isTransportFailure`).\n */\nfunction isTransportRejection(error: unknown, rejectOnHttpError: boolean): boolean {\n if (!rejectOnHttpError) return true;\n return isRecord(error) && error['isAxiosError'] === true && error['response'] === undefined;\n}\n"],"mappings":"8DA4CA,SAAS,EAAS,EAAkD,CAClE,OAAO,OAAO,GAAU,YAAY,GAAkB,C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AC,KAAK,CAAC,EAAM,KAA6B,CAAC,EAAM,OAAO,CAAK,CAAC,CAAC,EAC5F,OAAO,OAAO,YAAY,EAAQ,QAAQ,CAAC,KAAU,CAAC,EAAQ,IAAI,EAAK,YAAY,CAAC,CAAC,CAAC,CACxF,CAwBA,SAAgB,EACd,EACA,EACe,CACf,IAAM,EAAO,EAAQ,aAAe,CAAC,cAAc,EACnD,OAAO,MAAO,EAAK,IAAS,CAC1B,IAAM,EAAS,GAAM,QAAU,IAAA,GACzB,EAA0B,CAC9B,QAAS,EAAW,EAAM,CAAI,EAC9B,GAAI,EAAS,CAAE,QAAO,EAAI,CAAC,EAC3B,GAAI,EAAQ,kBAAoB,CAAC,EAAI,CAAE,mBAAsB,EAAK,CACpE,EACM,GAAU,GAAM,QAAU,MAAA,CAAO,YAAY,IAAM,OACnD,EACJ,GAAU,OAAO,GAAM,MAAS,SAAW,KAAK,MAAM,EAAK,IAAI,EAAI,IAAA,GACjE,EACJ,GAAI,CACF,EAAS,MAAO,EAAS,EAAS,KAAK,EAAK,EAAM,CAAM,EAAI,EAAS,IAAI,EAAK,CAAM,EACtF,OAAS,EAAgB,CAKvB,MAHI,GAAQ,UAAY,IAAQ,CAAC,EAAqB,EAAO,EAAQ,iBAAiB,EAC9E,EAEF,IAAI,EAAc,kBAAmB,CAAE,IAAK,CAAI,EAAG,CAAE,IAAK,EAAK,MAAO,CAAM,CAAC,CACrF,CACA,OAAO,EAAe,EAAQ,CAAG,CACnC,CACF,CASA,SAAS,EAAqB,EAAgB,EAAqC,CAEjF,MADA,CAAK,GACE,EAAS,CAAK,GAAK,EAAM,eAAoB,IAAQ,EAAM,WAAgB,IAAA,EACpF"}
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{GSwapSDKError as e}from"../classes/gswap_sdk_error.js";import{normalizePrivateKey as t,serialize as n,signPersonalMessage as r,signSerializedNative as i}from"./signing.js";import a from"bignumber.js";function o(e,n){let r=t(e);try{return n(r)}finally{r.fill(0)}}function s(e,t){return o(e,e=>i(e,t))}function c(e,t,n){return o(e,e=>r(e,t,n))}const l=/^(?:0|[1-9][0-9]*)$/u;function u(e){return e.startsWith(`Ethereum Signed Message:
|
|
2
|
-
`)&&l.test(e.slice(26))}const d=[`signature`,`multisig`,`trace`,`types`,`domain`,`stringsInstructions`];function f(t){let r;try{r=JSON.parse(t)}catch{throw new e(`PERSONAL_SIGN_NOT_JSON`,{})}if(typeof r!=`object`||!r||Array.isArray(r))throw new e(`PERSONAL_SIGN_NOT_OBJECT`,{});let i=r;if(!Object.prototype.hasOwnProperty.call(i,`prefix`))return{prefix:``,message:t};let{prefix:a,...o}=i;if(typeof a!=`string`||!u(a))throw new e(`PERSONAL_SIGN_BAD_PREFIX`,{});let s=d.filter(e=>Object.prototype.hasOwnProperty.call(o,e));if(s.length>0)throw new e(`PERSONAL_SIGN_ENVELOPE_FIELDS`,{fields:s.join(`, `)});if(n(i)!==t)throw new e(`PERSONAL_SIGN_NOT_CANONICAL`,{});return{prefix:a,message:n(o)}}function p(e,t){let{prefix:n,message:r}=f(t);return c(e,n,r)}function m(e,t){let r={...t};return delete r.signature,{signature:s(e,n(r)),...r}}function h(e){let t={};for(let n of Object.keys(e))n!==`EIP712Domain`&&(t[n]=e[n]);return t}function g(e){let t=t=>{let n=e?.[t];return typeof n==`string`?n:``};return`${t(`collection`)}$${t(`category`)}$${t(`type`)}$${t(`additionalKey`)}`}function _(t){let n=new a(NaN);try{n=new a(t)}catch{}if(!n.isFinite())throw new e(`INVALID_DECIMAL`,{value:String(t)});return n.toFixed()}export{_ as canonicalDecimalString,f as resolvePersonalSignChainDtoPayload,c as signChainDtoHash,s as signChainDtoNative,p as signChainDtoPersonalSign,m as signRawObject,h as stripEip712DomainType,g as tokenClassDollarKey,o as withPrivateKey};
|
|
3
|
-
//# sourceMappingURL=chain_dto_signing.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"chain_dto_signing.js","names":[],"sources":["../../../src/utils/chain_dto_signing.ts"],"sourcesContent":["/**\n * String-key signing entry points for apps that hold a private key only briefly (the Gala Wallet\n * extension reads its session key at sign time and must not keep it in a long-lived object).\n *\n * These are thin, byte-exact ports of the functions the wallet shipped in\n * `wallet_extension/src/helpers/wallet/signing.ts` (including the fail-closed personal-sign\n * payload resolver from its commit 34ca4e4), re-expressed over the SDK's own primitives. Every\n * function takes the key as a string (`0x`-optional hex, or base64) or as bytes, normalizes it per\n * call, and zeroes the normalized copy before returning, so nothing in this module retains a key.\n * A JavaScript string cannot be wiped; the caller owns the lifetime of the string it passes in.\n */\nimport BigNumber from 'bignumber.js';\nimport { GSwapSDKError } from '../classes/gswap_sdk_error.js';\nimport {\n normalizePrivateKey,\n serialize,\n signPersonalMessage,\n signSerializedNative,\n} from './signing.js';\n\n/** A secp256k1 private key as a hex/base64 string or as raw 32 bytes. */\nexport type PrivateKeyInput = string | Uint8Array;\n\n/**\n * Runs `action` with a private normalized copy of the key, zeroed afterwards (also when `action`\n * throws). Bytes given by the caller are copied, never modified: the caller owns them.\n */\nexport function withPrivateKey<T>(privateKey: PrivateKeyInput, action: (key: Uint8Array) => T): T {\n const key = normalizePrivateKey(privateKey);\n try {\n return action(key);\n } finally {\n key.fill(0);\n }\n}\n\n/**\n * GalaChain NATIVE signature over an already-serialized DTO: keccak256 of the exact bytes with no\n * prefix and no envelope (wallet `signChainDtoNative`). The caller owns serialization, so the\n * bytes a user reviewed and the bytes signed cannot diverge.\n *\n * @returns 130 lowercase hex characters, `r || s || v` with `v` = `1b`/`1c`, no `0x`.\n */\nexport function signChainDtoNative(privateKey: PrivateKeyInput, serializedDto: string): string {\n return withPrivateKey(privateKey, (key) => signSerializedNative(key, serializedDto));\n}\n\n/**\n * The personal-sign hash primitive (wallet `signChainDtoHash`): keccak256(`prefix` + `message`),\n * both verbatim, with no further EIP-191 wrap. `message` must be the DTO's serialization WITHOUT\n * its `prefix` field; callers holding a dApp-supplied string go through `signChainDtoPersonalSign`,\n * which derives both inputs from it.\n */\nexport function signChainDtoHash(\n privateKey: PrivateKeyInput,\n prefix: string,\n message: string,\n): string {\n return withPrivateKey(privateKey, (key) => signPersonalMessage(key, prefix, message));\n}\n\nconst PERSONAL_SIGN_HEADER = String.fromCharCode(0x19) + 'Ethereum Signed Message:\\n';\nconst PERSONAL_SIGN_LENGTH_PATTERN = /^(?:0|[1-9][0-9]*)$/u;\n\n// A header with a body starting `{` can never collide with another EIP-191 message's hash, and\n// anything that is not a header (arbitrary bytes the user cannot see on an approval card) is\n// refused. The number is NOT required to equal the byte length: the chain hashes whatever prefix\n// the submitted DTO carries, and defi-backend's bouncer rejects a mismatched header loudly.\nfunction isPersonalSignHeader(prefix: string): boolean {\n return (\n prefix.startsWith(PERSONAL_SIGN_HEADER) &&\n PERSONAL_SIGN_LENGTH_PATTERN.test(prefix.slice(PERSONAL_SIGN_HEADER.length))\n );\n}\n\n/**\n * Top-level fields that would make the chain (`getPayloadToSign`) or defi-backend's personal-sign\n * verifier hash something other than `prefix + serialize(dto minus prefix)`. An unsigned DTO from\n * a dApp never legitimately carries any of them, so they fail closed. Order is part of the error\n * message the wallet shows its user.\n */\nconst PERSONAL_SIGN_FORBIDDEN_FIELDS = [\n 'signature',\n 'multisig',\n 'trace',\n 'types',\n 'domain',\n 'stringsInstructions',\n] as const;\n\n/** What a `gala_signChainDto` personal-sign request hashes. */\nexport interface PersonalSignChainDtoPayload {\n /** The `prefix` the chain prepends: the DTO's own `prefix` field, or `''` when it has none. */\n prefix: string;\n /** The exact message hashed after `prefix`. */\n message: string;\n}\n\n/**\n * Derives what to hash for a `gala_signChainDto` personal-sign request from the exact string the\n * dApp sent (and the approval card displayed): wallet `resolvePersonalSignChainDtoPayload`.\n *\n * The dApp submits `{ ...dto, prefix, signature }`, which the chain recovers from\n * `keccak256(prefix + serialize(dto WITHOUT prefix))`. So when the string embeds a `prefix`\n * field, that field is removed and the remainder re-serialized; the prefix used is the dApp's own\n * value byte for byte. A string with no `prefix` field is hashed verbatim with an empty prefix\n * (chain-equivalent to a native signature of that exact string).\n *\n * Fails closed (throws `GSwapSDKError` `PERSONAL_SIGN_NOT_JSON`, `PERSONAL_SIGN_NOT_OBJECT`,\n * `PERSONAL_SIGN_BAD_PREFIX`, `PERSONAL_SIGN_ENVELOPE_FIELDS` or `PERSONAL_SIGN_NOT_CANONICAL`) on:\n * malformed JSON; JSON that is not a plain object; a `prefix` that is not an EIP-191\n * \"Ethereum Signed Message\" header; any signing-envelope field (`signature`, `multisig`, `trace`,\n * `types`, `domain`, `stringsInstructions`); and a string that is not already the canonical\n * serialization of what it parses to (duplicate keys, lossy numbers, key-order tricks the card\n * would render differently). Stripping `prefix` is therefore the ONLY byte change between the\n * reviewed string and the signed message.\n */\nexport function resolvePersonalSignChainDtoPayload(data: string): PersonalSignChainDtoPayload {\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch {\n throw new GSwapSDKError('PERSONAL_SIGN_NOT_JSON', {});\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new GSwapSDKError('PERSONAL_SIGN_NOT_OBJECT', {});\n }\n const dto = parsed as Record<string, unknown>;\n if (!Object.prototype.hasOwnProperty.call(dto, 'prefix')) {\n return { prefix: '', message: data };\n }\n\n const { prefix, ...withoutPrefix } = dto;\n if (typeof prefix !== 'string' || !isPersonalSignHeader(prefix)) {\n throw new GSwapSDKError('PERSONAL_SIGN_BAD_PREFIX', {});\n }\n const forbidden = PERSONAL_SIGN_FORBIDDEN_FIELDS.filter((field) =>\n Object.prototype.hasOwnProperty.call(withoutPrefix, field),\n );\n if (forbidden.length > 0) {\n throw new GSwapSDKError('PERSONAL_SIGN_ENVELOPE_FIELDS', { fields: forbidden.join(', ') });\n }\n if (serialize(dto) !== data) {\n throw new GSwapSDKError('PERSONAL_SIGN_NOT_CANONICAL', {});\n }\n return { prefix, message: serialize(withoutPrefix) };\n}\n\n/**\n * Signs a GalaChain personal-sign scheme DTO from the exact string a dApp sent through\n * `gala_signChainDto` (wallet `signChainDtoPersonalSign`). See\n * `resolvePersonalSignChainDtoPayload` for what is signed and what is refused; the signature\n * recovers, under the chain's `getPayloadToSign`, to this key for the DTO the dApp submits with\n * its `prefix`, and equals a `personal_sign` of the bare body when that prefix is the EIP-191\n * header of the bare body's byte length.\n *\n * @throws GSwapSDKError (`PERSONAL_SIGN_*`, see `resolvePersonalSignChainDtoPayload`) before any\n * signing when the input is refused.\n */\nexport function signChainDtoPersonalSign(privateKey: PrivateKeyInput, data: string): string {\n const { prefix, message } = resolvePersonalSignChainDtoPayload(data);\n return signChainDtoHash(privateKey, prefix, message);\n}\n\n/**\n * Raw object signing (wallet `signObject`), used for transfers, bridge and fee-dry-run DTOs the\n * wallet signs itself. Removes ONLY `signature`, signs `keccak256(serialize(rest))` natively\n * (no `prefix` handling, and `trace` / `multisig` stay in the signed bytes, unlike\n * `signNative`), and returns `{ signature, ...rest }` with the signature as the FIRST key, exactly\n * like the wallet. Callers that must not sign extra fields strip them first.\n */\nexport function signRawObject(\n privateKey: PrivateKeyInput,\n obj: Record<string, unknown>,\n): { signature: string } & Record<string, unknown> {\n const rest = { ...obj };\n delete rest['signature'];\n return {\n signature: signChainDtoNative(privateKey, serialize(rest)),\n ...rest,\n };\n}\n\n/**\n * Drops the `EIP712Domain` entry from a dApp-supplied types map (a typed-data encoder derives the\n * domain type itself and rejects an explicit one). The order of the remaining types is preserved.\n */\nexport function stripEip712DomainType<T>(types: Record<string, T>): Record<string, T> {\n const stripped: Record<string, T> = {};\n for (const typeName of Object.keys(types)) {\n if (typeName !== 'EIP712Domain') stripped[typeName] = types[typeName] as T;\n }\n return stripped;\n}\n\n/**\n * `collection$category$type$additionalKey` for a token-class object (wallet `decodeTokenData`).\n * Lenient on purpose: any missing or non-string part becomes `''`, so a display layer never\n * throws on odd input.\n */\nexport function tokenClassDollarKey(token: Record<string, unknown> | null | undefined): string {\n const part = (field: string): string => {\n const value = token?.[field];\n return typeof value === 'string' ? value : '';\n };\n return `${part('collection')}$${part('category')}$${part('type')}$${part('additionalKey')}`;\n}\n\n/**\n * A quantity in the form GalaChain's `IsBigNumber` validator accepts: FIXED notation, no leading\n * zeros, no trailing decimal zeros (`BigNumber#toFixed()`; never `toString()`, which turns\n * `0.00000001` into `1e-8`, and never a JS number in between).\n *\n * @throws GSwapSDKError (`INVALID_DECIMAL`) for a value that is not a finite number. The wallet's\n * `cleanNumber` returned the string `'NaN'` there; signing that text can only fail on chain.\n */\nexport function canonicalDecimalString(value: string | number): string {\n let parsed = new BigNumber(Number.NaN);\n try {\n parsed = new BigNumber(value);\n } catch {\n // BigNumber throws instead of returning NaN when its DEBUG flag is on; both mean \"invalid\".\n }\n if (!parsed.isFinite()) {\n throw new GSwapSDKError('INVALID_DECIMAL', { value: String(value) });\n }\n return parsed.toFixed();\n}\n"],"mappings":"+MA2BA,SAAgB,EAAkB,EAA6B,EAAmC,CAChG,IAAM,EAAM,EAAoB,CAAU,EAC1C,GAAI,CACF,OAAO,EAAO,CAAG,CACnB,QAAU,CACR,EAAI,KAAK,CAAC,CACZ,CACF,CASA,SAAgB,EAAmB,EAA6B,EAA+B,CAC7F,OAAO,EAAe,EAAa,GAAQ,EAAqB,EAAK,CAAa,CAAC,CACrF,CAQA,SAAgB,EACd,EACA,EACA,EACQ,CACR,OAAO,EAAe,EAAa,GAAQ,EAAoB,EAAK,EAAQ,CAAO,CAAC,CACtF,CAEA,MACM,EAA+B,uBAMrC,SAAS,EAAqB,EAAyB,CACrD,OACE,EAAO,WAAW;CAAoB,GACtC,EAA6B,KAAK,EAAO,MAAM,EAA2B,CAAC,CAE/E,CAQA,MAAM,EAAiC,CACrC,YACA,WACA,QACA,QACA,SACA,qBACF,EA6BA,SAAgB,EAAmC,EAA2C,CAC5F,IAAI,EACJ,GAAI,CACF,EAAS,KAAK,MAAM,CAAI,CAC1B,MAAQ,CACN,MAAM,IAAI,EAAc,yBAA0B,CAAC,CAAC,CACtD,CACA,GAAuB,OAAO,GAAW,WAArC,GAAiD,MAAM,QAAQ,C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GAAG,EAAK,MAAM,EAAE,GAAG,EAAK,eAAe,GAC1F,CAUA,SAAgB,EAAuB,EAAgC,CACrE,IAAI,EAAS,IAAI,EAAU,GAAU,EACrC,GAAI,CACF,EAAS,IAAI,EAAU,CAAK,CAC9B,MAAQ,CAER,CACA,GAAI,CAAC,EAAO,SAAS,EACnB,MAAM,IAAI,EAAc,kBAAmB,CAAE,MAAO,OAAO,CAAK,CAAE,CAAC,EAErE,OAAO,EAAO,QAAQ,CACxB"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function e(e){return[e.collection,e.category,e.type,e.additionalKey].join(`$`)}function t(e,t){let n=e.split(t),r=n.slice(-3),i=n.slice(0,-3).join(t);if(n.length<4||i.length===0||r.some(e=>e.length===0))return;let[a,o,s]=r;return{collection:i,category:a,type:o,additionalKey:s}}function n(e){if(typeof e==`string`)return t(e,e.includes(`|`)?`|`:`$`);if(typeof e==`object`&&e)try{let{collection:t,category:n,type:r,additionalKey:i}=e;return typeof t!=`string`||typeof n!=`string`||typeof r!=`string`||typeof i!=`string`||t===``||n===``||r===``||i===``?void 0:{collection:t,category:n,type:r,additionalKey:i}}catch{return}}function r(e){return typeof e==`string`?t(e,`$`):void 0}export{e as compositeKeyOf,t as splitClassKey,r as tryParseCompositeKey,n as tryParseTokenClassKey};
|
|
2
|
-
//# sourceMappingURL=class_key.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"class_key.js","names":[],"sources":["../../../src/utils/class_key.ts"],"sourcesContent":["import type { GalaChainTokenClassKey } from '../types/token.js';\n\n/**\n * Token class keys that never throw: the `$`-joined composite key and the non-throwing parsers.\n * This module imports nothing at run time (the key type is erased), so an app shell that reads a\n * stored key pays for a few hundred bytes, never for the error class or the catalog. The parser\n * that THROWS an SDK error on a bad key (`parseTokenClassKey`) lives in `ordering.ts`.\n */\n\n/** Return the `$`-joined composite key used by GalaChain object identities. */\nexport function compositeKeyOf(token: GalaChainTokenClassKey): string {\n return [token.collection, token.category, token.type, token.additionalKey].join('$');\n}\n\n/**\n * Splits `collection<d>category<d>type<d>additionalKey` from the right, or `undefined` when there\n * are fewer than four segments or any of the four is empty. The one place the split is written;\n * the strict `parseTokenClassKey` calls it too.\n *\n * The LAST three segments are always `category`, `type` and `additionalKey`; everything before\n * them is the `collection`. Parsing from the right is required because real collections contain\n * the `$` delimiter themselves (for example `$GMUSIC`), so a plain left-to-right `split('$')`\n * shifts every field.\n */\nexport function splitClassKey(\n key: string,\n delimiter: '|' | '$',\n): GalaChainTokenClassKey | undefined {\n const segments = key.split(delimiter);\n const tail = segments.slice(-3);\n const collection = segments.slice(0, -3).join(delimiter);\n if (segments.length < 4 || collection.length === 0 || tail.some((part) => part.length === 0)) {\n return undefined;\n }\n const [category, type, additionalKey] = tail;\n return {\n collection,\n category: category as string,\n type: type as string,\n additionalKey: additionalKey as string,\n };\n}\n\n/**\n * The non-throwing `parseTokenClassKey`: the class key, or `undefined` when `value` is not\n * one. A string is split exactly as `parseTokenClassKey` splits it (`|` form when it contains a\n * `|`, else `$`, from the right, all four parts non-empty). Unlike `parseTokenClassKey`, an\n * object is VALIDATED, not just copied: all four fields must be non-empty strings. Anything else\n * (`undefined`, `null`, a number, an array) is `undefined`, so it is safe on untrusted input (a\n * stored token, a URL parameter, a wallet row) without a `try`/`catch`.\n *\n * Use {@link tryParseCompositeKey} instead when only the `$` form is valid input.\n *\n * @example\n * ```ts\n * const key = tryParseTokenClassKey(row.compositeKey);\n * if (key === undefined) return failClosed(); // no class is known: never invent one from a symbol\n * ```\n */\nexport function tryParseTokenClassKey(value: unknown): GalaChainTokenClassKey | undefined {\n if (typeof value === 'string') return splitClassKey(value, value.includes('|') ? '|' : '$');\n if (typeof value !== 'object' || value === null) return undefined;\n try {\n const { collection, category, type, additionalKey } = value as Record<string, unknown>;\n if (\n typeof collection !== 'string' ||\n typeof category !== 'string' ||\n typeof type !== 'string' ||\n typeof additionalKey !== 'string' ||\n collection === '' ||\n category === '' ||\n type === '' ||\n additionalKey === ''\n ) {\n return undefined;\n }\n return { collection, category, type, additionalKey };\n } catch {\n // A getter or proxy that throws is not a token class key.\n return undefined;\n }\n}\n\n/**\n * Parses a `$`-joined composite key (`Collection$Category$Type$AdditionalKey`, what\n * {@link compositeKeyOf} writes) and nothing else, or `undefined`. It is {@link tryParseTokenClassKey}\n * for a string that may ONLY be in the `$` form: a key that contains `|` is NOT read as the pipe\n * form here (it stays part of a segment), and only a string is accepted. The split is from the\n * right, so a collection that itself contains `$` (production's `$GMUSIC`, stage's\n * `$GMUSIC_TEST1`) stays whole; `'GALA'`, `'GALA$Unit$none'`, `'ETIME$$$'`, `'GALA$Unit$none$'` and\n * `'$$$$'` are `undefined`.\n *\n * It replaces an app's own `parseCompositeKey(key): Components | null` (`?? null`), which had\n * exactly these semantics.\n *\n * @example\n * ```ts\n * tryParseCompositeKey('$GMUSIC_TEST1$Unit$none$none')?.collection; // '$GMUSIC_TEST1'\n * tryParseCompositeKey('GALA$Unit$none'); // undefined\n * ```\n */\nexport function tryParseCompositeKey(value: unknown): GalaChainTokenClassKey | undefined {\n return typeof value === 'string' ? splitClassKey(value, '$') : undefined;\n}\n"],"mappings":"AAUA,SAAgB,EAAe,EAAuC,CACpE,MAAO,CAAC,EAAM,WAAY,EAAM,SAAU,EAAM,KAAM,EAAM,aAAa,CAAC,CAAC,KAAK,GAAG,CACrF,CAYA,SAAgB,EACd,EACA,EACoC,CACpC,IAAM,EAAW,EAAI,MAAM,CAAS,EAC9B,EAAO,EAAS,MAAM,EAAE,EACxB,EAAa,EAAS,MAAM,EAAG,EAAE,CAAC,CAAC,KAAK,CAAS,EACvD,GAAI,EAAS,OAAS,GAAK,EAAW,SAAW,GAAK,EAAK,KAAM,GAAS,EAAK,SAAW,CAAC,EACzF,OAEF,GAAM,CAAC,EAAU,EAAM,GAAiB,EACxC,MAAO,CACL,aACU,WACJ,OACS,eACjB,CACF,CAkBA,SAAgB,EAAsB,EAAoD,CACxF,GAAI,OAAO,GAAU,SAAU,OAAO,EAAc,EAAO,EAAM,SAAS,GAAG,EAAI,IAAM,GAAG,EAC1F,GAAI,OAAO,GAAU,UAAY,EACjC,GAAI,CACF,GAAM,CAAE,aAAY,WAAU,OAAM,iBAAkB,EAatD,OAXE,OAAO,GAAe,UACtB,OAAO,GAAa,UACpB,OAAO,GAAS,UAChB,OAAO,GAAkB,UACzB,IAAe,IACf,IAAa,IACb,IAAS,IACT,IAAkB,GAElB,OAEK,CAAE,aAAY,WAAU,OAAM,eAAc,CACrD,MAAQ,CAEN,MACF,CACF,CAoBA,SAAgB,EAAqB,EAAoD,CACvF,OAAO,OAAO,GAAU,SAAW,EAAc,EAAO,GAAG,EAAI,IAAA,EACjE"}
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{GSwapSDKError as e}from"../classes/gswap_sdk_error.js";function t(t,n){let r={};r[t]=[];function i(e){let t=r[e];
|
|
2
|
-
/* c8 ignore next */
|
|
3
|
-
if(!t)throw Error(`Missing EIP-712 type definition for ${e}`);return t}function a(t,n,o,s=!1){if(Array.isArray(n)){let e=n.length>0?a(t,n[0],o,!0):`string`;s||i(o).push({name:t,type:(e??t)+`[]`})}else if(typeof n==`object`&&n){if(r[t])throw new e(`EIP712_NAME_COLLISION`,{name:t});r[t]=[],Object.entries(n).forEach(([e,n])=>{a(e,n,t)}),s||i(o).push({name:t,type:t})}else{let r;switch(typeof n){case`string`:r=`string`;break;case`number`:r=`int256`;break;case`boolean`:r=`bool`;break;case`bigint`:case`symbol`:case`undefined`:case`function`:case`object`:throw new e(`EIP712_UNSUPPORTED_VALUE`,{valueType:typeof n})}if(s)return r;i(o).push({name:t,type:r})}}return Object.entries(n).forEach(([e,n])=>{a(e,n,t)}),r}function n(t){let n=typeof t==`string`&&/^0x[0-9a-fA-F]+$/u.test(t)?Number(t):typeof t==`number`?t:NaN;if(!Number.isSafeInteger(n)||n<=0)throw new e(`INVALID_CHAIN_ID`,{chainId:typeof t==`string`||typeof t==`number`?String(t):typeof t});return{name:`ethereum`,chainId:n}}const r=/* @__PURE__ */ new Set([`RequestTrade`,`AddLiquidity`,`RemoveLiquidity`,`CollectPositionFees`]);function i(e,t){return typeof e[t]==`number`?e[t]:0}function a(e){return{...e,amount0Desired:i(e,`amount0Desired`),amount0Min:i(e,`amount0Min`),amount1Desired:i(e,`amount1Desired`),amount1Min:i(e,`amount1Min`),positionId:e.positionId??``}}function o(e){return{...e,amount:i(e,`amount`),amount0Min:i(e,`amount0Min`),amount1Min:i(e,`amount1Min`),positionId:e.positionId??``}}function s(e){return{...e,amount0Requested:i(e,`amount0Requested`),amount1Requested:i(e,`amount1Requested`),positionId:e.positionId??``}}const c={AddLiquidity:a,RemoveLiquidity:o,CollectPositionFees:s};function l(e,n){let r=c[e],i=r?r(n):n;return{completedDto:i,types:t(e,i)}}export{r as EIP712_CAPABLE_METHODS,c as EIP712_FIELD_COMPLETERS,l as buildEIP712Payload,n as eip712DomainFor,t as generateEIP712Types};
|
|
4
|
-
//# sourceMappingURL=eip712.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"eip712.js","names":[],"sources":["../../../src/utils/eip712.ts"],"sourcesContent":["/**\n * Genuine EIP-712 typed-data signing for the four v2 dex-contract operations proven (2026-09-16,\n * live bisection against stage — see defi-backend's `chain-findings-artifact` memory /\n * https://claude.ai/artifact/3N9MevSjoQdU7gqnVB3dfU) to recover the `client|` identity correctly\n * via `eth_signTypedData_v4`, unlike `personal_sign` (which only ever resolves the bare `eth|`\n * form — see `BrowserWalletSigner`'s own doc comment). Mirrors frontend_v2's\n * `src/Services/eip712Types.ts` + `readWriteUtilsV2.ts`'s `EIP712_FIELD_COMPLETERS` exactly —\n * ported here rather than shared as a package because gswap-sdk has no frontend_v2 dependency\n * and should not gain one for four small functions.\n */\nimport { GSwapSDKError } from '../classes/gswap_sdk_error.js';\n\n/** EIP-712 `types`: each struct name mapped to its ordered `{ name, type }` fields. */\nexport type EIP712Types = Record<string, Array<{ name: string; type: string }>>;\n\n/**\n * Derives the EIP-712 `types` for a DTO from its runtime shape.\n *\n * The generated `types` travel with the signed payload and are what BOTH sides hash, so they\n * must enumerate EVERY field the chain-side DTO will carry. GalaChain refuses any signature\n * whose `types` leave a DTO field uncovered (`assertNoUnsignedFields`, the fix for the\n * 2026-08-18 unsigned-field-injection drain); when that happens signature recovery fails\n * outright and the chain reports \"Missing signerPublicKey or signerAddress field in dto\".\n */\nexport function generateEIP712Types(\n typeName: string,\n params: Record<string, unknown>,\n): EIP712Types {\n const types: EIP712Types = {};\n types[typeName] = [];\n\n // Every `name` this is ever called with (the top-level `typeName`, or a nested struct's own\n // name) is unconditionally assigned `types[name] = []` on the line immediately before any\n // recursive call that could reach here; TypeScript still types `types[name]` as\n // possibly-undefined (index-signature access), so the guard below stays for real type safety\n // even though no current call path can actually trigger it.\n function fieldsFor(name: string): Array<{ name: string; type: string }> {\n const fields = types[name];\n /* c8 ignore next */\n if (!fields) throw new Error(`Missing EIP-712 type definition for ${name}`);\n return fields;\n }\n\n function addField(\n name: string,\n fieldValue: unknown,\n parentTypeName: string,\n onlyGetType = false,\n ): string | undefined {\n if (Array.isArray(fieldValue)) {\n const type =\n fieldValue.length > 0 ? addField(name, fieldValue[0], parentTypeName, true) : 'string';\n if (!onlyGetType) fieldsFor(parentTypeName).push({ name, type: (type ?? name) + '[]' });\n } else if (typeof fieldValue === 'object' && fieldValue !== null) {\n if (types[name]) {\n throw new GSwapSDKError('EIP712_NAME_COLLISION', { name });\n }\n types[name] = [];\n Object.entries(fieldValue).forEach(([key, value]) => {\n addField(key, value, name);\n });\n if (!onlyGetType) fieldsFor(parentTypeName).push({ name, type: name });\n } else {\n let eipType: string;\n switch (typeof fieldValue) {\n case 'string':\n eipType = 'string';\n break;\n case 'number':\n eipType = 'int256';\n break;\n case 'boolean':\n eipType = 'bool';\n break;\n case 'bigint':\n case 'symbol':\n case 'undefined':\n case 'function':\n case 'object':\n throw new GSwapSDKError('EIP712_UNSUPPORTED_VALUE', { valueType: typeof fieldValue });\n }\n if (onlyGetType) {\n return eipType;\n }\n fieldsFor(parentTypeName).push({ name, type: eipType });\n }\n return undefined;\n }\n\n Object.entries(params).forEach(([key, value]) => {\n addField(key, value, typeName);\n });\n\n return types;\n}\n\n/** The EIP-712 domain carried by a signed payload: GalaChain only uses `name` and `chainId`. */\nexport interface EIP712DomainValue {\n name: string;\n chainId: number;\n}\n\n/**\n * Builds the EIP-712 domain from the wallet's LIVE `eth_chainId` result, exactly like frontend_v2\n * (DEFI-1895): a wallet hashes whatever domain it is handed, and MetaMask refuses a `chainId` that\n * differs from its active network, so a hardcoded `1` breaks every wallet that is not on Mainnet.\n * defi-backend recovers the signer from the `domain` the payload carries (live-proven for chain\n * ids 1, 56 and 11155111), so following the wallet is correct on every network.\n *\n * @param chainId - The raw `eth_chainId` result: a `0x` hex string (the JSON-RPC form) or an integer.\n * @throws GSwapSDKError (`INVALID_CHAIN_ID`) when the wallet answers with anything else.\n */\nexport function eip712DomainFor(chainId: unknown): EIP712DomainValue {\n const parsed =\n typeof chainId === 'string' && /^0x[0-9a-fA-F]+$/u.test(chainId)\n ? Number(chainId)\n : typeof chainId === 'number'\n ? chainId\n : Number.NaN;\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new GSwapSDKError('INVALID_CHAIN_ID', {\n chainId:\n typeof chainId === 'string' || typeof chainId === 'number'\n ? String(chainId)\n : typeof chainId,\n });\n }\n return { name: 'ethereum', chainId: parsed };\n}\n\n/**\n * The four v2 operations proven to recover the signer correctly via genuine EIP-712: `RequestTrade`\n * never had the problem (one numeric field). `AddLiquidity`/`RemoveLiquidity`/\n * `CollectPositionFees` each need their `types` completed with a handful of fields their real\n * server-side DTO always carries — see the `complete*Fields` functions below. `CreatePool` is a\n * genuinely different, unsolved problem (nested `TokenClassKey` structs, not a flat\n * missing-field gap) and is NOT in this set — callers must keep using `personal-sign` for it.\n */\nexport const EIP712_CAPABLE_METHODS: ReadonlySet<string> = new Set([\n 'RequestTrade',\n 'AddLiquidity',\n 'RemoveLiquidity',\n 'CollectPositionFees',\n]);\n\n/**\n * Every `complete*Fields` function below shares the same two live-proven rules:\n * 1. Numeric completeness fields MUST be JS `number`, never numeric strings —\n * `generateEIP712Types` infers a field's Solidity type from `typeof`, and declaring one as\n * EIP-712 `string` instead of `int256` breaks recovery identically to omitting the field\n * entirely (verified live on AddLiquidity: `amount0Min: '0'` fails with the exact same\n * \"Missing signerPublicKey\" error as `amount0Min` being absent; `amount0Min: 0` succeeds).\n * 2. `positionId` has no such constraint — an empty string works, and does not target an\n * existing position (`positionId: ''` created a fresh position on AddLiquidity, not an add\n * to position id `''`; on RemoveLiquidity/CollectPositionFees the real position is still\n * resolved from `token0`/`token1`/`fee`/`tickLower`/`tickUpper`, not from this field).\n */\nfunction numericOr0(dto: Record<string, unknown>, field: string): number {\n return typeof dto[field] === 'number' ? dto[field] : 0;\n}\n\n/**\n * `AddLiquidity`'s real server-side DTO always carries `amount0Desired`/`amount0Min`/\n * `amount1Desired`/`amount1Min`/`positionId` once reconstructed, regardless of which deposit\n * convention the caller used (`Positions.addLiquidityByTicks` only ever sends\n * `depositQuantityToken0`/`depositQuantityToken1`). Proven empirically by bisection: none of the\n * five alone fixes recovery, all five together does (live 201, tx `407d9b24...`, block\n * `2429022`).\n */\nfunction completeAddLiquidityFields(dto: Record<string, unknown>): Record<string, unknown> {\n return {\n ...dto,\n amount0Desired: numericOr0(dto, 'amount0Desired'),\n amount0Min: numericOr0(dto, 'amount0Min'),\n amount1Desired: numericOr0(dto, 'amount1Desired'),\n amount1Min: numericOr0(dto, 'amount1Min'),\n positionId: dto['positionId'] ?? '',\n };\n}\n\n/**\n * `RemoveLiquidity`'s real server-side DTO always carries `amount`/`amount0Min`/`amount1Min`/\n * `positionId` — `Positions.removeLiquidity` only ever sends a `withdrawalQuantityTokenX` (or\n * neither, for a full close). Proven empirically: every subset of these four fails, all four\n * together succeeds (live, random-signer probe — recovery confirmed by the response moving from\n * \"Missing signerPublicKey\" to a genuine position-not-found 404).\n */\nfunction completeRemoveLiquidityFields(dto: Record<string, unknown>): Record<string, unknown> {\n return {\n ...dto,\n amount: numericOr0(dto, 'amount'),\n amount0Min: numericOr0(dto, 'amount0Min'),\n amount1Min: numericOr0(dto, 'amount1Min'),\n positionId: dto['positionId'] ?? '',\n };\n}\n\n/**\n * `CollectPositionFees`'s real server-side DTO always carries `amount0Requested`/\n * `amount1Requested`/`positionId` — `Positions.collectPositionFees` sends only the five identity\n * fields. Proven empirically the same way as `completeRemoveLiquidityFields`.\n */\nfunction completeCollectPositionFeesFields(dto: Record<string, unknown>): Record<string, unknown> {\n return {\n ...dto,\n amount0Requested: numericOr0(dto, 'amount0Requested'),\n amount1Requested: numericOr0(dto, 'amount1Requested'),\n positionId: dto['positionId'] ?? '',\n };\n}\n\nexport const EIP712_FIELD_COMPLETERS: Readonly<\n Record<string, (dto: Record<string, unknown>) => Record<string, unknown>>\n> = {\n AddLiquidity: completeAddLiquidityFields,\n RemoveLiquidity: completeRemoveLiquidityFields,\n CollectPositionFees: completeCollectPositionFeesFields,\n};\n\n/**\n * Completes a DTO's fields for EIP-712 signing (a no-op for methods with no known gap, e.g.\n * `RequestTrade`) and derives its `types`. Exported separately from the signing call itself so tests\n * can assert on the exact payload without needing a live provider.\n */\nexport function buildEIP712Payload(\n methodName: string,\n dto: Record<string, unknown>,\n): { completedDto: Record<string, unknown>; types: EIP712Types } {\n const completer = EIP712_FIELD_COMPLETERS[methodName];\n const completedDto = completer ? completer(dto) : dto;\n const types = generateEIP712Types(methodName, completedDto);\n return { completedDto, types };\n}\n"],"mappings":"8DAwBA,SAAgB,EACd,EACA,EACa,CACb,IAAM,EAAqB,CAAC,EAC5B,EAAM,GAAY,CAAC,EAOnB,SAAS,EAAU,EAAqD,CACtE,IAAM,EAAS,EAAM;;AAErB,GAAI,CAAC,EAAQ,MAAU,MAAM,uCAAuC,GAAM,EAC1E,OAAO,CACT,CAEA,SAAS,EACP,EACA,EACA,EACA,EAAc,GACM,C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OAAO,GAAY,SAC9C,OAAO,CAAO,EACd,OAAO,CACf,CAAC,EAEH,MAAO,CAAE,KAAM,WAAY,QAAS,CAAO,CAC7C,CAUA,MAAa,kBAA8C,IAAI,IAAI,CACjE,eACA,eACA,kBACA,qBACF,CAAC,EAcD,SAAS,EAAW,EAA8B,EAAuB,CACvE,OAAO,OAAO,EAAI,IAAW,SAAW,EAAI,GAAS,CACvD,CAUA,SAAS,EAA2B,EAAuD,CACzF,MAAO,CACL,GAAG,EACH,eAAgB,EAAW,EAAK,gBAAgB,EAChD,WAAY,EAAW,EAAK,YAAY,EACxC,eAAgB,EAAW,EAAK,gBAAgB,EAChD,WAAY,EAAW,EAAK,YAAY,EACxC,WAAY,EAAI,YAAiB,EACnC,CACF,CASA,SAAS,EAA8B,EAAuD,CAC5F,MAAO,CACL,GAAG,EACH,OAAQ,EAAW,EAAK,QAAQ,EAChC,WAAY,EAAW,EAAK,YAAY,EACxC,WAAY,EAAW,EAAK,YAAY,EACxC,WAAY,EAAI,YAAiB,EACnC,CACF,CAOA,SAAS,EAAkC,EAAuD,CAChG,MAAO,CACL,GAAG,EACH,iBAAkB,EAAW,EAAK,kBAAkB,EACpD,iBAAkB,EAAW,EAAK,kBAAkB,EACpD,WAAY,EAAI,YAAiB,EACnC,CACF,CAEA,MAAa,EAET,CACF,aAAc,EACd,gBAAiB,EACjB,oBAAqB,CACvB,EAOA,SAAgB,EACd,EACA,EAC+D,CAC/D,IAAM,EAAY,EAAwB,GACpC,EAAe,EAAY,EAAU,CAAG,EAAI,EAElD,MAAO,CAAE,eAAc,MADT,EAAoB,EAAY,CACnB,CAAE,CAC/B"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=Symbol.for(`@gala-chain/gswap-sdk/error`);function t(e){return typeof e==`object`&&!!e}function n(n){return t(n)&&n[e]===!0}function r(e){return n(e)?!0:t(e)&&typeof e.code==`string`&&t(e.params)&&!Array.isArray(e.params)}export{e as GSWAP_ERROR_BRAND,n as hasGSwapErrorBrand,r as isGSwapErrorLike};
|
|
2
|
-
//# sourceMappingURL=error_brand.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"error_brand.js","names":[],"sources":["../../../src/utils/error_brand.ts"],"sourcesContent":["/**\n * The brand every `GSwapSDKError` carries, and the duck-type check for the \"failure shape\". This\n * module has NO imports on purpose: it is part of the light `@gala-chain/gswap-sdk/wallet` entry,\n * which must never pull the error catalog or the main bundle in.\n */\n\n/**\n * The brand of an SDK error: `error[GSWAP_ERROR_BRAND] === true`. It is a registered symbol\n * (`Symbol.for`), so two copies of the SDK in one page (a wallet bundle and an app bundle) still\n * recognise each other's errors, which `instanceof` cannot do.\n */\nexport const GSWAP_ERROR_BRAND: unique symbol = Symbol.for('@gala-chain/gswap-sdk/error');\n\n/** The least an object must have to be read as an SDK error or its plain-object view. */\nexport interface GSwapErrorShape {\n readonly code: string;\n readonly params: Readonly<Record<string, unknown>>;\n}\n\nfunction isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/** True when `value` carries the SDK error brand (a real `GSwapSDKError`, from any copy of the SDK). */\nexport function hasGSwapErrorBrand(value: unknown): boolean {\n return isRecord(value) && value[GSWAP_ERROR_BRAND] === true;\n}\n\n/**\n * True when `value` is an SDK error (it carries the brand) or a plain-object VIEW of one: a string\n * `code` and an object `params`, which is the shape of `GSwapSDKError` and of the wrapper objects\n * an app builds from one (`{ code, params, status?, phase?, ... }`). A wallet's own error (an\n * EIP-1193 numeric `code`, an ethers error with a string `code` and no `params`) is neither. It\n * says the value has the SDK's shape, not that `code` is a code the SDK knows.\n *\n * @example\n * ```ts\n * if (isGSwapErrorLike(error)) report(error.code, error.params); // no `instanceof`, no SDK import\n * ```\n */\nexport function isGSwapErrorLike(value: unknown): value is GSwapErrorShape {\n if (hasGSwapErrorBrand(value)) return true;\n return (\n isRecord(value) &&\n typeof value['code'] === 'string' &&\n isRecord(value['params']) &&\n !Array.isArray(value['params'])\n );\n}\n"],"mappings":"AAWA,MAAa,EAAmC,OAAO,IAAI,6BAA6B,EAQxF,SAAS,EAAS,EAAuD,CACvE,OAAO,OAAO,GAAU,YAAY,CACtC,CAGA,SAAgB,EAAmB,EAAyB,CAC1D,OAAO,EAAS,CAAK,GAAK,EAAM,KAAuB,EACzD,CAcA,SAAgB,EAAiB,EAA0C,CAEzE,OADI,EAAmB,CAAK,EAAU,GAEpC,EAAS,CAAK,GACd,OAAO,EAAM,MAAY,UACzB,EAAS,EAAM,MAAS,GACxB,CAAC,MAAM,QAAQ,EAAM,MAAS,CAElC"}
|