Skip to content

Commit

Permalink
feat: add nep4 standard 🦄
Browse files Browse the repository at this point in the history
  • Loading branch information
ilyar committed Jun 6, 2021
1 parent 013957a commit 5783892
Show file tree
Hide file tree
Showing 14 changed files with 526 additions and 69 deletions.
54 changes: 42 additions & 12 deletions example/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,32 @@
import * as near from '@4ire-labs/near-sdk'
import 'dotenv/config'

async function main() {
class NFTBasic extends near.NEP4Standard {
mintToken(owner_id: string, token_id: number): Promise<near.Outcome<void>> {
return this.callRaw({
methodName: 'mint_token',
args: {owner_id, token_id},
})
}
}

async function token() {
// NFT Basic
const ownerContract = near.custodianAccount(near.accountIdBySlug('nep4'))
const NFTContract = await near.Contract.connect(
NFTBasic,
near.accountIdBySlug('nep4'),
ownerContract,
)
const tokenId = +new Date
const mintTrx = await NFTContract.mintToken(ownerContract.accountId, tokenId)
console.log(`Minted NFT #${tokenId}:`, {
accountId: await NFTContract.getTokenOwner(tokenId),
transactionId: mintTrx.transactionId,
})
}

async function account() {
const deposit = '0.05'
const entropy = Buffer.from('0123456789ABCDEF')
const mnemonic = near.generateMnemonic(entropy)
Expand All @@ -27,28 +52,33 @@ async function main() {

// Normal Account
newAccount = near.mnemonicToAccount(mnemonic, near.accountIdBySlug(`sample${+new Date}`))
console.log('Normal Account:', {
await near.writeUnencryptedFileSystemKeyStore(newAccount)
trx = await near.createAccount(sender, newAccount, deposit)
console.log('Created normal account:', {
accountId: newAccount.accountId,
publicKey: newAccount.keyPair.publicKey.toString(),
transactionId: trx.transactionId,
})
await near.writeUnencryptedFileSystemKeyStore(newAccount)
trx = await near.createAccount(sender, newAccount, deposit)
console.log(trx.outcome.transaction.hash)
trx = await near.deleteAccount(newAccount)
console.log(trx.outcome.transaction.hash)
console.log('Deleted transactionId:', trx.transactionId)

// Custodial Account
newAccount = near.custodianAccount(near.accountIdBySlug(`sample${+new Date}`), sender)
console.log('Custodial Account:', {
trx = await near.createAccount(sender, newAccount, deposit)
await near.writeUnencryptedFileSystemKeyStore(newAccount)
console.log('Created custodial account:', {
accountId: newAccount.accountId,
publicKey: newAccount.keyPair.publicKey.toString(),
transactionId: trx.transactionId,
})
await near.writeUnencryptedFileSystemKeyStore(newAccount)
trx = await near.createAccount(sender, newAccount, deposit)
console.log(trx.outcome.transaction.hash)
console.log('state:', await near.stateAccount(newAccount))
trx = await near.deleteAccount(newAccount)
console.log(trx.outcome.transaction.hash)
console.log('Deleted transactionId:', trx.transactionId)
}

async function main() {
await token()
await account()
}

main().catch(console.error)

10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@4ire-labs/near-sdk",
"version": "1.0.0-beta.6",
"version": "1.0.0-beta.7",
"license": "UNLICENSED",
"description": "SDK for NEAR Protocol",
"keywords": [
Expand All @@ -18,7 +18,7 @@
},
"scripts": {
"coveralls": "coveralls < coverage/lcov.info",
"setup-near": "ts-node script/setup",
"setup-near": "ts-node util/setup",
"setup": "yarn up && yarn setup-near",
"up": "yarn down && docker-compose up --detach",
"down": "docker-compose down --volumes",
Expand All @@ -28,10 +28,10 @@
"docs": "typedoc --entryPoints src/index.ts --out build/docs",
"release": "yarn version --prerelease && yarn build && cd build && npm publish --access public",
"package": "mkdir -p build && json-mask 'name,version,license,description,repository,main,types,dependencies,keywords' package.json > build/package.json && cp readme.md build/readme.md",
"build": "yarn package && tsc",
"build": "yarn package && tsc || exit 0",
"qa": "yarn lint && yarn test && yarn test-example",
"test-example": "yarn build && yarn clean-example && cp test.env example/.env && cd example && yarn install && yarn test",
"test": "jest --coverage"
"test": "jest --detectOpenHandles --coverage"
},
"eslintConfig": {
"root": true,
Expand Down Expand Up @@ -87,7 +87,7 @@
},
"testTimeout": 20000,
"collectCoverageFrom": [
"src/*.ts"
"src/**/*.ts"
]
},
"devDependencies": {
Expand Down
87 changes: 74 additions & 13 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ npm install @4ire-labs/near-sdk

# Use

TL;DR run [example](https://github.com/4IRE-Labs/near-sdk/tree/main/example)

```dotenv
NEAR_ENV=testnet
NEAR_SENDER_ID=name.testnet
Expand All @@ -24,8 +26,46 @@ NEAR_SENDER_PRIVATE_KEY=ed25519:data
```typescript
import * as near from '@4ire-labs/near-sdk'
import 'dotenv/config'
```

## NFT

```typescript
class NFTBasic extends near.NEP4Standard {
mintToken(owner_id: string, token_id: number): Promise<near.Outcome<void>> {
return this.callRaw({
methodName: 'mint_token',
args: {owner_id, token_id},
})
}
}

async function main() {
async function token() {
const ownerContract = near.custodianAccount(near.accountIdBySlug('nep4'))
const NFTContract = await near.Contract.connect(
NFTBasic,
near.accountIdBySlug('nep4'),
ownerContract,
)
const tokenId = +new Date
const mintTrx = await NFTContract.mintToken(ownerContract.accountId, tokenId)
console.log(`Minted NFT #${tokenId}:`, {
accountId: await NFTContract.getTokenOwner(tokenId),
transactionId: mintTrx.transactionId,
})
}
```
```shell
Minted NFT #1622990248520: {
accountId: 'nep4.local',
transactionId: 'nep4.local:5d5o65nfmWWdbXXwtfM9mdqyR6E7X2VEPt586JeSHQK4'
}
```

## Account

```typescript
async function account() {
const deposit = '0.05'
const entropy = Buffer.from('0123456789ABCDEF')
const mnemonic = near.generateMnemonic(entropy)
Expand All @@ -51,31 +91,52 @@ async function main() {

// Normal Account
newAccount = near.mnemonicToAccount(mnemonic, near.accountIdBySlug(`sample${+new Date}`))
console.log('Normal Account:', {
await near.writeUnencryptedFileSystemKeyStore(newAccount)
trx = await near.createAccount(sender, newAccount, deposit)
console.log('Created normal account:', {
accountId: newAccount.accountId,
publicKey: newAccount.keyPair.publicKey.toString(),
transactionId: trx.transactionId,
})
await near.writeUnencryptedFileSystemKeyStore(newAccount)
trx = await near.createAccount(sender, newAccount, deposit)
console.log(trx.outcome.transaction.hash)
trx = await near.deleteAccount(newAccount)
console.log(trx.outcome.transaction.hash)
console.log('Deleted transactionId:', trx.transactionId)

// Custodial Account
newAccount = near.custodianAccount(near.accountIdBySlug(`sample${+new Date}`), sender)
console.log('Custodial Account:', {
trx = await near.createAccount(sender, newAccount, deposit)
await near.writeUnencryptedFileSystemKeyStore(newAccount)
console.log('Created custodial account:', {
accountId: newAccount.accountId,
publicKey: newAccount.keyPair.publicKey.toString(),
transactionId: trx.transactionId,
})
await near.writeUnencryptedFileSystemKeyStore(newAccount)
trx = await near.createAccount(sender, newAccount, deposit)
console.log(trx.outcome.transaction.hash)
console.log('state:', await near.stateAccount(newAccount))
trx = await near.deleteAccount(newAccount)
console.log(trx.outcome.transaction.hash)
console.log('Deleted transactionId:', trx.transactionId)
}
```

main().catch(console.error)
```shell
mnemonic: coral maze mimic half fat breeze thought choice drastic boss bacon middle
Implicit Account: {
accountId: '47d322f48bf873ad10c1b6ed2253518d3d3e0cad9a1a72a9c62b311400b72c7a',
publicKey: 'ed25519:5qNgFf7z5huxn11jgPJBnX2RGdmcmYodhLWnd71oozgH'
}
Sender Account: {
accountId: 'local',
publicKey: 'ed25519:7PGseFbWxvYVgZ89K1uTJKYoKetWs7BJtbyXDzfbAcqX'
}
Created normal account: {
accountId: 'sample1622990251089.local',
publicKey: 'ed25519:5qNgFf7z5huxn11jgPJBnX2RGdmcmYodhLWnd71oozgH',
transactionId: 'local:EpGPDCgKUbdGZQsx517bMSfiYSbCEqa49xrw1J6Voobk'
}
Deleted transactionId: sample1622990251089.local:CLnDXM7JAZqiWLWdthdrAB6SdBNmW9S9SFZvPKP8JmNn
Created custodial account: {
accountId: 'sample1622990256631.local',
publicKey: 'ed25519:7PGseFbWxvYVgZ89K1uTJKYoKetWs7BJtbyXDzfbAcqX',
transactionId: 'local:2TCrKv62VeViFdnQB9AknYpVXRuxVp4zA8rccAgNmctq'
}
Deleted transactionId: sample1622990256631.local:3gwSA1hEiZ3rWja3tPifZPbWhr7ok39FTfaNg4VrqNbP
```

## [🧙‍♂ Docs for develop 🧝‍♀️](https://github.com/4IRE-Labs/near-sdk/blob/main/docs/readme.md#develop-docs)
12 changes: 0 additions & 12 deletions script/setup.ts

This file was deleted.

26 changes: 25 additions & 1 deletion src/connect.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import * as api from 'near-api-js'
import * as config from './config'
import * as account from './account'

import {
Account,
} from 'near-api-js'
import {
Action,
} from 'near-api-js/src/transaction'
import {
Outcome,
transactionOutcome,
} from './transaction'
export interface ConnectParam {
networkId?: string
accountId?: string
Expand Down Expand Up @@ -50,3 +59,18 @@ export async function connectConfigByParam(param?: ConnectParam): Promise<api.Co
export async function newConnect(account: account.AccountNetwork): Promise<api.Near> {
return api.connect(await connectConfigByAccount(account))
}

export async function newAccountConnect(account: account.AccountNetwork): Promise<AccountConnect> {
const near = await newConnect(account)
return new AccountConnect(near.connection, account.accountId)
}

export class AccountConnect extends Account {
async sendTransaction<Type>(receiverId: string, actionList: Action[]): Promise<Outcome<Type>> {
const outcome = await this.signAndSendTransaction({
receiverId,
actions: actionList,
})
return transactionOutcome(outcome)
}
}
51 changes: 43 additions & 8 deletions src/contract.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,48 @@
import * as near from '.'
import * as dotenv from 'dotenv'
import * as path from 'path'
dotenv.config({ path: path.join(path.dirname(__dirname), 'test.env') })
import * as util from '../util'
import {toNear} from '.'
util.config()

test('createAndDeployContract', async () => {
jest.setTimeout(10000)
test('deploy without init', async () => {
const code = await near.fetchContract('near', 'mainnet')
expect(code).toBeTruthy()
const contract = near.generateAccount(`contract${+ new Date}`)
const contractAccount = await near.createAndDeployContract(contract, code, '100')
expect(contractAccount).toBeTruthy()
const accountId = `contract${+ new Date}`
const sender = near.parseAccountNetwork('local')
const contract = near.generateAccount(accountId)
const result = await near.deployContract(contract, code, {
sender,
amount: '10',
})
expect(result.account.accountId).toEqual(accountId)
expect(result.outcome.value).toEqual('')
})

test('deploy and init', async () => {
const code = await near.fetchContract('contract.paras.near', 'mainnet')
expect(code).toBeTruthy()
const accountId = `contract${+ new Date}`
const sender = near.parseAccountNetwork('local')
const contract = near.generateAccount(accountId)
const props = {
sender,
amount: '10',
init: {
methodName: 'init',
args: {
initialOwner: 'local',
},
}
}
let result = await near.deployContract<boolean>(contract, code, props)
let state = await result.account.state()
expect(toNear(state.amount)).toBeGreaterThanOrEqual(10)
expect(result.account.accountId).toEqual(accountId)
expect(result.outcome.value).toEqual(true)
// redeploy
props.sender = contract
delete props.init
result = await near.deployContract<boolean>(contract, code, props)
state = await result.account.state()
expect(toNear(state.amount)).toBeGreaterThanOrEqual(9)
expect(result.outcome.value).toEqual('')
})

0 comments on commit 5783892

Please sign in to comment.