Advertisement
jambtc

yii Sends Token. Save transaction and send notification

May 23rd, 2019
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.56 KB | None | 0 0
  1. /**
  2.      * Sends Token. Save transaction and send notification
  3.      * @param string $_POST['from'] the from ethereum address
  4.      * @param string $_POST['to'] the to ethereum address
  5.      * @param integer $_POST['amount'] the amount to be send
  6.      * @return 'id_token' 'data' 'status' 'token_price' 'wallet_address'  'url'
  7.      * @throws CJSON
  8.      */
  9.      public function actionSend()
  10.      {
  11.         $fromAccount = $_POST['from'];
  12.         $toAccount = $_POST['to'];
  13.         $amount = $_POST['amount'];
  14.  
  15.         $amountForContract = $amount * 100; //PERCHE' I DECIMALI DEL TOKEN SONO 2
  16.  
  17.         //Carico i parametri
  18.         $settings=NGatePay::loadSettings();
  19.         if ($settings === null || empty($settings->poa_url)){//} || empty($settings->poa_port)){
  20.             echo CJSON::encode(array(
  21.                 "error"=>'Errore: I parametri di configurazione POA non sono stati trovati',
  22.                 'id'=>time()
  23.             ));
  24.             exit;
  25.         }
  26.         //Carico i parametri del wallet
  27.         $wallets=Wallets::model()->findByAttributes(array('wallet_address'=>$fromAccount));
  28.         if ($wallets === null || empty($wallets->wallet_key)){//} || empty($wallets->poa_port)){
  29.             echo CJSON::encode(array(
  30.                 "error"=>'Errore: I parametri per la connessione al wallet non sono stati trovati',
  31.                 'id'=>time()
  32.             ));
  33.             exit;
  34.         }
  35.  
  36.         //CREO la transazione
  37.         /**
  38.           * This is fairly straightforward as per the ABI spec
  39.           * First you need the function selector for test(address,uint256) which is the first four bytes of the keccak-256 hash of that string, namely 0xba14d606.
  40.           * Then you need the address as a 32-byte word: 0x000000000000000000000000c5622be5861b7200cbace14e28b98c4ab77bd9b4.
  41.           * Finally you need amount (10000) as a 32-byte word: 0x0000000000000000000000000000000000000000000000000000000000002710
  42.         */
  43.  
  44.         $data_tx = [
  45.             'selector' => '0xa9059cbb000000000000000000000000', //ERC20 0xa9059cbb function transfer(address,uint256)
  46.             'address' => self::Encode("address", $toAccount), // $receiving_address è l'indirizzo destinatario,
  47.             'amount' => self::Encode("uint", $amountForContract), //$amount l'ammontare della transazione (da moltiplicare per 10^2)
  48.         ];
  49.  
  50.         $transaction = new Transaction([
  51.            'nonce' => '0x01'.time(),
  52.            'from' => $fromAccount, //indirizzo commerciante
  53.            'to' => $settings->poa_contractAddress, //indirizzo contratto
  54.            'gas' => '0x200b20',
  55.            //'gasPrice' => '0x9184e72a000', // gasPrice giusto?
  56.            'value' => '0',
  57.            'data' =>  $data_tx['selector'] . $data_tx['address'] . $data_tx['amount'],
  58.         ]);
  59.  
  60.         //$transaction->offsetSet('chainId', 6174); //IL NUMERO DELLA CHAIN PUO' VARIARE NEL TEMPO???
  61.         // E' IL CASO DI IMPOSTARLO NEL DB QUANDO SI INSERISCE L'URL DELLA POA?
  62.         $transaction->offsetSet('chainId', 1516); //1516 è QUELLA DEL MIO UFFICIO
  63.         #echo '<pre>Transazione: '.print_r($transaction,true).'</pre>';
  64.  
  65.         $signed_transaction = $transaction->sign(Utility::decryptURL($wallets->wallet_key)); // la chiave privata del wallet
  66.         #echo '<pre>Transazione firmata: '.print_r($signed_transaction,true).'</pre>';
  67.  
  68.         $web3 = new Web3($settings->poa_url); // indirizzo della poa
  69.         $eth = $web3->eth;
  70.         $eth->sendRawTransaction(sprintf('0x%s', $signed_transaction), function ($err, $tx) {
  71.             if ($err !== null) {
  72.                 echo CJSON::encode(array(
  73.                     "error"=>'Errore sendRawTransaction: '.$err->getMessage(),
  74.                     'id'=>time()
  75.                 ));
  76.                 exit;
  77.             }
  78.             //echo 'TX: ' . $tx;
  79.             //exit;
  80.             self::setTransaction($tx);
  81.         });
  82.         // elimino l'inserimento del balance, perchè non serve a nulla
  83.         // utilizzo questo campo per salvare il numero di blocco in cui presumibilmente avviene la transazione
  84.         $response = null;
  85.         $eth->getBlockByNumber('latest',false, function ($err, $block) use (&$response){
  86.             if ($err !== null) {
  87.                 throw new CHttpException(404,'Errore: '.$err->getMessage());
  88.             }
  89.             $response = $block;
  90.         });
  91.  
  92.         //salva la transazione ERC20
  93.         $timestamp = time();
  94.         $invoice_timestamp = $timestamp;
  95.  
  96.         //calcolo expiration time
  97.         $totalseconds = $settings->poa_expiration * 60; //poa_expiration è in minuti, * 60 lo trasforma in secondi
  98.         $expiration_timestamp = $timestamp + $totalseconds; //DEFAULT = 15 MINUTES
  99.  
  100.         //$rate = $this->getFiatRate(); // al momento il token è peggato 1/1 sull'euro
  101.         $rate = NGatePay::getFiatRate('token'); //
  102.  
  103.         $attributes = array(
  104.             'id_pos'    => 0,
  105.             'id_merchant' => Merchants::model()->findByAttributes(array('id_user'=>$wallets->id_user))->id_merchant,
  106.             'status'    => 'sending',
  107.             'type'  => 'token',
  108.             'token_price'   => - $amount,
  109.             'token_ricevuti'    => 0,
  110.             'fiat_price'        => $rate * $amount,
  111.             'currency'  => 'EUR',
  112.             'item_desc' => 'wallet',
  113.             'item_code' => '',
  114.             'invoice_timestamp' => $invoice_timestamp,
  115.             'expiration_timestamp' => $expiration_timestamp,
  116.             'rate' => $rate,
  117.             'wallet_address' => $fromAccount,
  118.             'balance' => hexdec($response->number), // numero del blocco in base 10
  119.             'txhash'    => self::getTransaction(),
  120.             'poa_url' => $settings->poa_url,    // QUESTI PARAMETRI SONO DA RIVEDERE!! pROBABILMENTE NON SERVONO PIù
  121.             'poa_port' => $settings->poa_port,  //
  122.             'id_bill' => 0
  123.         );
  124.         //salvo la transazione in db. Restituisce object
  125.         $tokens = NGatePay::saveETHTransaction($attributes);
  126.  
  127.         //salva la notifica
  128.         $notification = array(
  129.             'type_notification' => $tokens->type,
  130.             'id_merchant' => $tokens->id_merchant,
  131.             'id_tocheck' => $tokens->id_token,
  132.             'status' => $tokens->status,
  133.             'description' => ' '.ucfirst($tokens->type), //.' da '. $tokens->item_desc,
  134.             'url' => "index.php?r=tokens/view&id=".Utility::encryptURL($tokens->id_token),
  135.             'timestamp' => $timestamp,
  136.             'price' => - $rate * $amount,
  137.             'deleted' => 0,
  138.         );
  139.         NGatePay::save_notification($notification);
  140.  
  141.         //eseguo lo script che si occuperà in background di verificare lo stato dell'invoice appena creata...
  142.         $cmd = Yii::app()->basePath.DIRECTORY_SEPARATOR.'yiic send --id='.Utility::encryptURL($tokens->id_token);
  143.         NGatePay::execInBackground($cmd);
  144.  
  145.         //adesso posso uscire
  146.         $send_json = array(
  147.             'id' => $invoice_timestamp, //NECESSARIO PER IL SALVATAGGIO IN  indexedDB quando ritorna al Service Worker
  148.             'id_token' => Utility::encryptURL($tokens->id_token),
  149.             'data'  => date('d/m/Y H:i:s', $invoice_timestamp),
  150.             'status' => Yii::app()->controller->walletStatus($tokens->status),
  151.             //'token_price' => $tokens->token_price,
  152.             'token_price' => Yii::app()->controller->typePrice($tokens->token_price,$tokens->type),
  153.             'wallet_address' => substr($fromAccount,0,10).'...',
  154.             'url' => Yii::app()->createUrl("wallet/details")."&id=".Utility::encryptURL($tokens->id_token),
  155.         );
  156.         echo CJSON::encode($send_json);
  157.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement