Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stellar address validation #2486

Merged
merged 8 commits into from
Mar 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 46 additions & 62 deletions packages/playground/src/components/withdraw_dialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,33 +13,43 @@
{{ selectedName?.charAt(0).toUpperCase() + selectedName!.slice(1) }} (withdraw fee is: {{ withdrawFee }} TFT)
</v-card-text>
<v-card-text>
<v-form v-model="isValidSwap">
<v-text-field
v-model="target"
:label="selectedName?.charAt(0).toUpperCase() + selectedName!.slice(1) + ' Target Wallet Address'"
:error-messages="targetError"
:disabled="validatingAddress"
:loading="validatingAddress"
:rules="[() => !!target || 'This field is required', swapAddressCheck]"
<FormValidator v-model="valid">
<InputValidator
:value="target"
:rules="[validators.required('This field is required'), () => swapAddressCheck()]"
:async-rules="[validateAddress]"
#="{ props: validationProps }"
>
</v-text-field>
<v-text-field
@paste.prevent
label="Amount (TFT)"
v-model="amount"
type="number"
onkeydown="javascript: return event.keyCode == 69 || /^\+$/.test(event.key) ? false : true"
<v-text-field
v-bind="{ ...validationProps }"
v-model="target"
:label="selectedName?.charAt(0).toUpperCase() + selectedName!.slice(1) + ' Target Wallet Address'"
:disabled="validatingAddress"
:loading="validationProps.loading"
>
</v-text-field>
</InputValidator>
<InputValidator
:value="amount"
#="{ props: validationProps }"
:rules="[
() => !!amount || 'This field is required',
() =>
(amount.toString().split('.').length > 1 ? amount.toString().split('.')[1].length <= 3 : true) ||
'Amount must have 3 decimals only',
() => amount >= 2 || 'Amount should be at least 2 TFT',
() => amount < freeBalance! || 'Amount cannot exceed balance',
]"
validators.required('This field is required'),
validators.min('Amount should be at least 2 TFT', 2),
validators.max( 'Amount cannot exceed balance',freeBalance!),
validators.isValidDecimalNumber(3,'Amount must have 3 decimals only')
]"
>
</v-text-field>
</v-form>
<v-text-field
v-bind="{ ...validationProps }"
@paste.prevent
label="Amount (TFT)"
v-model="amount"
type="number"
onkeydown="javascript: return event.keyCode == 69 || /^\+$/.test(event.key) ? false : true"
0oM4R marked this conversation as resolved.
Show resolved Hide resolved
>
</v-text-field>
</InputValidator>
</FormValidator>
</v-card-text>
<v-card-actions class="justify-end pb-4 px-6">
<v-btn variant="outlined" color="anchor" class="px-3" @click="closeDialog"> Close </v-btn>
Expand All @@ -48,7 +58,7 @@
color="secondary"
variant="outlined"
@click="withdrawTFT(target, amount)"
:disabled="!isValidSwap || validatingAddress"
:disabled="!valid || validatingAddress"
:loading="loadingWithdraw"
>Send</v-btn
>
Expand All @@ -59,20 +69,19 @@
</template>

<script setup lang="ts">
import { default as StellarSdk, StrKey } from "stellar-sdk";
import { StrKey } from "stellar-sdk";
import { onMounted, ref } from "vue";

import { useProfileManagerController } from "../components/profile_manager_controller.vue";
import { useProfileManager } from "../stores";
import { createCustomToast, ToastType } from "../utils/custom_toast";
import { getGrid } from "../utils/grid";

