@drift-labs/sdk 0.2.0-master.20 → 0.2.0-master.21

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 (62) hide show
  1. package/lib/accounts/types.d.ts +0 -1
  2. package/lib/clearingHouse.d.ts +2 -2
  3. package/lib/clearingHouse.js +25 -19
  4. package/lib/clearingHouseUser.d.ts +9 -1
  5. package/lib/clearingHouseUser.js +57 -20
  6. package/lib/math/orders.d.ts +2 -1
  7. package/lib/math/orders.js +14 -5
  8. package/lib/types.d.ts +3 -0
  9. package/my-script/.env +7 -0
  10. package/my-script/getUserStats.ts +124 -0
  11. package/my-script/multiConnections.ts +137 -0
  12. package/my-script/test-regex.ts +11 -0
  13. package/my-script/utils.ts +52 -0
  14. package/my-script/ww18NdhuLSQPCrHSx7V68eZJpe2y311heWeXJfSmP3Q.json +1 -0
  15. package/my-script/ww2z7N9TG1PLLUQGQF2VKzCFaPtQ5FBhRfeEAuy6c5C.json +1 -0
  16. package/my-script/ww3StJtTubhwssqAhvSSAc5ifCgKjzmF8hz7Gt2DmSa.json +1 -0
  17. package/package.json +1 -1
  18. package/src/clearingHouse.ts +27 -23
  19. package/src/clearingHouseUser.ts +67 -42
  20. package/src/math/orders.ts +26 -9
  21. package/src/types.ts +3 -0
  22. package/src/addresses/marketAddresses.js +0 -26
  23. package/src/assert/assert.js +0 -9
  24. package/src/constants/banks.js +0 -42
  25. package/src/constants/markets.js +0 -42
  26. package/src/constants/numericConstants.js +0 -41
  27. package/src/events/eventList.js +0 -77
  28. package/src/events/eventSubscriber.js +0 -139
  29. package/src/events/fetchLogs.js +0 -50
  30. package/src/events/pollingLogProvider.js +0 -64
  31. package/src/events/sort.js +0 -44
  32. package/src/events/txEventCache.js +0 -71
  33. package/src/events/webSocketLogProvider.js +0 -41
  34. package/src/examples/makeTradeExample.js +0 -80
  35. package/src/factory/bigNum.js +0 -390
  36. package/src/factory/oracleClient.js +0 -20
  37. package/src/math/auction.js +0 -42
  38. package/src/math/conversion.js +0 -11
  39. package/src/math/funding.js +0 -248
  40. package/src/math/oracles.js +0 -26
  41. package/src/math/repeg.js +0 -128
  42. package/src/math/state.js +0 -15
  43. package/src/math/trade.js +0 -253
  44. package/src/math/utils.js +0 -26
  45. package/src/math/utils.js.map +0 -1
  46. package/src/oracles/oracleClientCache.js +0 -19
  47. package/src/oracles/pythClient.js +0 -46
  48. package/src/oracles/quoteAssetOracleClient.js +0 -32
  49. package/src/oracles/switchboardClient.js +0 -69
  50. package/src/oracles/types.js +0 -2
  51. package/src/orderParams.js +0 -20
  52. package/src/slot/SlotSubscriber.js +0 -39
  53. package/src/token/index.js +0 -38
  54. package/src/tokenFaucet.js +0 -189
  55. package/src/tx/types.js +0 -2
  56. package/src/tx/utils.js +0 -17
  57. package/src/userName.js +0 -20
  58. package/src/util/computeUnits.js +0 -27
  59. package/src/util/getTokenAddress.js +0 -9
  60. package/src/util/promiseTimeout.js +0 -14
  61. package/src/util/tps.js +0 -27
  62. package/src/wallet.js +0 -35
