@cityofzion/bs-neo3 1.2.0 → 1.3.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.
Files changed (46) hide show
  1. package/dist/BSNeo3.d.ts +3 -3
  2. package/dist/BSNeo3.js +9 -9
  3. package/dist/builder/invocation/FlamingoSwapInvocationBuilderNeo3.d.ts +7 -0
  4. package/dist/builder/invocation/FlamingoSwapInvocationBuilderNeo3.js +95 -0
  5. package/dist/builder/invocation/NeonDappKitInvocationBuilderNeo3.d.ts +34 -0
  6. package/dist/builder/invocation/NeonDappKitInvocationBuilderNeo3.js +102 -0
  7. package/dist/constants/FlamingoSwapConstants.d.ts +36 -0
  8. package/dist/constants/FlamingoSwapConstants.js +853 -0
  9. package/dist/{BSNeo3Helper.js → helpers/BSNeo3Helper.js} +2 -2
  10. package/dist/helpers/FlamingoSwapHelper.d.ts +19 -0
  11. package/dist/helpers/FlamingoSwapHelper.js +84 -0
  12. package/dist/index.d.ts +13 -11
  13. package/dist/index.js +13 -11
  14. package/dist/{DoraBDSNeo3.d.ts → services/blockchain-data/DoraBDSNeo3.d.ts} +4 -4
  15. package/dist/{DoraBDSNeo3.js → services/blockchain-data/DoraBDSNeo3.js} +3 -3
  16. package/dist/{RpcBDSNeo3.d.ts → services/blockchain-data/RpcBDSNeo3.d.ts} +2 -2
  17. package/dist/{RpcBDSNeo3.js → services/blockchain-data/RpcBDSNeo3.js} +4 -4
  18. package/dist/{FlamingoEDSNeo3.d.ts → services/exchange-data/FlamingoEDSNeo3.d.ts} +1 -1
  19. package/dist/{FlamingoEDSNeo3.js → services/exchange-data/FlamingoEDSNeo3.js} +1 -1
  20. package/dist/{DoraESNeo3.d.ts → services/explorer/DoraESNeo3.d.ts} +2 -2
  21. package/dist/{DoraESNeo3.js → services/explorer/DoraESNeo3.js} +1 -1
  22. package/dist/{NeonDappKitLedgerServiceNeo3.d.ts → services/ledger/NeonDappKitLedgerServiceNeo3.d.ts} +2 -4
  23. package/dist/services/ledger/NeonDappKitLedgerServiceNeo3.js +135 -0
  24. package/dist/{GhostMarketNDSNeo3.d.ts → services/nft-data/GhostMarketNDSNeo3.d.ts} +2 -2
  25. package/dist/{RpcNDSNeo3.d.ts → services/nft-data/RpcNDSNeo3.d.ts} +1 -1
  26. package/dist/services/swap/FlamingoSwapServiceNeo3.d.ts +23 -0
  27. package/dist/services/swap/FlamingoSwapServiceNeo3.js +271 -0
  28. package/dist/services/swap/handlers/FlamingoSwapDetailsHandler.d.ts +24 -0
  29. package/dist/services/swap/handlers/FlamingoSwapDetailsHandler.js +178 -0
  30. package/dist/services/swap/handlers/FlamingoSwapRouteHandler.d.ts +13 -0
  31. package/dist/services/swap/handlers/FlamingoSwapRouteHandler.js +181 -0
  32. package/dist/services/swap/handlers/FlamingoSwapSocketHandler.d.ts +9 -0
  33. package/dist/services/swap/handlers/FlamingoSwapSocketHandler.js +57 -0
  34. package/dist/services/swap/handlers/index.d.ts +3 -0
  35. package/dist/services/swap/handlers/index.js +19 -0
  36. package/package.json +7 -5
  37. package/dist/NeonDappKitLedgerServiceNeo3.js +0 -110
  38. package/dist/flamingo-swap/FlamingoSwapControllerService.d.ts +0 -20
  39. package/dist/flamingo-swap/FlamingoSwapControllerService.js +0 -290
  40. package/dist/flamingo-swap/FlamingoSwapHelper.d.ts +0 -48
  41. package/dist/flamingo-swap/FlamingoSwapHelper.js +0 -171
  42. package/dist/flamingo-swap/FlamingoSwapNeonDappKitInvocationBuilder.d.ts +0 -19
  43. package/dist/flamingo-swap/FlamingoSwapNeonDappKitInvocationBuilder.js +0 -208
  44. package/dist/{BSNeo3Helper.d.ts → helpers/BSNeo3Helper.d.ts} +0 -0
  45. package/dist/{GhostMarketNDSNeo3.js → services/nft-data/GhostMarketNDSNeo3.js} +1 -1
  46. /package/dist/{RpcNDSNeo3.js → services/nft-data/RpcNDSNeo3.js} +0 -0
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
12
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
13
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
14
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
15
+ };
16
+ var _a, _FlamingoSwapRouteHandler_invokeReserves, _FlamingoSwapRouteHandler_createSwapRoute, _FlamingoSwapRouteHandler_getShortestRoutePath;
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.FlamingoSwapRouteHandler = void 0;
19
+ const neon_dappkit_1 = require("@cityofzion/neon-dappkit");
20
+ const neon_dappkit_types_1 = require("@cityofzion/neon-dappkit-types");
21
+ const NeonDappKitInvocationBuilderNeo3_1 = require("../../../builder/invocation/NeonDappKitInvocationBuilderNeo3");
22
+ const FlamingoSwapHelper_1 = require("../../../helpers/FlamingoSwapHelper");
23
+ class FlamingoSwapRouteHandler {
24
+ static calculateBestRouteForSwap({ tokenToUse, tokenToReceive, network, }) {
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ const routePath = __classPrivateFieldGet(this, _a, "m", _FlamingoSwapRouteHandler_getShortestRoutePath).call(this, {
27
+ network,
28
+ startToken: tokenToUse,
29
+ targetToken: tokenToReceive,
30
+ });
31
+ if (routePath.length === 0)
32
+ return [];
33
+ const { stack: reservesStack } = yield __classPrivateFieldGet(this, _a, "m", _FlamingoSwapRouteHandler_invokeReserves).call(this, { network, routePath });
34
+ return __classPrivateFieldGet(this, _a, "m", _FlamingoSwapRouteHandler_createSwapRoute).call(this, { network, routePath, reservesStack });
35
+ });
36
+ }
37
+ static createPoolGraph(network) {
38
+ const pools = FlamingoSwapHelper_1.FlamingoSwapHelper.getFlamingoSwapPools(network);
39
+ const tokens = FlamingoSwapHelper_1.FlamingoSwapHelper.getFlamingoSwapTokens(network);
40
+ const { NEO, bNEO } = tokens;
41
+ const poolGraph = {};
42
+ // Initialize poolGraph with empty arrays
43
+ Object.values(tokens).forEach(token => {
44
+ poolGraph[token.symbol] = [];
45
+ });
46
+ // Add edges to poolGraph
47
+ Object.values(pools).forEach(pool => {
48
+ const tokenA = pool.tokens[0].symbol;
49
+ const tokenB = pool.tokens[1].symbol;
50
+ poolGraph[tokenA].push(tokenB);
51
+ poolGraph[tokenB].push(tokenA);
52
+ });
53
+ // Remove duplicates from poolGraph
54
+ Object.keys(poolGraph).forEach(tokenSymbol => {
55
+ poolGraph[tokenSymbol] = [...new Set(poolGraph[tokenSymbol])];
56
+ });
57
+ // Include NEO to the poolGraph
58
+ poolGraph[NEO.symbol] = Object.keys(tokens).filter(tokenSymbol => tokenSymbol === bNEO.symbol);
59
+ // Include relationship between NEO and bNEO
60
+ poolGraph[bNEO.symbol].push(NEO.symbol);
61
+ return poolGraph;
62
+ }
63
+ }
64
+ exports.FlamingoSwapRouteHandler = FlamingoSwapRouteHandler;
65
+ _a = FlamingoSwapRouteHandler, _FlamingoSwapRouteHandler_invokeReserves = function _FlamingoSwapRouteHandler_invokeReserves({ network, routePath }) {
66
+ return __awaiter(this, void 0, void 0, function* () {
67
+ const invoker = yield neon_dappkit_1.NeonInvoker.init({
68
+ rpcAddress: network.url,
69
+ });
70
+ const scriptHashes = FlamingoSwapHelper_1.FlamingoSwapHelper.getFlamingoSwapScriptHashes(network);
71
+ const routerScriptHash = scriptHashes.flamingoSwapRouter;
72
+ // Remove NEO token from the routePath because it's not supported by the router
73
+ const routePathWithoutNeo = routePath.filter(route => !FlamingoSwapHelper_1.FlamingoSwapHelper.isNeoToken(network, route.tokenToUse) &&
74
+ !FlamingoSwapHelper_1.FlamingoSwapHelper.isNeoToken(network, route.tokenToReceive));
75
+ const getReservesContractInvocations = routePathWithoutNeo.map(route => NeonDappKitInvocationBuilderNeo3_1.NeonDappKitInvocationBuilderNeo3.getReservesContractInvocation({
76
+ routerScriptHash,
77
+ tokenToUseHash: route.tokenToUse.hash,
78
+ tokenToReceiveHash: route.tokenToReceive.hash,
79
+ }));
80
+ const getReservesContractInvocationMulti = {
81
+ invocations: [...getReservesContractInvocations],
82
+ };
83
+ return yield invoker.testInvoke(getReservesContractInvocationMulti);
84
+ });
85
+ }, _FlamingoSwapRouteHandler_createSwapRoute = function _FlamingoSwapRouteHandler_createSwapRoute({ network, routePath, reservesStack }) {
86
+ const isNeoTokenToUse = FlamingoSwapHelper_1.FlamingoSwapHelper.isNeoToken(network, routePath[0].tokenToUse);
87
+ const isNeoTokenToReceive = FlamingoSwapHelper_1.FlamingoSwapHelper.isNeoToken(network, routePath[routePath.length - 1].tokenToReceive);
88
+ const swapRoute = [];
89
+ for (let index = 0; index < reservesStack.length; index++) {
90
+ const item = reservesStack[index];
91
+ if (!neon_dappkit_types_1.TypeChecker.isStackTypeArray(item) ||
92
+ !neon_dappkit_types_1.TypeChecker.isStackTypeInteger(item.value[0]) ||
93
+ !neon_dappkit_types_1.TypeChecker.isStackTypeInteger(item.value[1])) {
94
+ throw new Error('Invalid reserves response');
95
+ }
96
+ // Include NEO token in the swapRoute with 0 reserves because it wasn't supported by the router during the reserves invocation
97
+ if (isNeoTokenToUse && index === 0) {
98
+ swapRoute.push({
99
+ tokenToUse: routePath[index].tokenToUse,
100
+ reserveTokenToUse: '0',
101
+ tokenToReceive: routePath[index].tokenToReceive,
102
+ reserveTokenToReceive: '0',
103
+ });
104
+ index++;
105
+ }
106
+ swapRoute.push({
107
+ tokenToUse: routePath[index].tokenToUse,
108
+ reserveTokenToUse: item.value[1].value,
109
+ tokenToReceive: routePath[index].tokenToReceive,
110
+ reserveTokenToReceive: item.value[0].value,
111
+ });
112
+ }
113
+ // Include NEO token in the swapRoute with 0 reserves because it wasn't supported by the router during the reserves invocation
114
+ if (isNeoTokenToReceive) {
115
+ swapRoute.push({
116
+ tokenToUse: routePath[routePath.length - 1].tokenToUse,
117
+ reserveTokenToUse: '0',
118
+ tokenToReceive: routePath[routePath.length - 1].tokenToReceive,
119
+ reserveTokenToReceive: '0',
120
+ });
121
+ }
122
+ return swapRoute;
123
+ }, _FlamingoSwapRouteHandler_getShortestRoutePath = function _FlamingoSwapRouteHandler_getShortestRoutePath({ network, startToken, targetToken }) {
124
+ // Initialize an empty object to track predecessors of each token
125
+ const predecessor = {};
126
+ // Create a graph representation of the token network
127
+ const poolGraph = this.createPoolGraph(network);
128
+ // Initialize the queue with the start token's symbol
129
+ const queue = [startToken.symbol];
130
+ // Track visited tokens, starting with the start token marked as visited
131
+ const tokensVisited = {
132
+ [startToken.symbol]: true,
133
+ };
134
+ // Initialize an empty array to store the path of tokens
135
+ let path = [];
136
+ while (queue.length) {
137
+ // Remove and get the first token symbol from the queue
138
+ const currentTokenSymbol = queue.shift();
139
+ if (!currentTokenSymbol)
140
+ break;
141
+ const currentToken = FlamingoSwapHelper_1.FlamingoSwapHelper.getFlamingoSwapToken(network, currentTokenSymbol);
142
+ if (!currentToken)
143
+ continue;
144
+ // Get the neighbors of the current token from the graph
145
+ const neighbours = poolGraph[currentToken.symbol];
146
+ for (const neighbourSymbol of neighbours || []) {
147
+ if (tokensVisited[neighbourSymbol])
148
+ continue; // Skip if the neighbor has already been visited
149
+ // Mark the neighbor token as visited
150
+ tokensVisited[neighbourSymbol] = true;
151
+ // Record the current token as the predecessor of the neighbor token
152
+ predecessor[neighbourSymbol] = currentToken;
153
+ // Add the neighbor token symbol to the queue
154
+ queue.push(neighbourSymbol);
155
+ if (neighbourSymbol === targetToken.symbol) {
156
+ // Initialize the path with the target token
157
+ path = [targetToken];
158
+ // Start reconstructing the path from the target token back to the start token
159
+ let prevToken = currentToken;
160
+ while (prevToken && prevToken.symbol !== startToken.symbol) {
161
+ path.push(prevToken); // Add the predecessor token to the path
162
+ prevToken = predecessor[prevToken.symbol]; // Move to the predecessor token
163
+ }
164
+ // If the start token is reached, add it to the path and reverse the path to start-to-end order
165
+ if (prevToken) {
166
+ path.push(prevToken);
167
+ path.reverse();
168
+ }
169
+ break;
170
+ }
171
+ }
172
+ if (path.length)
173
+ break;
174
+ }
175
+ const routePath = [];
176
+ // Convert the token path into route paths
177
+ for (let i = 0; i < path.length - 1; i++) {
178
+ routePath.push({ tokenToUse: path[i], tokenToReceive: path[i + 1] });
179
+ }
180
+ return routePath;
181
+ };
@@ -0,0 +1,9 @@
1
+ type ListenBlockAddedParams = {
2
+ callback: () => Promise<void> | void;
3
+ };
4
+ export declare class FlamingoSwapSocketService {
5
+ #private;
6
+ onBlockAdded({ callback }: ListenBlockAddedParams): void;
7
+ closeConnection(): void;
8
+ }
9
+ export {};
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
12
+ if (kind === "m") throw new TypeError("Private method is not writable");
13
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
14
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
16
+ };
17
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
18
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
19
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
+ };
22
+ var __importDefault = (this && this.__importDefault) || function (mod) {
23
+ return (mod && mod.__esModule) ? mod : { "default": mod };
24
+ };
25
+ var _FlamingoSwapSocketService_ws;
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.FlamingoSwapSocketService = void 0;
28
+ const isomorphic_ws_1 = __importDefault(require("isomorphic-ws"));
29
+ const FlamingoSwapConstants_1 = require("../../../constants/FlamingoSwapConstants");
30
+ class FlamingoSwapSocketService {
31
+ constructor() {
32
+ _FlamingoSwapSocketService_ws.set(this, void 0);
33
+ }
34
+ onBlockAdded({ callback }) {
35
+ __classPrivateFieldSet(this, _FlamingoSwapSocketService_ws, new isomorphic_ws_1.default(FlamingoSwapConstants_1.BLOCKCHAIN_WSS_URL), "f");
36
+ __classPrivateFieldGet(this, _FlamingoSwapSocketService_ws, "f").onopen = () => {
37
+ const block_added = {
38
+ jsonrpc: '2.0',
39
+ method: 'subscribe',
40
+ params: ['block_added'],
41
+ id: 1,
42
+ };
43
+ __classPrivateFieldGet(this, _FlamingoSwapSocketService_ws, "f").send(JSON.stringify(block_added));
44
+ };
45
+ __classPrivateFieldGet(this, _FlamingoSwapSocketService_ws, "f").onmessage = () => __awaiter(this, void 0, void 0, function* () {
46
+ yield callback();
47
+ });
48
+ }
49
+ closeConnection() {
50
+ if (!__classPrivateFieldGet(this, _FlamingoSwapSocketService_ws, "f"))
51
+ return;
52
+ __classPrivateFieldGet(this, _FlamingoSwapSocketService_ws, "f").close();
53
+ __classPrivateFieldSet(this, _FlamingoSwapSocketService_ws, null, "f");
54
+ }
55
+ }
56
+ exports.FlamingoSwapSocketService = FlamingoSwapSocketService;
57
+ _FlamingoSwapSocketService_ws = new WeakMap();
@@ -0,0 +1,3 @@
1
+ export * from './FlamingoSwapDetailsHandler';
2
+ export * from './FlamingoSwapRouteHandler';
3
+ export * from './FlamingoSwapSocketHandler';
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./FlamingoSwapDetailsHandler"), exports);
18
+ __exportStar(require("./FlamingoSwapRouteHandler"), exports);
19
+ __exportStar(require("./FlamingoSwapSocketHandler"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cityofzion/bs-neo3",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "repository": "https://github.com/CityOfZion/blockchain-services",
@@ -17,14 +17,16 @@
17
17
  "query-string": "7.1.3",
18
18
  "@ledgerhq/hw-transport": "~6.30.5",
19
19
  "@cityofzion/neon-dappkit": "0.4.1",
20
- "bignumber.js": "~9.1.2",
21
- "isomorphic-ws": "~5.0.0",
22
- "@cityofzion/blockchain-service": "1.2.0",
20
+ "bignumber.js": "^9.1.2",
21
+ "isomorphic-ws": "^5.0.0",
22
+ "lodash.clonedeep": "^4.5.0",
23
+ "@cityofzion/blockchain-service": "1.3.0",
23
24
  "@cityofzion/bs-asteroid-sdk": "0.9.0"
24
25
  },
25
26
  "devDependencies": {
26
27
  "@cityofzion/neon-dappkit-types": "~0.3.1",
27
28
  "@ledgerhq/hw-transport-node-hid": "~6.28.5",
29
+ "@types/lodash.clonedeep": "^4.5.9",
28
30
  "@types/jest": "29.5.3",
29
31
  "@typescript-eslint/eslint-plugin": "^6.5.0",
30
32
  "@typescript-eslint/parser": "^6.5.0",
@@ -34,7 +36,7 @@
34
36
  "ts-jest": "29.1.1",
35
37
  "ts-node": "10.9.1",
36
38
  "typescript": "4.9.5",
37
- "typed-emitter": "~2.1.0"
39
+ "typed-emitter": "^2.1.0"
38
40
  },
39
41
  "scripts": {
40
42
  "build": "tsc --project tsconfig.build.json",
@@ -1,110 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.NeonDappKitLedgerServiceNeo3 = void 0;
16
- const neon_js_1 = require("@cityofzion/neon-js");
17
- const neon_dappkit_1 = require("@cityofzion/neon-dappkit");
18
- const events_1 = __importDefault(require("events"));
19
- class NeonDappKitLedgerServiceNeo3 {
20
- constructor(getLedgerTransport) {
21
- this.getLedgerTransport = getLedgerTransport;
22
- this.emitter = new events_1.default();
23
- }
24
- getAddress(transport) {
25
- return __awaiter(this, void 0, void 0, function* () {
26
- const publicKey = yield this.getPublicKey(transport);
27
- const { address } = new neon_js_1.wallet.Account(publicKey);
28
- return address;
29
- });
30
- }
31
- getSigningCallback(transport) {
32
- return (transaction, { witnessIndex, network }) => __awaiter(this, void 0, void 0, function* () {
33
- const publicKey = yield this.getPublicKey(transport);
34
- const account = new neon_js_1.wallet.Account(publicKey);
35
- const witnessScriptHash = neon_js_1.wallet.getScriptHashFromVerificationScript(transaction.witnesses[witnessIndex].verificationScript.toString());
36
- if (account.scriptHash !== witnessScriptHash) {
37
- throw new Error('Invalid witness script hash');
38
- }
39
- const signature = yield this.getSignature(transport, transaction.serialize(false), network, witnessIndex);
40
- return signature;
41
- });
42
- }
43
- getSignature(transport, serializedTransaction, networkMagic, addressIndex = 0) {
44
- return __awaiter(this, void 0, void 0, function* () {
45
- try {
46
- this.emitter.emit('getSignatureStart');
47
- const bip44Buffer = this.toBip44Buffer(addressIndex);
48
- yield transport.send(0x80, 0x02, 0, 0x80, bip44Buffer, [0x9000]);
49
- yield transport.send(0x80, 0x02, 1, 0x80, Buffer.from(neon_dappkit_1.NeonParser.numToHex(networkMagic, 4, true), 'hex'), [
50
- 0x9000,
51
- ]);
52
- const chunks = serializedTransaction.match(/.{1,510}/g) || [];
53
- for (let i = 0; i < chunks.length - 1; i++) {
54
- yield transport.send(0x80, 0x02, 2 + i, 0x80, Buffer.from(chunks[i], 'hex'), [0x9000]);
55
- }
56
- const response = yield transport.send(0x80, 0x02, 2 + chunks.length, 0x00, Buffer.from(chunks[chunks.length - 1], 'hex'), [0x9000]);
57
- if (response.length <= 2) {
58
- throw new Error(`No more data but Ledger did not return signature!`);
59
- }
60
- const signature = this.derSignatureToHex(response.toString('hex'));
61
- return signature;
62
- }
63
- finally {
64
- this.emitter.emit('getSignatureEnd');
65
- }
66
- });
67
- }
68
- getPublicKey(transport, addressIndex = 0) {
69
- return __awaiter(this, void 0, void 0, function* () {
70
- const bip44Buffer = this.toBip44Buffer(addressIndex);
71
- const result = yield transport.send(0x80, 0x04, 0x00, 0x00, bip44Buffer, [0x9000]);
72
- const publicKey = result.toString('hex').substring(0, 130);
73
- return publicKey;
74
- });
75
- }
76
- toBip44Buffer(addressIndex = 0, changeIndex = 0, accountIndex = 0) {
77
- const accountHex = this.to8BitHex(accountIndex + 0x80000000);
78
- const changeHex = this.to8BitHex(changeIndex);
79
- const addressHex = this.to8BitHex(addressIndex);
80
- return Buffer.from('8000002C' + '80000378' + accountHex + changeHex + addressHex, 'hex');
81
- }
82
- to8BitHex(num) {
83
- const hex = num.toString(16);
84
- return '0'.repeat(8 - hex.length) + hex;
85
- }
86
- derSignatureToHex(response) {
87
- const ss = new neon_js_1.u.StringStream(response);
88
- // The first byte is format. It is usually 0x30 (SEQ) or 0x31 (SET)
89
- // The second byte represents the total length of the DER module.
90
- ss.read(2);
91
- // Now we read each field off
92
- // Each field is encoded with a type byte, length byte followed by the data itself
93
- ss.read(1); // Read and drop the type
94
- const r = ss.readVarBytes();
95
- ss.read(1);
96
- const s = ss.readVarBytes();
97
- // We will need to ensure both integers are 32 bytes long
98
- const integers = [r, s].map(i => {
99
- if (i.length < 64) {
100
- i = '0'.repeat(i.length - 64) + i;
101
- }
102
- if (i.length > 64) {
103
- i = i.substr(-64);
104
- }
105
- return i;
106
- });
107
- return integers.join('');
108
- }
109
- }
110
- exports.NeonDappKitLedgerServiceNeo3 = NeonDappKitLedgerServiceNeo3;
@@ -1,20 +0,0 @@
1
- import { Account, Network, SwapControllerService, SwapControllerServiceEvents, SwapControllerServiceSwapToReceiveArgs, SwapControllerServiceSwapToUseArgs, Token } from '@cityofzion/blockchain-service';
2
- import TypedEmitter from 'typed-emitter';
3
- import { BSNeo3NetworkId } from '../BSNeo3Helper';
4
- export declare class FlamingoSwapControllerService implements SwapControllerService<BSNeo3NetworkId> {
5
- #private;
6
- eventEmitter: TypedEmitter<SwapControllerServiceEvents>;
7
- constructor(network: Network<BSNeo3NetworkId>);
8
- buildSwapArgs(): SwapControllerServiceSwapToReceiveArgs<BSNeo3NetworkId> | SwapControllerServiceSwapToUseArgs<BSNeo3NetworkId>;
9
- setAccountToUse(account: Account | null): void;
10
- setAmountToUse(val: string | null): void;
11
- setAmountToReceive(val: string | null): void;
12
- setDeadline(deadline: string): void;
13
- setSlippage(slippage: number): void;
14
- setTokenToUse(val: Token | null): Promise<void>;
15
- setTokenToReceive(val: Token | null): Promise<void>;
16
- swap(isLedger?: boolean): Promise<void>;
17
- setReserves(): Promise<void>;
18
- startListeningBlockGeneration(): void;
19
- stopListeningBlockGeneration(): void;
20
- }