import { isValidStellarAddress } from "../utils/validators";
const withdrawDialog = ref(false);
const targetError = ref("");
const target = ref("");
const isValidSwap = ref(false);
const valid = ref(false);
const validatingAddress = ref(false);
const server = new StellarSdk.Server(window.env.STELLAR_HORIZON_URL);
const loadingWithdraw = ref(false);
const ProfileManagerController = useProfileManagerController();
const profileManager = useProfileManager();
Expand All @@ -94,53 +103,28 @@ onMounted(async () => {
function swapAddressCheck() {
targetError.value = "";
if (!target.value) {
isValidSwap.value = false;
return true;
return;
}
const isValid = StrKey.isValidEd25519PublicKey(target.value);
const blockedAddresses = [
"GBNOTAYUMXVO5QDYWYO2SOCOYIJ3XFIP65GKOQN7H65ZZSO6BK4SLWSC",
"GA2CWNBUHX7NZ3B5GR4I23FMU7VY5RPA77IUJTIXTTTGKYSKDSV6LUA4",
];
if (blockedAddresses.includes(target.value)) {
targetError.value = "Blocked Address";
return false;
return {
message: "Blocked Address",
};
}
if (!isValid || target.value.match(/\W/)) {
targetError.value = "invalid address";
isValidSwap.value = false;
return false;
return {
message: "Invalid address",
};
}
targetError.value = "";
validatingAddress.value = true;
isValidSwap.value = true;
if (props.selectedName == "stellar") validateAddress();
return true;
}

async function validateAddress() {
try {
// check if the account provided exists on stellar
const account = await server.loadAccount(target.value);
// check if the account provided has the appropriate trustlines
const includes = account.balances.find(
(b: { asset_code: string; asset_issuer: string }) =>
b.asset_code === "TFT" && b.asset_issuer === window.env.TFT_ASSET_ISSUER,
);
if (!includes) throw new Error("invalid trustline");
} catch (e) {
targetError.value =
(e as Error).message === "invalid trustline"
? "Address does not have a valid trustline to TFT"
: "Address not found";
validatingAddress.value = false;
isValidSwap.value = false;
return;
}

validatingAddress.value = false;
isValidSwap.value = true;
return;
if (props.selectedName == "stellar") return await isValidStellarAddress(target.value);
}

async function withdrawTFT(targetAddress: string, withdrawAmount: number) {
Expand Down
2 changes: 2 additions & 0 deletions packages/playground/src/dashboard/components/user_farms.vue
Original file line number Diff line number Diff line change
Expand Up @@ -99,12 +99,14 @@
<input-validator
:value="address"
:rules="[validators.required('Address is required.'), customStellarValidation]"
:async-rules="[validators.isValidStellarAddress]"
#="{ props }"
>
<v-text-field
v-model="address"
v-bind="props"
outlined
:loading="props.loading"
label="Stellar Wallet Address"
></v-text-field>
</input-validator>
Expand Down
32 changes: 32 additions & 0 deletions packages/playground/src/utils/validators.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import StellarSdk from "stellar-sdk";
import validator from "validator";
import type { Options } from "validator/lib/isBoolean";
import type { IsEmailOptions } from "validator/lib/isEmail";
import type { IsFQDNOptions } from "validator/lib/isFQDN";
import type { IsURLOptions } from "validator/lib/isURL";

import type { RuleReturn } from "@/components/input_validator.vue";

/**
* Checks if a value is empty, undefined, or null.
* @param msg - The error message to be returned if the value is empty.
Expand Down Expand Up @@ -739,3 +742,32 @@ export function isValidSSHKey(key: string): boolean {
const sshKeyRegex = /^(ssh-rsa|ssh-dss|ecdsa-[a-zA-Z0-9-]+|ssh-ed25519)\s+(\S+)\s+(\S+)/;
return sshKeyRegex.test(key);
}

export function isValidDecimalNumber(length: number, msg: string) {
return (value: string) => {
if (!(value.toString().split(".").length > 1 ? value.toString().split(".")[1].length <= length : true)) {
return {
message: msg,
};
}
};
}
export async function isValidStellarAddress(target: string): Promise<RuleReturn> {
const server = new StellarSdk.Server(window.env.STELLAR_HORIZON_URL);
try {
// check if the account provided exists on stellar
const account = await server.loadAccount(target);
// check if the account provided has the appropriate trustlines
const includes = account.balances.find(
(b: { asset_code: string; asset_issuer: string }) =>
b.asset_code === "TFT" && b.asset_issuer === window.env.TFT_ASSET_ISSUER,
);
if (!includes) throw new Error("Invalid trustline");
} catch (e) {
const message =
(e as Error).message === "Invalid trustline"
? "Address does not have a valid trustline to TFT"
: "Address not found";
return { message };
}
}
Loading