@drift-labs/sdk 0.2.0-master.15 → 0.2.0-master.18
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/lib/accounts/types.d.ts +1 -0
- package/lib/constants/numericConstants.d.ts +2 -0
- package/lib/constants/numericConstants.js +5 -3
- package/lib/events/types.js +1 -0
- package/lib/index.d.ts +5 -0
- package/lib/index.js +5 -0
- package/lib/math/position.js +1 -1
- package/lib/types.d.ts +2 -0
- package/package.json +1 -1
- package/src/addresses/marketAddresses.js +26 -0
- package/src/assert/assert.js +9 -0
- package/src/constants/banks.js +42 -0
- package/src/constants/markets.js +42 -0
- package/src/constants/numericConstants.js +41 -0
- package/src/constants/numericConstants.ts +10 -2
- package/src/events/eventList.js +77 -0
- package/src/events/eventSubscriber.js +139 -0
- package/src/events/fetchLogs.js +50 -0
- package/src/events/pollingLogProvider.js +64 -0
- package/src/events/sort.js +44 -0
- package/src/events/txEventCache.js +71 -0
- package/src/events/types.js +20 -0
- package/src/events/types.ts +1 -0
- package/src/events/webSocketLogProvider.js +41 -0
- package/src/examples/makeTradeExample.js +80 -0
- package/src/factory/bigNum.js +390 -0
- package/src/factory/oracleClient.js +20 -0
- package/src/index.ts +5 -0
- package/src/math/amm.js +369 -0
- package/src/math/auction.js +42 -0
- package/src/math/conversion.js +11 -0
- package/src/math/funding.js +248 -0
- package/src/math/oracles.js +26 -0
- package/src/math/position.ts +1 -1
- package/src/math/repeg.js +128 -0
- package/src/math/state.js +15 -0
- package/src/math/trade.js +253 -0
- package/src/math/utils.js +26 -0
- package/src/math/utils.js.map +1 -0
- package/src/oracles/oracleClientCache.js +19 -0
- package/src/oracles/pythClient.js +46 -0
- package/src/oracles/quoteAssetOracleClient.js +32 -0
- package/src/oracles/switchboardClient.js +69 -0
- package/src/oracles/types.js +2 -0
- package/src/orderParams.js +20 -0
- package/src/slot/SlotSubscriber.js +39 -0
- package/src/token/index.js +38 -0
- package/src/tokenFaucet.js +189 -0
- package/src/tx/types.js +2 -0
- package/src/tx/utils.js +17 -0
- package/src/types.js +125 -0
- package/src/types.ts +2 -0
- package/src/userName.js +20 -0
- package/src/util/computeUnits.js +27 -0
- package/src/util/getTokenAddress.js +9 -0
- package/src/util/promiseTimeout.js +14 -0
- package/src/util/tps.js +27 -0
- package/src/wallet.js +35 -0
|
@@ -0,0 +1,26 @@
|
|
|
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;
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
|
@@ -0,0 +1,19 @@
|
|
|
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;
|
|
@@ -0,0 +1,46 @@
|
|
|
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;
|
|
@@ -0,0 +1,32 @@
|
|
|
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;
|
|
@@ -0,0 +1,69 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
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;
|
|
@@ -0,0 +1,39 @@
|
|
|
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;
|
|
@@ -0,0 +1,38 @@
|
|
|
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;
|
|
@@ -0,0 +1,189 @@
|
|
|
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
ADDED
package/src/tx/utils.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
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/types.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DefaultOrderParams = exports.LiquidationType = exports.TradeSide = exports.isOneOfVariant = exports.isVariant = exports.OrderTriggerCondition = exports.OrderActionExplanation = exports.OrderAction = exports.OrderDiscountTier = exports.OrderStatus = exports.OrderType = exports.OracleSource = exports.DepositDirection = exports.PositionDirection = exports.BankBalanceType = exports.SwapDirection = void 0;
|
|
4
|
+
const _1 = require(".");
|
|
5
|
+
// # Utility Types / Enums / Constants
|
|
6
|
+
class SwapDirection {
|
|
7
|
+
}
|
|
8
|
+
exports.SwapDirection = SwapDirection;
|
|
9
|
+
SwapDirection.ADD = { add: {} };
|
|
10
|
+
SwapDirection.REMOVE = { remove: {} };
|
|
11
|
+
class BankBalanceType {
|
|
12
|
+
}
|
|
13
|
+
exports.BankBalanceType = BankBalanceType;
|
|
14
|
+
BankBalanceType.DEPOSIT = { deposit: {} };
|
|
15
|
+
BankBalanceType.BORROW = { borrow: {} };
|
|
16
|
+
class PositionDirection {
|
|
17
|
+
}
|
|
18
|
+
exports.PositionDirection = PositionDirection;
|
|
19
|
+
PositionDirection.LONG = { long: {} };
|
|
20
|
+
PositionDirection.SHORT = { short: {} };
|
|
21
|
+
class DepositDirection {
|
|
22
|
+
}
|
|
23
|
+
exports.DepositDirection = DepositDirection;
|
|
24
|
+
DepositDirection.DEPOSIT = { deposit: {} };
|
|
25
|
+
DepositDirection.WITHDRAW = { withdraw: {} };
|
|
26
|
+
class OracleSource {
|
|
27
|
+
}
|
|
28
|
+
exports.OracleSource = OracleSource;
|
|
29
|
+
OracleSource.PYTH = { pyth: {} };
|
|
30
|
+
OracleSource.SWITCHBOARD = { switchboard: {} };
|
|
31
|
+
OracleSource.QUOTE_ASSET = { quoteAsset: {} };
|
|
32
|
+
class OrderType {
|
|
33
|
+
}
|
|
34
|
+
exports.OrderType = OrderType;
|
|
35
|
+
OrderType.LIMIT = { limit: {} };
|
|
36
|
+
OrderType.TRIGGER_MARKET = { triggerMarket: {} };
|
|
37
|
+
OrderType.TRIGGER_LIMIT = { triggerLimit: {} };
|
|
38
|
+
OrderType.MARKET = { market: {} };
|
|
39
|
+
class OrderStatus {
|
|
40
|
+
}
|
|
41
|
+
exports.OrderStatus = OrderStatus;
|
|
42
|
+
OrderStatus.INIT = { init: {} };
|
|
43
|
+
OrderStatus.OPEN = { open: {} };
|
|
44
|
+
class OrderDiscountTier {
|
|
45
|
+
}
|
|
46
|
+
exports.OrderDiscountTier = OrderDiscountTier;
|
|
47
|
+
OrderDiscountTier.NONE = { none: {} };
|
|
48
|
+
OrderDiscountTier.FIRST = { first: {} };
|
|
49
|
+
OrderDiscountTier.SECOND = { second: {} };
|
|
50
|
+
OrderDiscountTier.THIRD = { third: {} };
|
|
51
|
+
OrderDiscountTier.FOURTH = { fourth: {} };
|
|
52
|
+
class OrderAction {
|
|
53
|
+
}
|
|
54
|
+
exports.OrderAction = OrderAction;
|
|
55
|
+
OrderAction.PLACE = { place: {} };
|
|
56
|
+
OrderAction.CANCEL = { cancel: {} };
|
|
57
|
+
OrderAction.EXPIRE = { expire: {} };
|
|
58
|
+
OrderAction.FILL = { fill: {} };
|
|
59
|
+
OrderAction.TRIGGER = { trigger: {} };
|
|
60
|
+
class OrderActionExplanation {
|
|
61
|
+
}
|
|
62
|
+
exports.OrderActionExplanation = OrderActionExplanation;
|
|
63
|
+
OrderActionExplanation.NONE = { none: {} };
|
|
64
|
+
OrderActionExplanation.BREACHED_MARGIN_REQUIREMENT = {
|
|
65
|
+
breachedMarginRequirement: {},
|
|
66
|
+
};
|
|
67
|
+
OrderActionExplanation.ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
|
|
68
|
+
oraclePriceBreachedLimitPrice: {},
|
|
69
|
+
};
|
|
70
|
+
OrderActionExplanation.MARKET_ORDER_FILLED_TO_LIMIT_PRICE = {
|
|
71
|
+
marketOrderFilledToLimitPrice: {},
|
|
72
|
+
};
|
|
73
|
+
class OrderTriggerCondition {
|
|
74
|
+
}
|
|
75
|
+
exports.OrderTriggerCondition = OrderTriggerCondition;
|
|
76
|
+
OrderTriggerCondition.ABOVE = { above: {} };
|
|
77
|
+
OrderTriggerCondition.BELOW = { below: {} };
|
|
78
|
+
function isVariant(object, type) {
|
|
79
|
+
return object.hasOwnProperty(type);
|
|
80
|
+
}
|
|
81
|
+
exports.isVariant = isVariant;
|
|
82
|
+
function isOneOfVariant(object, types) {
|
|
83
|
+
return types.reduce((result, type) => {
|
|
84
|
+
return result || object.hasOwnProperty(type);
|
|
85
|
+
}, false);
|
|
86
|
+
}
|
|
87
|
+
exports.isOneOfVariant = isOneOfVariant;
|
|
88
|
+
var TradeSide;
|
|
89
|
+
(function (TradeSide) {
|
|
90
|
+
TradeSide[TradeSide["None"] = 0] = "None";
|
|
91
|
+
TradeSide[TradeSide["Buy"] = 1] = "Buy";
|
|
92
|
+
TradeSide[TradeSide["Sell"] = 2] = "Sell";
|
|
93
|
+
})(TradeSide = exports.TradeSide || (exports.TradeSide = {}));
|
|
94
|
+
class LiquidationType {
|
|
95
|
+
}
|
|
96
|
+
exports.LiquidationType = LiquidationType;
|
|
97
|
+
LiquidationType.LIQUIDATE_PERP = { liquidatePerp: {} };
|
|
98
|
+
LiquidationType.LIQUIDATE_BORROW = { liquidateBorrow: {} };
|
|
99
|
+
LiquidationType.LIQUIDATE_BORROW_FOR_PERP_PNL = {
|
|
100
|
+
liquidateBorrowForPerpPnl: {},
|
|
101
|
+
};
|
|
102
|
+
LiquidationType.LIQUIDATE_PERP_PNL_FOR_DEPOSIT = {
|
|
103
|
+
liquidatePerpPnlForDeposit: {},
|
|
104
|
+
};
|
|
105
|
+
exports.DefaultOrderParams = {
|
|
106
|
+
orderType: OrderType.MARKET,
|
|
107
|
+
userOrderId: 0,
|
|
108
|
+
direction: PositionDirection.LONG,
|
|
109
|
+
baseAssetAmount: _1.ZERO,
|
|
110
|
+
price: _1.ZERO,
|
|
111
|
+
marketIndex: _1.ZERO,
|
|
112
|
+
reduceOnly: false,
|
|
113
|
+
postOnly: false,
|
|
114
|
+
immediateOrCancel: false,
|
|
115
|
+
triggerPrice: _1.ZERO,
|
|
116
|
+
triggerCondition: OrderTriggerCondition.ABOVE,
|
|
117
|
+
positionLimit: _1.ZERO,
|
|
118
|
+
oraclePriceOffset: _1.ZERO,
|
|
119
|
+
padding0: _1.ZERO,
|
|
120
|
+
padding1: _1.ZERO,
|
|
121
|
+
optionalAccounts: {
|
|
122
|
+
discountToken: false,
|
|
123
|
+
referrer: false,
|
|
124
|
+
},
|
|
125
|
+
};
|
package/src/types.ts
CHANGED
package/src/userName.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
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;
|