package/src/math/utils.js DELETED
@@ -1,26 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.squareRootBN = void 0;
4
- const __1 = require("../");
5
- const squareRootBN = (n, closeness = new __1.BN(1)) => {
6
- // Assuming the sqrt of n as n only
7
- let x = n;
8
- // The closed guess will be stored in the root
9
- let root;
10
- // To count the number of iterations
11
- let count = 0;
12
- const TWO = new __1.BN(2);
13
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
14
- while (count < Number.MAX_SAFE_INTEGER) {
15
- count++;
16
- // Calculate more closed x
17
- root = x.add(n.div(x)).div(TWO);
18
- // Check for closeness
19
- if (x.sub(root).abs().lte(closeness))
20
- break;
21
- // Update root
22
- x = root;
23
- }
24
- return root;
25
- };
26
- exports.squareRootBN = squareRootBN;
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["utils.ts"],"names":[],"mappings":";;;AAAA,2BAAyB;AAElB,MAAM,YAAY,GAAG,CAAC,CAAC,EAAE,SAAS,GAAG,IAAI,MAAE,CAAC,CAAC,CAAC,EAAE,EAAE;IACxD,mCAAmC;IACnC,IAAI,CAAC,GAAG,CAAC,CAAC;IAEV,8CAA8C;IAC9C,IAAI,IAAI,CAAC;IAET,oCAAoC;IACpC,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,MAAM,GAAG,GAAG,IAAI,MAAE,CAAC,CAAC,CAAC,CAAC;IAEtB,6DAA6D;IAC7D,OAAO,KAAK,GAAG,MAAM,CAAC,gBAAgB,EAAE;QACvC,KAAK,EAAE,CAAC;QAER,0BAA0B;QAC1B,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAEhC,sBAAsB;QACtB,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,SAAS,CAAC;YAAE,MAAM;QAE5C,cAAc;QACd,CAAC,GAAG,IAAI,CAAC;KACT;IAED,OAAO,IAAI,CAAC;AACb,CAAC,CAAC;AA1BW,QAAA,YAAY,gBA0BvB"}
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OracleClientCache = void 0;
4
- const oracleClient_1 = require("../factory/oracleClient");
5
- class OracleClientCache {
6
- constructor() {
7
- this.cache = new Map();
8
- }
9
- get(oracleSource, connection) {
10
- const key = Object.keys(oracleSource)[0];
11
- if (this.cache.has(key)) {
12
- return this.cache.get(key);
13
- }
14
- const client = oracleClient_1.getOracleClient(oracleSource, connection);
15
- this.cache.set(key, client);
16
- return client;
17
- }
18
- }
19
- exports.OracleClientCache = OracleClientCache;
@@ -1,46 +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
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.convertPythPrice = exports.PythClient = void 0;
13
- const client_1 = require("@pythnetwork/client");
14
- const anchor_1 = require("@project-serum/anchor");
15
- const numericConstants_1 = require("../constants/numericConstants");
16
- class PythClient {
17
- constructor(connection) {
18
- this.connection = connection;
19
- }
20
- getOraclePriceData(pricePublicKey) {
21
- return __awaiter(this, void 0, void 0, function* () {
22
- const accountInfo = yield this.connection.getAccountInfo(pricePublicKey);
23
- return this.getOraclePriceDataFromBuffer(accountInfo.data);
24
- });
25
- }
26
- getOraclePriceDataFromBuffer(buffer) {
27
- const priceData = client_1.parsePriceData(buffer);
28
- return {
29
- price: convertPythPrice(priceData.aggregate.price, priceData.exponent),
30
- slot: new anchor_1.BN(priceData.lastSlot.toString()),
31
- confidence: convertPythPrice(priceData.confidence, priceData.exponent),
32
- twap: convertPythPrice(priceData.twap.value, priceData.exponent),
33
- twapConfidence: convertPythPrice(priceData.twac.value, priceData.exponent),
34
- hasSufficientNumberOfDataPoints: true,
35
- };
36
- }
37
- }
38
- exports.PythClient = PythClient;
39
- function convertPythPrice(price, exponent) {
40
- exponent = Math.abs(exponent);
41
- const pythPrecision = numericConstants_1.TEN.pow(new anchor_1.BN(exponent).abs());
42
- return new anchor_1.BN(price * Math.pow(10, exponent))
43
- .mul(numericConstants_1.MARK_PRICE_PRECISION)
44
- .div(pythPrecision);
45
- }
46
- exports.convertPythPrice = convertPythPrice;
@@ -1,32 +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
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.QuoteAssetOracleClient = exports.QUOTE_ORACLE_PRICE_DATA = void 0;
13
- const anchor_1 = require("@project-serum/anchor");
14
- const numericConstants_1 = require("../constants/numericConstants");
15
- exports.QUOTE_ORACLE_PRICE_DATA = {
16
- price: numericConstants_1.MARK_PRICE_PRECISION,
17
- slot: new anchor_1.BN(0),
18
- confidence: new anchor_1.BN(1),
19
- hasSufficientNumberOfDataPoints: true,
20
- };
21
- class QuoteAssetOracleClient {
22
- constructor() { }
23
- getOraclePriceData(_pricePublicKey) {
24
- return __awaiter(this, void 0, void 0, function* () {
25
- return Promise.resolve(exports.QUOTE_ORACLE_PRICE_DATA);
26
- });
27
- }
28
- getOraclePriceDataFromBuffer(_buffer) {
29
- return exports.QUOTE_ORACLE_PRICE_DATA;
30
- }
31
- }
32
- exports.QuoteAssetOracleClient = QuoteAssetOracleClient;
@@ -1,69 +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.SwitchboardClient = void 0;
16
- const web3_js_1 = require("@solana/web3.js");
17
- const anchor_1 = require("@project-serum/anchor");
18
- const numericConstants_1 = require("../constants/numericConstants");
19
- const wallet_1 = require("../wallet");
20
- const switchboard_v2_json_1 = __importDefault(require("../idl/switchboard_v2.json"));
21
- let program;
22
- class SwitchboardClient {
23
- constructor(connection) {
24
- this.connection = connection;
25
- }
26
- getOraclePriceData(pricePublicKey) {
27
- return __awaiter(this, void 0, void 0, function* () {
28
- const accountInfo = yield this.connection.getAccountInfo(pricePublicKey);
29
- return this.getOraclePriceDataFromBuffer(accountInfo.data);
30
- });
31
- }
32
- getOraclePriceDataFromBuffer(buffer) {
33
- const program = this.getProgram();
34
- const aggregatorAccountData = program.account.aggregatorAccountData.coder.accounts.decode('AggregatorAccountData', buffer);
35
- const price = convertSwitchboardDecimal(aggregatorAccountData.latestConfirmedRound.result);
36
- const confidence = convertSwitchboardDecimal(aggregatorAccountData.latestConfirmedRound
37
- .stdDeviation);
38
- const hasSufficientNumberOfDataPoints = aggregatorAccountData.latestConfirmedRound.numSuccess >=
39
- aggregatorAccountData.minOracleResults;
40
- const slot = aggregatorAccountData.latestConfirmedRound.roundOpenSlot;
41
- return {
42
- price,
43
- slot,
44
- confidence,
45
- hasSufficientNumberOfDataPoints,
46
- };
47
- }
48
- getProgram() {
49
- if (program) {
50
- return program;
51
- }
52
- program = getSwitchboardProgram(this.connection);
53
- return program;
54
- }
55
- }
56
- exports.SwitchboardClient = SwitchboardClient;
57
- function getSwitchboardProgram(connection) {
58
- const DEFAULT_KEYPAIR = web3_js_1.Keypair.fromSeed(new Uint8Array(32).fill(1));
59
- const programId = web3_js_1.PublicKey.default;
60
- const wallet = new wallet_1.Wallet(DEFAULT_KEYPAIR);
61
- const provider = new anchor_1.AnchorProvider(connection, wallet, {});
62
- return new anchor_1.Program(switchboard_v2_json_1.default, programId, provider);
63
- }
64
- function convertSwitchboardDecimal(switchboardDecimal) {
65
- const switchboardPrecision = numericConstants_1.TEN.pow(new anchor_1.BN(switchboardDecimal.scale));
66
- return switchboardDecimal.mantissa
67
- .mul(numericConstants_1.MARK_PRICE_PRECISION)
68
- .div(switchboardPrecision);
69
- }
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getMarketOrderParams = exports.getTriggerLimitOrderParams = exports.getTriggerMarketOrderParams = exports.getLimitOrderParams = void 0;
4
- const types_1 = require("./types");
5
- function getLimitOrderParams(params) {
6
- return Object.assign({}, params, { orderType: types_1.OrderType.LIMIT });
7
- }
8
- exports.getLimitOrderParams = getLimitOrderParams;
9
- function getTriggerMarketOrderParams(params) {
10
- return Object.assign({}, params, { orderType: types_1.OrderType.TRIGGER_MARKET });
11
- }
12
- exports.getTriggerMarketOrderParams = getTriggerMarketOrderParams;
13
- function getTriggerLimitOrderParams(params) {
14
- return Object.assign({}, params, { orderType: types_1.OrderType.TRIGGER_LIMIT });
15
- }
16
- exports.getTriggerLimitOrderParams = getTriggerLimitOrderParams;
17
- function getMarketOrderParams(params) {
18
- return Object.assign({}, params, { orderType: types_1.OrderType.MARKET });
19
- }
20
- exports.getMarketOrderParams = getMarketOrderParams;
@@ -1,39 +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
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.SlotSubscriber = void 0;
13
- const events_1 = require("events");
14
- class SlotSubscriber {
15
- constructor(connection, _config) {
16
- this.connection = connection;
17
- this.eventEmitter = new events_1.EventEmitter();
18
- }
19
- subscribe() {
20
- return __awaiter(this, void 0, void 0, function* () {
21
- this.currentSlot = yield this.connection.getSlot('confirmed');
22
- this.subscriptionId = this.connection.onSlotChange((slotInfo) => {
23
- this.currentSlot = slotInfo.slot;
24
- this.eventEmitter.emit('newSlot', slotInfo.slot);
25
- });
26
- });
27
- }
28
- getSlot() {
29
- return this.currentSlot;
30
- }
31
- unsubscribe() {
32
- return __awaiter(this, void 0, void 0, function* () {
33
- if (this.subscriptionId) {
34
- yield this.connection.removeSlotChangeListener(this.subscriptionId);
35
- }
36
- });
37
- }
38
- }
39
- exports.SlotSubscriber = SlotSubscriber;
@@ -1,38 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseTokenAccount = void 0;
4
- const spl_token_1 = require("@solana/spl-token");
5
- const web3_js_1 = require("@solana/web3.js");
6
- function parseTokenAccount(data) {
7
- const accountInfo = spl_token_1.AccountLayout.decode(data);
8
- accountInfo.mint = new web3_js_1.PublicKey(accountInfo.mint);
9
- accountInfo.owner = new web3_js_1.PublicKey(accountInfo.owner);
10
- accountInfo.amount = spl_token_1.u64.fromBuffer(accountInfo.amount);
11
- if (accountInfo.delegateOption === 0) {
12
- accountInfo.delegate = null;
13
- // eslint-disable-next-line new-cap
14
- accountInfo.delegatedAmount = new spl_token_1.u64(0);
15
- }
16
- else {
17
- accountInfo.delegate = new web3_js_1.PublicKey(accountInfo.delegate);
18
- accountInfo.delegatedAmount = spl_token_1.u64.fromBuffer(accountInfo.delegatedAmount);
19
- }
20
- accountInfo.isInitialized = accountInfo.state !== 0;
21
- accountInfo.isFrozen = accountInfo.state === 2;
22
- if (accountInfo.isNativeOption === 1) {
23
- accountInfo.rentExemptReserve = spl_token_1.u64.fromBuffer(accountInfo.isNative);
24
- accountInfo.isNative = true;
25
- }
26
- else {
27
- accountInfo.rentExemptReserve = null;
28
- accountInfo.isNative = false;
29
- }
30
- if (accountInfo.closeAuthorityOption === 0) {
31
- accountInfo.closeAuthority = null;
32
- }
33
- else {
34
- accountInfo.closeAuthority = new web3_js_1.PublicKey(accountInfo.closeAuthority);
35
- }
36
- return accountInfo;
37
- }
38
- exports.parseTokenAccount = parseTokenAccount;
@@ -1,189 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
- Object.defineProperty(o, "default", { enumerable: true, value: v });
11
- }) : function(o, v) {
12
- o["default"] = v;
13
- });
14
- var __importStar = (this && this.__importStar) || function (mod) {
15
- if (mod && mod.__esModule) return mod;
16
- var result = {};
17
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
- __setModuleDefault(result, mod);
19
- return result;
20
- };
21
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
22
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
23
- return new (P || (P = Promise))(function (resolve, reject) {
24
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
25
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
26
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
27
- step((generator = generator.apply(thisArg, _arguments || [])).next());
28
- });
29
- };
30
- var __importDefault = (this && this.__importDefault) || function (mod) {
31
- return (mod && mod.__esModule) ? mod : { "default": mod };
32
- };
33
- Object.defineProperty(exports, "__esModule", { value: true });
34
- exports.TokenFaucet = void 0;
35
- const anchor = __importStar(require("@project-serum/anchor"));
36
- const anchor_1 = require("@project-serum/anchor");
37
- const spl_token_1 = require("@solana/spl-token");
38
- const web3_js_1 = require("@solana/web3.js");
39
- const token_faucet_json_1 = __importDefault(require("./idl/token_faucet.json"));
40
- class TokenFaucet {
41
- constructor(connection, wallet, programId, mint, opts) {
42
- this.connection = connection;
43
- this.wallet = wallet;
44
- this.opts = opts || anchor_1.AnchorProvider.defaultOptions();
45
- const provider = new anchor_1.AnchorProvider(connection, wallet, this.opts);
46
- this.provider = provider;
47
- this.program = new anchor_1.Program(token_faucet_json_1.default, programId, provider);
48
- this.mint = mint;
49
- }
50
- getFaucetConfigPublicKeyAndNonce() {
51
- return __awaiter(this, void 0, void 0, function* () {
52
- return anchor.web3.PublicKey.findProgramAddress([
53
- Buffer.from(anchor.utils.bytes.utf8.encode('faucet_config')),
54
- this.mint.toBuffer(),
55
- ], this.program.programId);
56
- });
57
- }
58
- getMintAuthority() {
59
- return __awaiter(this, void 0, void 0, function* () {
60
- return (yield anchor.web3.PublicKey.findProgramAddress([
61
- Buffer.from(anchor.utils.bytes.utf8.encode('mint_authority')),
62
- this.mint.toBuffer(),
63
- ], this.program.programId))[0];
64
- });
65
- }
66
- getFaucetConfigPublicKey() {
67
- return __awaiter(this, void 0, void 0, function* () {
68
- return (yield this.getFaucetConfigPublicKeyAndNonce())[0];
69
- });
70
- }
71
- initialize() {
72
- return __awaiter(this, void 0, void 0, function* () {
73
- const [faucetConfigPublicKey] = yield this.getFaucetConfigPublicKeyAndNonce();
74
- return yield this.program.rpc.initialize({
75
- accounts: {
76
- faucetConfig: faucetConfigPublicKey,
77
- admin: this.wallet.publicKey,
78
- mintAccount: this.mint,
79
- rent: web3_js_1.SYSVAR_RENT_PUBKEY,
80
- systemProgram: anchor.web3.SystemProgram.programId,
81
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
82
- },
83
- });
84
- });
85
- }
86
- fetchState() {
87
- return __awaiter(this, void 0, void 0, function* () {
88
- return yield this.program.account.faucetConfig.fetch(yield this.getFaucetConfigPublicKey());
89
- });
90
- }
91
- mintToUserIx(userTokenAccount, amount) {
92
- return __awaiter(this, void 0, void 0, function* () {
93
- return this.program.instruction.mintToUser(amount, {
94
- accounts: {
95
- faucetConfig: yield this.getFaucetConfigPublicKey(),
96
- mintAccount: this.mint,
97
- userTokenAccount,
98
- mintAuthority: yield this.getMintAuthority(),
99
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
100
- },
101
- });
102
- });
103
- }
104
- mintToUser(userTokenAccount, amount) {
105
- return __awaiter(this, void 0, void 0, function* () {
106
- const mintIx = yield this.mintToUserIx(userTokenAccount, amount);
107
- const tx = new web3_js_1.Transaction().add(mintIx);
108
- const txSig = yield this.program.provider.sendAndConfirm(tx, [], this.opts);
109
- return txSig;
110
- });
111
- }
112
- transferMintAuthority() {
113
- return __awaiter(this, void 0, void 0, function* () {
114
- return yield this.program.rpc.transferMintAuthority({
115
- accounts: {
116
- faucetConfig: yield this.getFaucetConfigPublicKey(),
117
- mintAccount: this.mint,
118
- mintAuthority: yield this.getMintAuthority(),
119
- tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
120
- admin: this.wallet.publicKey,
121
- },
122
- });
123
- });
124
- }
125
- createAssociatedTokenAccountAndMintTo(userPublicKey, amount) {
126
- return __awaiter(this, void 0, void 0, function* () {
127
- const tx = new web3_js_1.Transaction();
128
- const [associatedTokenPublicKey, createAssociatedAccountIx, mintToTx] = yield this.createAssociatedTokenAccountAndMintToInstructions(userPublicKey, amount);
129
- let associatedTokenAccountExists = false;
130
- try {
131
- const assosciatedTokenAccount = yield this.connection.getAccountInfo(associatedTokenPublicKey);
132
- associatedTokenAccountExists = !!assosciatedTokenAccount;
133
- }
134
- catch (e) {
135
- // token account doesn't exist
136
- associatedTokenAccountExists = false;
137
- }
138
- const skipAccountCreation = associatedTokenAccountExists;
139
- if (!skipAccountCreation)
140
- tx.add(createAssociatedAccountIx);
141
- tx.add(mintToTx);
142
- const txSig = yield this.program.provider.sendAndConfirm(tx, [], this.opts);
143
- return [associatedTokenPublicKey, txSig];
144
- });
145
- }
146
- createAssociatedTokenAccountAndMintToInstructions(userPublicKey, amount) {
147
- return __awaiter(this, void 0, void 0, function* () {
148
- const state = yield this.fetchState();
149
- const associateTokenPublicKey = yield this.getAssosciatedMockUSDMintAddress({ userPubKey: userPublicKey });
150
- const createAssociatedAccountIx = spl_token_1.Token.createAssociatedTokenAccountInstruction(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, state.mint, associateTokenPublicKey, userPublicKey, this.wallet.publicKey);
151
- const mintToIx = yield this.mintToUserIx(associateTokenPublicKey, amount);
152
- return [associateTokenPublicKey, createAssociatedAccountIx, mintToIx];
153
- });
154
- }
155
- getAssosciatedMockUSDMintAddress(props) {
156
- return __awaiter(this, void 0, void 0, function* () {
157
- const state = yield this.fetchState();
158
- return spl_token_1.Token.getAssociatedTokenAddress(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, state.mint, props.userPubKey);
159
- });
160
- }
161
- getTokenAccountInfo(props) {
162
- return __awaiter(this, void 0, void 0, function* () {
163
- const assosciatedKey = yield this.getAssosciatedMockUSDMintAddress(props);
164
- const state = yield this.fetchState();
165
- const token = new spl_token_1.Token(this.connection, state.mint, spl_token_1.TOKEN_PROGRAM_ID,
166
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
167
- // @ts-ignore
168
- this.provider.payer);
169
- return yield token.getAccountInfo(assosciatedKey);
170
- });
171
- }
172
- subscribeToTokenAccount(props) {
173
- return __awaiter(this, void 0, void 0, function* () {
174
- try {
175
- const tokenAccountKey = yield this.getAssosciatedMockUSDMintAddress(props);
176
- props.callback(yield this.getTokenAccountInfo(props));
177
- // Couldn't find a way to do it using anchor framework subscription, someone on serum discord recommended this way
178
- this.connection.onAccountChange(tokenAccountKey, (_accountInfo /* accountInfo is a buffer which we don't know how to deserialize */) => __awaiter(this, void 0, void 0, function* () {
179
- props.callback(yield this.getTokenAccountInfo(props));
180
- }));
181
- return true;
182
- }
183
- catch (e) {
184
- return false;
185
- }
186
- });
187
- }
188
- }
189
- exports.TokenFaucet = TokenFaucet;
package/src/tx/types.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
package/src/tx/utils.js DELETED
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.wrapInTx = void 0;
4
- const web3_js_1 = require("@solana/web3.js");
5
- const COMPUTE_UNITS_DEFAULT = 200000;
6
- function wrapInTx(instruction, computeUnits = 600000 // TODO, requires less code change
7
- ) {
8
- const tx = new web3_js_1.Transaction();
9
- if (computeUnits != COMPUTE_UNITS_DEFAULT) {
10
- tx.add(web3_js_1.ComputeBudgetProgram.requestUnits({
11
- units: computeUnits,
12
- additionalFee: 0,
13
- }));
14
- }
15
- return tx.add(instruction);
16
- }
17
- exports.wrapInTx = wrapInTx;
package/src/userName.js DELETED
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decodeName = exports.encodeName = exports.DEFAULT_USER_NAME = exports.MAX_NAME_LENGTH = void 0;
4
- exports.MAX_NAME_LENGTH = 32;
5
- exports.DEFAULT_USER_NAME = 'Main Account';
6
- function encodeName(name) {
7
- if (name.length > exports.MAX_NAME_LENGTH) {
8
- throw Error(`User name (${name}) longer than 32 characters`);
9
- }
10
- const buffer = Buffer.alloc(32);
11
- buffer.fill(name);
12
- buffer.fill(' ', name.length);
13
- return Array(...buffer);
14
- }
15
- exports.encodeName = encodeName;
16
- function decodeName(bytes) {
17
- const buffer = Buffer.from(bytes);
18
- return buffer.toString('utf8').trim();
19
- }
20
- exports.decodeName = decodeName;
@@ -1,27 +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
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.findComputeUnitConsumption = void 0;
13
- function findComputeUnitConsumption(programId, connection, txSignature, commitment = 'confirmed') {
14
- return __awaiter(this, void 0, void 0, function* () {
15
- const tx = yield connection.getTransaction(txSignature, { commitment });
16
- const computeUnits = [];
17
- const regex = new RegExp(`Program ${programId.toString()} consumed ([0-9]{0,6}) of ([0-9]{0,7}) compute units`);
18
- tx.meta.logMessages.forEach((logMessage) => {
19
- const match = logMessage.match(regex);
20
- if (match && match[1]) {
21
- computeUnits.push(match[1]);
22
- }
23
- });
24
- return computeUnits;
25
- });
26
- }
27
- exports.findComputeUnitConsumption = findComputeUnitConsumption;
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getTokenAddress = void 0;
4
- const spl_token_1 = require("@solana/spl-token");
5
- const web3_js_1 = require("@solana/web3.js");
6
- const getTokenAddress = (mintAddress, userPubKey) => {
7
- return spl_token_1.Token.getAssociatedTokenAddress(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, new web3_js_1.PublicKey(mintAddress), new web3_js_1.PublicKey(userPubKey));
8
- };
9
- exports.getTokenAddress = getTokenAddress;
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.promiseTimeout = void 0;
4
- function promiseTimeout(promise, timeoutMs) {
5
- let timeoutId;
6
- const timeoutPromise = new Promise((resolve) => {
7
- timeoutId = setTimeout(() => resolve(null), timeoutMs);
8
- });
9
- return Promise.race([promise, timeoutPromise]).then((result) => {
10
- clearTimeout(timeoutId);
11
- return result;
12
- });
13
- }
14
- exports.promiseTimeout = promiseTimeout;
package/src/util/tps.js DELETED
@@ -1,27 +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
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.estimateTps = void 0;
13
- function estimateTps(programId, connection, failed) {
14
- return __awaiter(this, void 0, void 0, function* () {
15
- let signatures = yield connection.getSignaturesForAddress(programId, undefined, 'finalized');
16
- if (failed) {
17
- signatures = signatures.filter((signature) => signature.err);
18
- }
19
- const numberOfSignatures = signatures.length;
20
- if (numberOfSignatures === 0) {
21
- return 0;
22
- }
23
- return (numberOfSignatures /
24
- (signatures[0].blockTime - signatures[numberOfSignatures - 1].blockTime));
25
- });
26
- }
27
- exports.estimateTps = estimateTps;
package/src/wallet.js DELETED
@@ -1,35 +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
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.Wallet = void 0;
13
- class Wallet {
14
- constructor(payer) {
15
- this.payer = payer;
16
- }
17
- signTransaction(tx) {
18
- return __awaiter(this, void 0, void 0, function* () {
19
- tx.partialSign(this.payer);
20
- return tx;
21
- });
22
- }
23
- signAllTransactions(txs) {
24
- return __awaiter(this, void 0, void 0, function* () {
25
- return txs.map((t) => {
26
- t.partialSign(this.payer);
27
- return t;
28
- });
29
- });
30
- }
31
- get publicKey() {
32
- return this.payer.publicKey;
33
- }
34
- }
35
- exports.Wallet = Wallet;