@zebec-network/exchange-card-sdk
Version:
An sdk for purchasing silver card in zebec
211 lines (210 loc) • 9.03 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NearService = void 0;
exports.createFunctionCall = createFunctionCall;
const assert_1 = __importDefault(require("assert"));
const bignumber_js_1 = require("bignumber.js");
const providers_1 = require("@near-js/providers");
const utils_1 = require("@near-js/utils");
const constants_1 = require("../constants");
const apiHelpers_1 = require("../helpers/apiHelpers");
/**
* Makes action payload for function call in near contract
* @param methodName method name
* @param args an object that will be passed as argument to method
* @param gas gas fee
* @param deposit deposit amount
*/
function createFunctionCall(methodName, args, gas, deposit) {
return {
type: "FunctionCall",
params: {
args,
deposit,
gas,
methodName,
},
};
}
class NearService {
wallet;
apiService;
provider;
constructor(wallet, apiConfig, options) {
this.wallet = wallet;
const sandbox = options?.sandbox ? options.sandbox : false;
this.apiService = new apiHelpers_1.ZebecCardAPIService(apiConfig, sandbox);
const url = sandbox ? constants_1.NEAR_RPC_URL.Sandbox : constants_1.NEAR_RPC_URL.Production;
this.provider = new providers_1.JsonRpcProvider({ url });
}
/**
* Fetches a quote for Bitcoin transfer.
*
* @returns {Promise<Quote>} A promise that resolves to a Quote object.
*/
async fetchQuote(symbol = "NEAR") {
const res = await this.apiService.fetchQuote(symbol);
return res;
}
/**
* Fetches the Bitcoin vault address.
*
* @returns {Promise<{ address: string }>} A promise that resolves to the vault address.
*/
async fetchVault(symbol = "NEAR") {
const data = await this.apiService.fetchVault(symbol);
return data;
}
async transferNear(params) {
const signerId = params.signerId ? params.signerId : this.wallet.signerId;
const fetchVault = await this.fetchVault();
const destination = fetchVault.address;
console.debug("destination:", destination);
const parsedAmount = (0, utils_1.parseNearAmount)(params.amount);
(0, assert_1.default)(parsedAmount, "Amount might be missing.");
const action = {
type: "Transfer",
params: {
deposit: parsedAmount,
},
};
const outcome = await this.wallet.signAndSendTransaction({
signerId: signerId,
receiverId: destination,
actions: [action],
});
return outcome;
}
async registerAccountInTokenContract(params) {
const signerId = params.signerId ? params.signerId : this.wallet.signerId;
const storageBalanceBoundsResult = await this.provider.query({
request_type: "call_function",
account_id: params.tokenContractId,
method_name: "storage_balance_bounds",
args_base64: Buffer.from(JSON.stringify({})).toString("base64"),
finality: "optimistic",
});
const storageBalanceBounds = JSON.parse(Buffer.from(storageBalanceBoundsResult.result).toString());
console.debug("storageBalanceBounds:", storageBalanceBounds);
const storageBalanceResult = await this.provider.query({
request_type: "call_function",
account_id: params.tokenContractId,
method_name: "storage_balance_of",
args_base64: Buffer.from(JSON.stringify({ account_id: signerId })).toString("base64"),
finality: "optimistic",
});
const storageBalance = JSON.parse(Buffer.from(storageBalanceResult.result).toString());
console.debug("storageBalance:", storageBalance);
const GAS = "30000000000000";
if (!storageBalance ||
(0, bignumber_js_1.BigNumber)(storageBalance.available).isLessThan(storageBalanceBounds.min)) {
const action = createFunctionCall("storage_deposit", {
account_id: signerId,
registration_only: false,
}, GAS, storageBalanceBounds.min);
const outcome = await this.wallet.signAndSendTransaction({
signerId: signerId,
receiverId: params.tokenContractId,
actions: [action],
});
return outcome;
}
return null;
}
async transferTokens(params) {
const signerId = params.signerId ? params.signerId : this.wallet.signerId;
console.log("signerId:", signerId);
const fetchVault = await this.fetchVault("NEAR-USDC");
const destination = fetchVault.address;
console.debug("destination:", destination);
let actions = [];
const GAS = "30000000000000";
const storageBalanceBoundsResult = await this.provider.query({
request_type: "call_function",
account_id: params.tokenContractId,
method_name: "storage_balance_bounds",
args_base64: Buffer.from(JSON.stringify({})).toString("base64"),
finality: "optimistic",
});
const storageBalanceBounds = JSON.parse(Buffer.from(storageBalanceBoundsResult.result).toString());
console.debug("storageBalanceBounds:", storageBalanceBounds);
const storageBalanceResult = await this.provider.query({
request_type: "call_function",
account_id: params.tokenContractId,
method_name: "storage_balance_of",
args_base64: Buffer.from(JSON.stringify({ account_id: destination })).toString("base64"),
finality: "optimistic",
});
const storageBalance = JSON.parse(Buffer.from(storageBalanceResult.result).toString());
console.debug("storageBalance:", storageBalance);
if (!storageBalance ||
(0, bignumber_js_1.BigNumber)(storageBalance.available).isLessThan(storageBalanceBounds.min)) {
const action = createFunctionCall("storage_deposit", {
account_id: destination,
registration_only: false,
}, GAS, storageBalanceBounds.max ? storageBalanceBounds.max : storageBalanceBounds.min);
actions.push(action);
}
const metadataResult = await this.provider.query({
request_type: "call_function",
finality: "final",
account_id: params.tokenContractId,
method_name: "ft_metadata",
args_base64: Buffer.from(JSON.stringify({})).toString("base64"),
});
const metadata = JSON.parse(Buffer.from(metadataResult.result).toString());
const tokenDecimals = metadata.decimals;
const parsedAmount = (0, bignumber_js_1.BigNumber)(params.amount)
.times((0, bignumber_js_1.BigNumber)(10).pow(tokenDecimals))
.toFixed(0);
const secutityDeposit = "1";
const transferAction = createFunctionCall("ft_transfer", {
receiver_id: destination,
amount: parsedAmount,
memo: null,
}, GAS, secutityDeposit);
actions.push(transferAction);
const outcome = await this.wallet.signAndSendTransaction({
signerId: signerId,
receiverId: params.tokenContractId,
actions,
});
return outcome;
}
async getNearBalance(params) {
const signerId = params.signerId ? params.signerId : this.wallet.signerId;
const result = await this.provider.query({
request_type: "view_account",
account_id: signerId,
finality: "final",
});
return { ...result };
}
async getTokenBalance(params) {
const signerId = params.signerId ? params.signerId : this.wallet.signerId;
const metadataResult = await this.provider.query({
request_type: "call_function",
finality: "final",
account_id: params.tokenContractId,
method_name: "ft_metadata",
args_base64: Buffer.from(JSON.stringify({})).toString("base64"),
});
const result = await this.provider.query({
request_type: "call_function",
finality: "final",
account_id: params.tokenContractId,
method_name: "ft_balance_of",
args_base64: Buffer.from(JSON.stringify({
account_id: signerId,
})).toString("base64"),
});
const metadata = JSON.parse(Buffer.from(metadataResult.result).toString());
const decimals = metadata.decimals;
const data = JSON.parse(Buffer.from(result.result).toString());
return (0, bignumber_js_1.BigNumber)(data).div((0, bignumber_js_1.BigNumber)(10).pow(decimals)).toFixed();
}
}
exports.NearService = NearService;